} else if r > 0 {
at = rhs[r-1] // report at last value
}
- var err error_
- err.code = WrongResultCount
- err.errorf(at, "%s return values", qualifier)
- err.errorf(nopos, "have %s", check.typesSummary(operandTypes(rhs), false))
- err.errorf(nopos, "want %s", check.typesSummary(varTypes(lhs), false))
- check.report(&err)
+ err := check.newError(WrongResultCount)
+ err.addf(at, "%s return values", qualifier)
+ err.addf(nopos, "have %s", check.typesSummary(operandTypes(rhs), false))
+ err.addf(nopos, "want %s", check.typesSummary(varTypes(lhs), false))
+ err.report()
}
// initVars type-checks assignments of initialization expressions orig_rhs
// Note that NewTuple(params...) below is (*Tuple)(nil) if len(params) == 0, as desired.
tparams, params2 := check.renameTParams(pos, sig.TypeParams().list(), NewTuple(params...))
- var err error_
- targs = check.infer(pos, tparams, targs, params2.(*Tuple), args, reverse, &err)
+ err := check.newError(CannotInferTypeArgs)
+ targs = check.infer(pos, tparams, targs, params2.(*Tuple), args, reverse, err)
if targs == nil {
if !err.empty() {
- err.code = CannotInferTypeArgs
- check.report(&err)
+ err.report()
}
x.mode = invalid
return nil, nil
if sig.params != nil {
params = sig.params.vars
}
- var err error_
- err.code = WrongArgCount
- err.errorf(at, "%s arguments in call to %s", qualifier, call.Fun)
- err.errorf(nopos, "have %s", check.typesSummary(operandTypes(args), false))
- err.errorf(nopos, "want %s", check.typesSummary(varTypes(params), sig.variadic))
- check.report(&err)
+ err := check.newError(WrongArgCount)
+ err.addf(at, "%s arguments in call to %s", qualifier, call.Fun)
+ err.addf(nopos, "have %s", check.typesSummary(operandTypes(args), false))
+ err.addf(nopos, "want %s", check.typesSummary(varTypes(params), sig.variadic))
+ err.report()
return
}
// infer missing type arguments of callee and function arguments
if len(tparams) > 0 {
- var err error_
- targs = check.infer(call.Pos(), tparams, targs, sigParams, args, false, &err)
+ err := check.newError(CannotInferTypeArgs)
+ targs = check.infer(call.Pos(), tparams, targs, sigParams, args, false, err)
if targs == nil {
// TODO(gri) If infer inferred the first targs[:n], consider instantiating
// the call signature for better error messages/gopls behavior.
// Perhaps instantiate as much as we can, also for arguments.
// This will require changes to how infer returns its results.
if !err.empty() {
- check.errorf(err.pos(), CannotInferTypeArgs, "in call to %s, %s", call.Fun, err.msg(check.qualifier))
+ check.errorf(err.pos(), CannotInferTypeArgs, "in call to %s, %s", call.Fun, err.msg())
}
return
}
// We use "other" rather than "previous" here because
// the first declaration seen may not be textually
// earlier in the source.
- err.errorf(pos, "other declaration of %s", obj.Name())
+ err.addf(pos, "other declaration of %s", obj.Name())
}
}
// binding."
if obj.Name() != "_" {
if alt := scope.Insert(obj); alt != nil {
- var err error_
- err.code = DuplicateDecl
- err.errorf(obj, "%s redeclared in this block", obj.Name())
+ err := check.newError(DuplicateDecl)
+ err.addf(obj, "%s redeclared in this block", obj.Name())
err.recordAltDecl(alt)
- check.report(&err)
+ err.report()
return
}
obj.setScopePos(pos)
return
}
- var err error_
- err.code = InvalidDeclCycle
+ err := check.newError(InvalidDeclCycle)
if tname != nil {
- err.errorf(obj, "invalid recursive type %s", objName)
+ err.addf(obj, "invalid recursive type %s", objName)
} else {
- err.errorf(obj, "invalid cycle in declaration of %s", objName)
+ err.addf(obj, "invalid cycle in declaration of %s", objName)
}
for range cycle {
- err.errorf(obj, "%s refers to", objName)
+ err.addf(obj, "%s refers to", objName)
i++
if i >= len(cycle) {
i = 0
obj = cycle[i]
objName = name(obj)
}
- err.errorf(obj, "%s", objName)
- check.report(&err)
+ err.addf(obj, "%s", objName)
+ err.report()
}
// firstInSrc reports the index of the object with the "smallest"
// For historical consistency, we report the primary error on the
// method, and the alt decl on the field.
- var err error_
- err.code = DuplicateFieldAndMethod
- err.errorf(alt, "field and method with the same name %s", fld.name)
+ err := check.newError(DuplicateFieldAndMethod)
+ err.addf(alt, "field and method with the same name %s", fld.name)
err.recordAltDecl(fld)
- check.report(&err)
+ err.report()
}
}
}
}
// An error_ represents a type-checking error.
-// To report an error_, call Checker.report.
+// A new error_ is created with Checker.newError.
+// To report an error_, call error_.report.
type error_ struct {
- desc []errorDesc
- code Code
- soft bool // TODO(gri) eventually determine this from an error code
+ check *Checker
+ desc []errorDesc
+ code Code
+ soft bool // TODO(gri) eventually determine this from an error code
+}
+
+// newError returns a new error_ with the given error code.
+func (check *Checker) newError(code Code) *error_ {
+ if code == 0 {
+ panic("error code must not be 0")
+ }
+ return &error_{check: check, code: code}
}
// An errorDesc describes part of a type-checking error.
return err.desc[0].pos
}
-func (err *error_) msg(qf Qualifier) string {
+// msg returns the formatted error message without the primary error position pos().
+func (err *error_) msg() string {
if err.empty() {
return "no error"
}
+
var buf strings.Builder
for i := range err.desc {
p := &err.desc[i]
fmt.Fprintf(&buf, "%s: ", p.pos)
}
}
- buf.WriteString(sprintf(qf, false, p.format, p.args...))
+ buf.WriteString(err.check.sprintf(p.format, p.args...))
}
return buf.String()
}
-// String is for testing.
-func (err *error_) String() string {
- if err.empty() {
- return "no error"
- }
- return fmt.Sprintf("%s: %s", err.pos(), err.msg(nil))
-}
-
-// errorf adds formatted error information to err.
+// addf adds formatted error information to err.
// It may be called multiple times to provide additional information.
-func (err *error_) errorf(at poser, format string, args ...interface{}) {
+// The position of the first call to addf determines the position of the reported Error.
+// Subsequent calls to addf provide additional information in the form of additional lines
+// in the error message (types2) or continuation errors identified by a tab-indented error
+// message (go/types).
+func (err *error_) addf(at poser, format string, args ...interface{}) {
err.desc = append(err.desc, errorDesc{atPos(at), format, args})
}
return sprintf(qf, false, format, args...)
}
-func (check *Checker) report(err *error_) {
- if err.empty() {
- panic("no error to report")
- }
- check.err(err.pos(), err.code, err.msg(check.qualifier), err.soft)
-}
-
func (check *Checker) trace(pos syntax.Pos, format string, args ...interface{}) {
fmt.Printf("%s:\t%s%s\n",
pos,
fmt.Println(sprintf(check.qualifier, true, format, args...))
}
-func (check *Checker) err(at poser, code Code, msg string, soft bool) {
- switch code {
- case InvalidSyntaxTree:
- msg = "invalid syntax tree: " + msg
- case 0:
- panic("no error code provided")
+// report reports the error err, setting check.firstError if necessary.
+func (err *error_) report() {
+ if err.empty() {
+ panic("no error to report")
}
- // Cheap trick: Don't report errors with messages containing
- // "invalid operand" or "invalid type" as those tend to be
- // follow-on errors which don't add useful information. Only
- // exclude them if these strings are not at the beginning,
- // and only if we have at least one error already reported.
- if check.firstErr != nil && (strings.Index(msg, "invalid operand") > 0 || strings.Index(msg, "invalid type") > 0) {
- return
+ msg := err.msg()
+ code := err.code
+ assert(code != 0)
+ if code == InvalidSyntaxTree {
+ msg = "invalid syntax tree: " + msg
}
- pos := atPos(at)
-
// If we are encountering an error while evaluating an inherited
// constant initialization expression, pos is the position of in
// the original expression, and not of the currently declared
// constant identifier. Use the provided errpos instead.
// TODO(gri) We may also want to augment the error message and
// refer to the position (pos) in the original expression.
+ check := err.check
+ pos := err.pos()
if check.errpos.IsKnown() {
assert(check.iota != nil)
pos = check.errpos
}
+ if check.conf.Trace {
+ check.trace(pos, "ERROR: %s", msg)
+ }
+
+ // Cheap trick: Don't report errors with messages containing
+ // "invalid operand" or "invalid type" as those tend to be
+ // follow-on errors which don't add useful information. Only
+ // exclude them if these strings are not at the beginning,
+ // and only if we have at least one error already reported.
+ isInvalidErr := strings.Index(msg, "invalid operand") > 0 || strings.Index(msg, "invalid type") > 0
+ if check.firstErr != nil && isInvalidErr {
+ return
+ }
+
// If we have a URL for error codes, add a link to the first line.
- if code != 0 && check.conf.ErrorURL != "" {
+ if check.conf.ErrorURL != "" {
u := fmt.Sprintf(check.conf.ErrorURL, code)
if i := strings.Index(msg, "\n"); i >= 0 {
msg = msg[:i] + u + msg[i:]
}
}
- err := Error{pos, stripAnnotations(msg), msg, soft, code}
- if check.firstErr == nil {
- check.firstErr = err
+ e := Error{
+ Pos: pos,
+ Msg: stripAnnotations(msg),
+ Full: msg,
+ Soft: err.soft,
+ Code: code,
}
- if check.conf.Trace {
- check.trace(pos, "ERROR: %s", msg)
+ if check.firstErr == nil {
+ check.firstErr = e
}
f := check.conf.Error
if f == nil {
panic(bailout{}) // report only first error
}
- f(err)
+
+ // TODO(gri) If e contains \t-indented sub-errors,
+ // for go/types f must be called for each
+ // of those sub-errors.
+ f(e)
}
const (
}
func (check *Checker) error(at poser, code Code, msg string) {
- check.err(at, code, msg, false)
+ err := check.newError(code)
+ err.addf(at, "%s", msg)
+ err.report()
}
func (check *Checker) errorf(at poser, code Code, format string, args ...interface{}) {
- check.err(at, code, check.sprintf(format, args...), false)
+ err := check.newError(code)
+ err.addf(at, format, args...)
+ err.report()
}
func (check *Checker) softErrorf(at poser, code Code, format string, args ...interface{}) {
- check.err(at, code, check.sprintf(format, args...), true)
+ err := check.newError(code)
+ err.addf(at, format, args...)
+ err.soft = true
+ err.report()
}
func (check *Checker) versionErrorf(at poser, v goVersion, format string, args ...interface{}) {
msg := check.sprintf(format, args...)
- msg = fmt.Sprintf("%s requires %s or later", msg, v)
- check.err(at, UnsupportedFeature, msg, true)
+ err := check.newError(UnsupportedFeature)
+ err.addf(at, "%s requires %s or later", msg, v)
+ err.report()
}
// atPos reports the left (= start) position of at.
func TestError(t *testing.T) {
var err error_
want := "no error"
- if got := err.String(); got != want {
+ if got := err.msg(); got != want {
t.Errorf("empty error: got %q, want %q", got, want)
}
- want = "<unknown position>: foo 42"
- err.errorf(nopos, "foo %d", 42)
- if got := err.String(); got != want {
+ want = "foo 42"
+ err.addf(nopos, "foo %d", 42)
+ if got := err.msg(); got != want {
t.Errorf("simple error: got %q, want %q", got, want)
}
- want = "<unknown position>: foo 42\n\tbar 43"
- err.errorf(nopos, "bar %d", 43)
- if got := err.String(); got != want {
+ want = "foo 42\n\tbar 43"
+ err.addf(nopos, "bar %d", 43)
+ if got := err.msg(); got != want {
t.Errorf("simple error: got %q, want %q", got, want)
}
}
}
}
if allFailed {
- err.errorf(arg, "type %s of %s does not match %s (cannot infer %s)", targ, arg.expr, tpar, typeParamsString(tparams))
+ err.addf(arg, "type %s of %s does not match %s (cannot infer %s)", targ, arg.expr, tpar, typeParamsString(tparams))
return
}
}
// the more general CannotInferTypeArgs.
if inferred != tpar {
if reverse {
- err.errorf(arg, "inferred type %s for %s does not match type %s of %s", inferred, tpar, targ, arg.expr)
+ err.addf(arg, "inferred type %s for %s does not match type %s of %s", inferred, tpar, targ, arg.expr)
} else {
- err.errorf(arg, "type %s of %s does not match inferred type %s for %s", targ, arg.expr, inferred, tpar)
+ err.addf(arg, "type %s of %s does not match inferred type %s for %s", targ, arg.expr, inferred, tpar)
}
} else {
- err.errorf(arg, "type %s of %s does not match %s", targ, arg.expr, tpar)
+ err.addf(arg, "type %s of %s does not match %s", targ, arg.expr, tpar)
}
}
// TODO(gri) Type parameters that appear in the constraint and
// for which we have type arguments inferred should
// use those type arguments for a better error message.
- err.errorf(pos, "%s (type %s) does not satisfy %s", tpar, tx, tpar.Constraint())
+ err.addf(pos, "%s (type %s) does not satisfy %s", tpar, tx, tpar.Constraint())
return nil
}
case single && !core.tilde:
constraint := tpar.iface()
if m, _ := check.missingMethod(tx, constraint, true, func(x, y Type) bool { return u.unify(x, y, exact) }, &cause); m != nil {
// TODO(gri) better error message (see TODO above)
- err.errorf(pos, "%s (type %s) does not satisfy %s %s", tpar, tx, tpar.Constraint(), cause)
+ err.addf(pos, "%s (type %s) does not satisfy %s %s", tpar, tx, tpar.Constraint(), cause)
return nil
}
}
} else {
m := maxType(max, arg.typ)
if m == nil {
- err.errorf(arg, "mismatched types %s and %s (cannot infer %s)", max, arg.typ, tpar)
+ err.addf(arg, "mismatched types %s and %s (cannot infer %s)", max, arg.typ, tpar)
return nil
}
max = m
for i, typ := range inferred {
if typ == nil || isParameterized(tparams, typ) {
obj := tparams[i].obj
- err.errorf(pos, "cannot infer %s (%s)", obj.name, obj.pos)
+ err.addf(pos, "cannot infer %s (%s)", obj.name, obj.pos)
return nil
}
}
return
}
- var err error_
- err.code = InvalidInitCycle
- err.errorf(obj, "initialization cycle for %s", obj.Name())
+ err := check.newError(InvalidInitCycle)
+ err.addf(obj, "initialization cycle for %s", obj.Name())
// subtle loop: print cycle[i] for i = 0, n-1, n-2, ... 1 for len(cycle) = n
for i := len(cycle) - 1; i >= 0; i-- {
- err.errorf(obj, "%s refers to", obj.Name())
+ err.addf(obj, "%s refers to", obj.Name())
obj = cycle[i]
}
// print cycle[0] again to close the cycle
- err.errorf(obj, "%s", obj.Name())
- check.report(&err)
+ err.addf(obj, "%s", obj.Name())
+ err.report()
}
// ----------------------------------------------------------------------------
if name := s.Label.Value; name != "_" {
lbl := NewLabel(s.Label.Pos(), check.pkg, name)
if alt := all.Insert(lbl); alt != nil {
- var err error_
- err.code = DuplicateLabel
+ err := check.newError(DuplicateLabel)
err.soft = true
- err.errorf(lbl.pos, "label %s already declared", name)
+ err.addf(lbl.pos, "label %s already declared", name)
err.recordAltDecl(alt)
- check.report(&err)
+ err.report()
// ok to continue
} else {
b.insert(s)
// TODO(mdempsky): Pivot stack so we report the cycle from the top?
- var err error_
- err.code = InvalidInstanceCycle
+ err := check.newError(InvalidInstanceCycle)
obj0 := check.mono.vertices[v].obj
- err.errorf(obj0, "instantiation cycle:")
+ err.addf(obj0, "instantiation cycle:")
qf := RelativeTo(check.pkg)
for _, v := range stack {
default:
panic("unexpected type")
case *Named:
- err.errorf(edge.pos, "%s implicitly parameterized by %s", obj.Name(), TypeString(edge.typ, qf)) // secondary error, \t indented
+ err.addf(edge.pos, "%s implicitly parameterized by %s", obj.Name(), TypeString(edge.typ, qf)) // secondary error, \t indented
case *TypeParam:
- err.errorf(edge.pos, "%s instantiated as %s", obj.Name(), TypeString(edge.typ, qf)) // secondary error, \t indented
+ err.addf(edge.pos, "%s instantiated as %s", obj.Name(), TypeString(edge.typ, qf)) // secondary error, \t indented
}
}
- check.report(&err)
+ err.report()
}
// recordCanon records that tpar is the canonical type parameter
// the object may be imported into more than one file scope
// concurrently. See go.dev/issue/32154.)
if alt := fileScope.Lookup(name); alt != nil {
- var err error_
- err.code = DuplicateDecl
- err.errorf(s.LocalPkgName, "%s redeclared in this block", alt.Name())
+ err := check.newError(DuplicateDecl)
+ err.addf(s.LocalPkgName, "%s redeclared in this block", alt.Name())
err.recordAltDecl(alt)
- check.report(&err)
+ err.report()
} else {
fileScope.insert(name, obj)
check.dotImportMap[dotImportKey{fileScope, name}] = pkgName
for name, obj := range scope.elems {
if alt := pkg.scope.Lookup(name); alt != nil {
obj = resolve(name, obj)
- var err error_
- err.code = DuplicateDecl
+ err := check.newError(DuplicateDecl)
if pkg, ok := obj.(*PkgName); ok {
- err.errorf(alt, "%s already declared through import of %s", alt.Name(), pkg.Imported())
+ err.addf(alt, "%s already declared through import of %s", alt.Name(), pkg.Imported())
err.recordAltDecl(pkg)
} else {
- err.errorf(alt, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
+ err.addf(alt, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
// TODO(gri) dot-imported objects don't have a position; recordAltDecl won't print anything
err.recordAltDecl(obj)
}
- check.report(&err)
+ err.report()
}
}
}
params, variadic := check.collectParams(scope, ftyp.ParamList, true, scopePos)
results, _ := check.collectParams(scope, ftyp.ResultList, false, scopePos)
scope.Squash(func(obj, alt Object) {
- var err error_
- err.code = DuplicateDecl
- err.errorf(obj, "%s redeclared in this block", obj.Name())
+ err := check.newError(DuplicateDecl)
+ err.addf(obj, "%s redeclared in this block", obj.Name())
err.recordAltDecl(alt)
- check.report(&err)
+ err.report()
})
if recvPar != nil {
// (quadratic algorithm, but these lists tend to be very short)
for _, vt := range seen[val] {
if Identical(v.typ, vt.typ) {
- var err error_
- err.code = DuplicateCase
- err.errorf(&v, "duplicate case %s in expression switch", &v)
- err.errorf(vt.pos, "previous case")
- check.report(&err)
+ err := check.newError(DuplicateCase)
+ err.addf(&v, "duplicate case %s in expression switch", &v)
+ err.addf(vt.pos, "previous case")
+ err.report()
continue L
}
}
if T != nil {
Ts = TypeString(T, check.qualifier)
}
- var err error_
- err.code = DuplicateCase
- err.errorf(e, "duplicate case %s in type switch", Ts)
- err.errorf(other, "previous case")
- check.report(&err)
+ err := check.newError(DuplicateCase)
+ err.addf(e, "duplicate case %s in type switch", Ts)
+ err.addf(other, "previous case")
+ err.report()
continue L
}
}
// if T != nil {
// Ts = TypeString(T, check.qualifier)
// }
-// var err error_
-// err.code = _DuplicateCase
-// err.errorf(e, "duplicate case %s in type switch", Ts)
-// err.errorf(other, "previous case")
-// check.report(&err)
+// err := check.newError(_DuplicateCase)
+// err.addf(e, "duplicate case %s in type switch", Ts)
+// err.addf(other, "previous case")
+// err.report()
// continue L
// }
// seen[hash] = e
// with the same name as a result parameter is in scope at the place of the return."
for _, obj := range res.vars {
if alt := check.lookup(obj.name); alt != nil && alt != obj {
- var err error_
- err.code = OutOfScopeResult
- err.errorf(s, "result parameter %s not in scope at return", obj.name)
- err.errorf(alt, "inner declaration of %s", obj)
- check.report(&err)
+ err := check.newError(OutOfScopeResult)
+ err.addf(s, "result parameter %s not in scope at return", obj.name)
+ err.addf(alt, "inner declaration of %s", obj)
+ err.report()
// ok to continue
}
}
func (check *Checker) declareInSet(oset *objset, pos syntax.Pos, obj Object) bool {
if alt := oset.insert(obj); alt != nil {
- var err error_
- err.code = DuplicateDecl
- err.errorf(pos, "%s redeclared", obj.Name())
+ err := check.newError(DuplicateDecl)
+ err.addf(pos, "%s redeclared", obj.Name())
err.recordAltDecl(alt)
- check.report(&err)
+ err.report()
return false
}
return true
mpos[m] = pos
case explicit:
if check != nil {
- var err error_
- err.code = DuplicateDecl
- err.errorf(pos, "duplicate method %s", m.name)
- err.errorf(mpos[other.(*Func)], "other declaration of %s", m.name)
- check.report(&err)
+ err := check.newError(DuplicateDecl)
+ err.addf(pos, "duplicate method %s", m.name)
+ err.addf(mpos[other.(*Func)], "other declaration of %s", m.name)
+ err.report()
}
default:
// We have a duplicate method name in an embedded (not explicitly declared) method.
if check != nil {
check.later(func() {
if !check.allowVersion(m.pkg, pos, go1_14) || !Identical(m.typ, other.Type()) {
- var err error_
- err.code = DuplicateDecl
- err.errorf(pos, "duplicate method %s", m.name)
- err.errorf(mpos[other.(*Func)], "other declaration of %s", m.name)
- check.report(&err)
+ err := check.newError(DuplicateDecl)
+ err.addf(pos, "duplicate method %s", m.name)
+ err.addf(mpos[other.(*Func)], "other declaration of %s", m.name)
+ err.report()
}
}).describef(pos, "duplicate method check for %s", m.name)
}
} else if r > 0 {
at = rhs[r-1] // report at last value
}
- var err error_
- err.code = WrongResultCount
- err.errorf(at, "%s return values", qualifier)
- err.errorf(noposn, "have %s", check.typesSummary(operandTypes(rhs), false))
- err.errorf(noposn, "want %s", check.typesSummary(varTypes(lhs), false))
- check.report(&err)
+ err := check.newError(WrongResultCount)
+ err.addf(at, "%s return values", qualifier)
+ err.addf(noposn, "have %s", check.typesSummary(operandTypes(rhs), false))
+ err.addf(noposn, "want %s", check.typesSummary(varTypes(lhs), false))
+ err.report()
}
// initVars type-checks assignments of initialization expressions orig_rhs
// Note that NewTuple(params...) below is (*Tuple)(nil) if len(params) == 0, as desired.
tparams, params2 := check.renameTParams(pos, sig.TypeParams().list(), NewTuple(params...))
- var err error_
- targs = check.infer(atPos(pos), tparams, targs, params2.(*Tuple), args, reverse, &err)
+ err := check.newError(CannotInferTypeArgs)
+ targs = check.infer(atPos(pos), tparams, targs, params2.(*Tuple), args, reverse, err)
if targs == nil {
if !err.empty() {
- err.code = CannotInferTypeArgs
- check.report(&err)
+ err.report()
}
x.mode = invalid
return nil, nil
if sig.params != nil {
params = sig.params.vars
}
- err := newErrorf(at, WrongArgCount, "%s arguments in call to %s", qualifier, call.Fun)
- err.errorf(noposn, "have %s", check.typesSummary(operandTypes(args), false))
- err.errorf(noposn, "want %s", check.typesSummary(varTypes(params), sig.variadic))
- check.report(err)
+ err := check.newError(WrongArgCount)
+ err.addf(at, "%s arguments in call to %s", qualifier, call.Fun)
+ err.addf(noposn, "have %s", check.typesSummary(operandTypes(args), false))
+ err.addf(noposn, "want %s", check.typesSummary(varTypes(params), sig.variadic))
+ err.report()
return
}
// infer missing type arguments of callee and function arguments
if len(tparams) > 0 {
- var err error_
- targs = check.infer(call, tparams, targs, sigParams, args, false, &err)
+ err := check.newError(CannotInferTypeArgs)
+ targs = check.infer(call, tparams, targs, sigParams, args, false, err)
if targs == nil {
// TODO(gri) If infer inferred the first targs[:n], consider instantiating
// the call signature for better error messages/gopls behavior.
// Perhaps instantiate as much as we can, also for arguments.
// This will require changes to how infer returns its results.
if !err.empty() {
- check.errorf(err.posn(), CannotInferTypeArgs, "in call to %s, %s", call.Fun, err.msg(check.fset, check.qualifier))
+ check.errorf(err.posn(), CannotInferTypeArgs, "in call to %s, %s", call.Fun, err.msg())
}
return
}
}
// An error_ represents a type-checking error.
-// To report an error_, call Checker.report.
+// A new error_ is created with Checker.newError.
+// To report an error_, call error_.report.
type error_ struct {
- desc []errorDesc
- code Code
- soft bool // TODO(gri) eventually determine this from an error code
+ check *Checker
+ desc []errorDesc
+ code Code
+ soft bool // TODO(gri) eventually determine this from an error code
+}
+
+// newError returns a new error_ with the given error code.
+func (check *Checker) newError(code Code) *error_ {
+ if code == 0 {
+ panic("error code must not be 0")
+ }
+ return &error_{check: check, code: code}
}
// An errorDesc describes part of a type-checking error.
return err.desc[0].posn
}
-func (err *error_) msg(fset *token.FileSet, qf Qualifier) string {
+// msg returns the formatted error message without the primary error position pos().
+func (err *error_) msg() string {
if err.empty() {
return "no error"
}
+
var buf strings.Builder
for i := range err.desc {
p := &err.desc[i]
if i > 0 {
fmt.Fprint(&buf, "\n\t")
if p.posn.Pos().IsValid() {
- fmt.Fprintf(&buf, "%s: ", fset.Position(p.posn.Pos()))
+ fmt.Fprintf(&buf, "%s: ", err.check.fset.Position(p.posn.Pos()))
}
}
- buf.WriteString(sprintf(fset, qf, false, p.format, p.args...))
+ buf.WriteString(err.check.sprintf(p.format, p.args...))
}
return buf.String()
}
-// String is for testing.
-func (err *error_) String() string {
- if err.empty() {
- return "no error"
- }
- return fmt.Sprintf("%d: %s", err.posn().Pos(), err.msg(nil, nil))
-}
-
-// errorf adds formatted error information to err.
+// addf adds formatted error information to err.
// It may be called multiple times to provide additional information.
-func (err *error_) errorf(at positioner, format string, args ...interface{}) {
+// The position of the first call to addf determines the position of the reported Error.
+// Subsequent calls to addf provide additional information in the form of additional lines
+// in the error message (types2) or continuation errors identified by a tab-indented error
+// message (go/types).
+func (err *error_) addf(at positioner, format string, args ...interface{}) {
err.desc = append(err.desc, errorDesc{at, format, args})
}
fmt.Println(sprintf(check.fset, check.qualifier, true, format, args...))
}
-// Report records the error pointed to by errp, setting check.firstError if
-// necessary.
-func (check *Checker) report(errp *error_) {
- if errp.empty() {
+// report reports the error err, setting check.firstError if necessary.
+func (err *error_) report() {
+ if err.empty() {
panic("empty error details")
}
- msg := errp.msg(check.fset, check.qualifier)
- switch errp.code {
- case InvalidSyntaxTree:
- msg = "invalid AST: " + msg
- case 0:
- panic("no error code provided")
+ msg := err.msg()
+ code := err.code
+ assert(code != 0)
+ if code == InvalidSyntaxTree {
+ msg = "invalid syntax tree: " + msg
+ }
+
+ // If we are encountering an error while evaluating an inherited
+ // constant initialization expression, pos is the position of in
+ // the original expression, and not of the currently declared
+ // constant identifier. Use the provided errpos instead.
+ // TODO(gri) We may also want to augment the error message and
+ // refer to the position (pos) in the original expression.
+ check := err.check
+ posn := err.posn()
+ if check.errpos != nil && check.errpos.Pos().IsValid() {
+ assert(check.iota != nil)
+ posn = check.errpos
+ }
+
+ if check.conf._Trace {
+ check.trace(posn.Pos(), "ERROR: %s", msg)
+ }
+
+ // Cheap trick: Don't report errors with messages containing
+ // "invalid operand" or "invalid type" as those tend to be
+ // follow-on errors which don't add useful information. Only
+ // exclude them if these strings are not at the beginning,
+ // and only if we have at least one error already reported.
+ isInvalidErr := strings.Index(msg, "invalid operand") > 0 || strings.Index(msg, "invalid type") > 0
+ if check.firstErr != nil && isInvalidErr {
+ return
}
// If we have a URL for error codes, add a link to the first line.
- if errp.code != 0 && check.conf._ErrorURL != "" {
- u := fmt.Sprintf(check.conf._ErrorURL, errp.code)
+ if check.conf._ErrorURL != "" {
+ u := fmt.Sprintf(check.conf._ErrorURL, code)
if i := strings.Index(msg, "\n"); i >= 0 {
msg = msg[:i] + u + msg[i:]
} else {
}
}
- span := spanOf(errp.desc[0].posn)
+ span := spanOf(err.desc[0].posn)
e := Error{
Fset: check.fset,
Pos: span.pos,
- Msg: msg,
- Soft: errp.soft,
- go116code: errp.code,
+ Msg: stripAnnotations(msg),
+ Soft: err.soft,
+ go116code: code,
go116start: span.start,
go116end: span.end,
}
- // Cheap trick: Don't report errors with messages containing
- // "invalid operand" or "invalid type" as those tend to be
- // follow-on errors which don't add useful information. Only
- // exclude them if these strings are not at the beginning,
- // and only if we have at least one error already reported.
- isInvalidErr := strings.Index(e.Msg, "invalid operand") > 0 || strings.Index(e.Msg, "invalid type") > 0
- if check.firstErr != nil && isInvalidErr {
- return
- }
-
- e.Msg = stripAnnotations(e.Msg)
if check.errpos != nil {
// If we have an internal error and the errpos override is set, use it to
// augment our error positioning.
e.go116start = span.start
e.go116end = span.end
}
- err := e
if check.firstErr == nil {
- check.firstErr = err
- }
-
- if check.conf._Trace {
- pos := e.Pos
- msg := e.Msg
- check.trace(pos, "ERROR: %s", msg)
+ check.firstErr = e
}
f := check.conf.Error
if f == nil {
panic(bailout{}) // report only first error
}
- f(err)
+
+ // TODO(gri) If e contains \t-indented sub-errors,
+ // for go/types f must be called for each
+ // of those sub-errors.
+ f(e)
}
const (
invalidOp = "invalid operation: "
)
-// newErrorf creates a new error_ for later reporting with check.report.
-func newErrorf(at positioner, code Code, format string, args ...any) *error_ {
- return &error_{
- desc: []errorDesc{{at, format, args}},
- code: code,
- }
+// The positioner interface is used to extract the position of type-checker
+// errors.
+type positioner interface {
+ Pos() token.Pos
}
func (check *Checker) error(at positioner, code Code, msg string) {
- check.report(newErrorf(at, code, "%s", msg))
+ err := check.newError(code)
+ err.addf(at, "%s", msg)
+ err.report()
}
-func (check *Checker) errorf(at positioner, code Code, format string, args ...any) {
- check.report(newErrorf(at, code, format, args...))
+func (check *Checker) errorf(at positioner, code Code, format string, args ...interface{}) {
+ err := check.newError(code)
+ err.addf(at, format, args...)
+ err.report()
}
-func (check *Checker) softErrorf(at positioner, code Code, format string, args ...any) {
- err := newErrorf(at, code, format, args...)
+func (check *Checker) softErrorf(at positioner, code Code, format string, args ...interface{}) {
+ err := check.newError(code)
+ err.addf(at, format, args...)
err.soft = true
- check.report(err)
+ err.report()
}
func (check *Checker) versionErrorf(at positioner, v goVersion, format string, args ...interface{}) {
msg := check.sprintf(format, args...)
- var err *error_
- err = newErrorf(at, UnsupportedFeature, "%s requires %s or later", msg, v)
- check.report(err)
-}
-
-// The positioner interface is used to extract the position of type-checker
-// errors.
-type positioner interface {
- Pos() token.Pos
+ err := check.newError(UnsupportedFeature)
+ err.addf(at, "%s requires %s or later", msg, v)
+ err.report()
}
// posSpan holds a position range along with a highlighted position within that
func TestError(t *testing.T) {
var err error_
want := "no error"
- if got := err.String(); got != want {
+ if got := err.msg(); got != want {
t.Errorf("empty error: got %q, want %q", got, want)
}
- want = "0: foo 42"
- err.errorf(noposn, "foo %d", 42)
- if got := err.String(); got != want {
+ want = "foo 42"
+ err.addf(noposn, "foo %d", 42)
+ if got := err.msg(); got != want {
t.Errorf("simple error: got %q, want %q", got, want)
}
- want = "0: foo 42\n\tbar 43"
- err.errorf(noposn, "bar %d", 43)
- if got := err.String(); got != want {
+ want = "foo 42\n\tbar 43"
+ err.addf(noposn, "bar %d", 43)
+ if got := err.msg(); got != want {
t.Errorf("simple error: got %q, want %q", got, want)
}
}
n.Args[0] = arg
return false
}
- case "errorf":
- // rewrite check.errorf(pos, ...) to check.errorf(posn, ...)
+ case "addf":
+ // rewrite err.addf(pos, ...) to err.addf(posn, ...)
if isIdent(n.Args[0], "pos") {
pos := n.Args[0].Pos()
arg := newIdent(pos, "posn")
})
}
-// fixErrErrorfCall updates calls of the form err.errorf(obj, ...) to err.errorf(obj.Pos(), ...).
+// fixErrErrorfCall updates calls of the form err.addf(obj, ...) to err.addf(obj.Pos(), ...).
func fixErrErrorfCall(f *ast.File) {
ast.Inspect(f, func(n ast.Node) bool {
switch n := n.(type) {
if isIdent(selx.X, "err") {
switch selx.Sel.Name {
case "errorf":
- // rewrite err.errorf(obj, ... ) to err.errorf(obj.Pos(), ... )
+ // rewrite err.addf(obj, ... ) to err.addf(obj.Pos(), ... )
if ident, _ := n.Args[0].(*ast.Ident); ident != nil && ident.Name == "obj" {
pos := n.Args[0].Pos()
fun := &ast.SelectorExpr{X: ident, Sel: newIdent(pos, "Pos")}
}
}
if allFailed {
- err.errorf(arg, "type %s of %s does not match %s (cannot infer %s)", targ, arg.expr, tpar, typeParamsString(tparams))
+ err.addf(arg, "type %s of %s does not match %s (cannot infer %s)", targ, arg.expr, tpar, typeParamsString(tparams))
return
}
}
// the more general CannotInferTypeArgs.
if inferred != tpar {
if reverse {
- err.errorf(arg, "inferred type %s for %s does not match type %s of %s", inferred, tpar, targ, arg.expr)
+ err.addf(arg, "inferred type %s for %s does not match type %s of %s", inferred, tpar, targ, arg.expr)
} else {
- err.errorf(arg, "type %s of %s does not match inferred type %s for %s", targ, arg.expr, inferred, tpar)
+ err.addf(arg, "type %s of %s does not match inferred type %s for %s", targ, arg.expr, inferred, tpar)
}
} else {
- err.errorf(arg, "type %s of %s does not match %s", targ, arg.expr, tpar)
+ err.addf(arg, "type %s of %s does not match %s", targ, arg.expr, tpar)
}
}
// TODO(gri) Type parameters that appear in the constraint and
// for which we have type arguments inferred should
// use those type arguments for a better error message.
- err.errorf(posn, "%s (type %s) does not satisfy %s", tpar, tx, tpar.Constraint())
+ err.addf(posn, "%s (type %s) does not satisfy %s", tpar, tx, tpar.Constraint())
return nil
}
case single && !core.tilde:
constraint := tpar.iface()
if m, _ := check.missingMethod(tx, constraint, true, func(x, y Type) bool { return u.unify(x, y, exact) }, &cause); m != nil {
// TODO(gri) better error message (see TODO above)
- err.errorf(posn, "%s (type %s) does not satisfy %s %s", tpar, tx, tpar.Constraint(), cause)
+ err.addf(posn, "%s (type %s) does not satisfy %s %s", tpar, tx, tpar.Constraint(), cause)
return nil
}
}
} else {
m := maxType(max, arg.typ)
if m == nil {
- err.errorf(arg, "mismatched types %s and %s (cannot infer %s)", max, arg.typ, tpar)
+ err.addf(arg, "mismatched types %s and %s (cannot infer %s)", max, arg.typ, tpar)
return nil
}
max = m
for i, typ := range inferred {
if typ == nil || isParameterized(tparams, typ) {
obj := tparams[i].obj
- err.errorf(posn, "cannot infer %s (%s)", obj.name, obj.pos)
+ err.addf(posn, "cannot infer %s (%s)", obj.name, obj.pos)
return nil
}
}
// if T != nil {
// Ts = TypeString(T, check.qualifier)
// }
-// var err error_
-// err.code = DuplicateCase
-// err.errorf(e, "duplicate case %s in type switch", Ts)
-// err.errorf(other, "previous case")
-// check.report(&err)
+// err := check.newError(_DuplicateCase)
+// err.addf(e, "duplicate case %s in type switch", Ts)
+// err.addf(other, "previous case")
+// err.report()
// continue L
// }
// seen[hash] = e