// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This file implements various error reporters.

package types

import (
	
	
	
	
	
	
	
)

func assert( bool) {
	if ! {
		 := "assertion failed"
		// Include information about the assertion location. Due to panic recovery,
		// this location is otherwise buried in the middle of the panicking stack.
		if , , ,  := runtime.Caller(1);  {
			 = fmt.Sprintf("%s:%d: %s", , , )
		}
		panic()
	}
}

func unreachable() {
	panic("unreachable")
}

// An error_ represents a type-checking error.
// To report an error_, call Checker.report.
type error_ struct {
	desc []errorDesc
	code errorCode
	soft bool // TODO(gri) eventually determine this from an error code
}

// An errorDesc describes part of a type-checking error.
type errorDesc struct {
	posn   positioner
	format string
	args   []interface{}
}

func ( *error_) () bool {
	return .desc == nil
}

func ( *error_) () token.Pos {
	if .empty() {
		return token.NoPos
	}
	return .desc[0].posn.Pos()
}

func ( *error_) ( *token.FileSet,  Qualifier) string {
	if .empty() {
		return "no error"
	}
	var  bytes.Buffer
	for  := range .desc {
		 := &.desc[]
		if  > 0 {
			fmt.Fprint(&, "\n\t")
			if .posn.Pos().IsValid() {
				fmt.Fprintf(&, "%s: ", .Position(.posn.Pos()))
			}
		}
		.WriteString(sprintf(, , false, .format, .args...))
	}
	return .String()
}

// String is for testing.
func ( *error_) () string {
	if .empty() {
		return "no error"
	}
	return fmt.Sprintf("%d: %s", .pos(), .msg(nil, nil))
}

// errorf adds formatted error information to err.
// It may be called multiple times to provide additional information.
func ( *error_) ( token.Pos,  string,  ...interface{}) {
	.desc = append(.desc, errorDesc{atPos(), , })
}

func ( *Checker) ( *Package) string {
	// Qualify the package unless it's the package being type-checked.
	if  != .pkg {
		if .pkgPathMap == nil {
			.pkgPathMap = make(map[string]map[string]bool)
			.seenPkgMap = make(map[*Package]bool)
			.markImports(.pkg)
		}
		// If the same package name was used by multiple packages, display the full path.
		if len(.pkgPathMap[.name]) > 1 {
			return strconv.Quote(.path)
		}
		return .name
	}
	return ""
}

// markImports recursively walks pkg and its imports, to record unique import
// paths in pkgPathMap.
func ( *Checker) ( *Package) {
	if .seenPkgMap[] {
		return
	}
	.seenPkgMap[] = true

	,  := .pkgPathMap[.name]
	if ! {
		 = make(map[string]bool)
		.pkgPathMap[.name] = 
	}
	[.path] = true

	for ,  := range .imports {
		.()
	}
}

// check may be nil.
func ( *Checker) ( string,  ...any) string {
	var  *token.FileSet
	var  Qualifier
	if  != nil {
		 = .fset
		 = .qualifier
	}
	return sprintf(, , false, , ...)
}

func sprintf( *token.FileSet,  Qualifier,  bool,  string,  ...any) string {
	for ,  := range  {
		switch a := .(type) {
		case nil:
			 = "<nil>"
		case operand:
			panic("got operand instead of *operand")
		case *operand:
			 = operandString(, )
		case token.Pos:
			if  != nil {
				 = .Position().String()
			}
		case ast.Expr:
			 = ExprString()
		case []ast.Expr:
			var  bytes.Buffer
			.WriteByte('[')
			writeExprList(&, )
			.WriteByte(']')
			 = .String()
		case Object:
			 = ObjectString(, )
		case Type:
			 = typeString(, , )
		case []Type:
			var  bytes.Buffer
			.WriteByte('[')
			for ,  := range  {
				if  > 0 {
					.WriteString(", ")
				}
				.WriteString(typeString(, , ))
			}
			.WriteByte(']')
			 = .String()
		case []*TypeParam:
			var  bytes.Buffer
			.WriteByte('[')
			for ,  := range  {
				if  > 0 {
					.WriteString(", ")
				}
				.WriteString(typeString(, , )) // use typeString so we get subscripts when debugging
			}
			.WriteByte(']')
			 = .String()
		}
		[] = 
	}
	return fmt.Sprintf(, ...)
}

func ( *Checker) ( token.Pos,  string,  ...any) {
	fmt.Printf("%s:\t%s%s\n",
		.fset.Position(),
		strings.Repeat(".  ", .indent),
		sprintf(.fset, .qualifier, true, , ...),
	)
}

// dump is only needed for debugging
func ( *Checker) ( string,  ...any) {
	fmt.Println(sprintf(.fset, .qualifier, true, , ...))
}

// Report records the error pointed to by errp, setting check.firstError if
// necessary.
func ( *Checker) ( *error_) {
	if .empty() {
		panic("empty error details")
	}

	 := spanOf(.desc[0].posn)
	 := Error{
		Fset:       .fset,
		Pos:        .pos,
		Msg:        .msg(.fset, .qualifier),
		Soft:       .soft,
		go116code:  .code,
		go116start: .start,
		go116end:   .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.
	 := strings.Index(.Msg, "invalid operand") > 0 || strings.Index(.Msg, "invalid type") > 0
	if .firstErr != nil &&  {
		return
	}

	.Msg = stripAnnotations(.Msg)
	if .errpos != nil {
		// If we have an internal error and the errpos override is set, use it to
		// augment our error positioning.
		// TODO(rFindley) we may also want to augment the error message and refer
		// to the position (pos) in the original expression.
		 := spanOf(.errpos)
		.Pos = .pos
		.go116start = .start
		.go116end = .end
	}
	 := 

	if .firstErr == nil {
		.firstErr = 
	}

	if trace {
		 := .Pos
		 := .Msg
		.trace(, "ERROR: %s", )
	}

	 := .conf.Error
	if  == nil {
		panic(bailout{}) // report only first error
	}
	()
}

// newErrorf creates a new error_ for later reporting with check.report.
func newErrorf( positioner,  errorCode,  string,  ...any) *error_ {
	return &error_{
		desc: []errorDesc{{, , }},
		code: ,
	}
}

func ( *Checker) ( positioner,  errorCode,  string) {
	.report(newErrorf(, , ))
}

func ( *Checker) ( positioner,  errorCode,  string,  ...any) {
	.report(newErrorf(, , , ...))
}

func ( *Checker) ( positioner,  errorCode,  string,  ...any) {
	 := newErrorf(, , , ...)
	.soft = true
	.report()
}

func ( *Checker) ( positioner,  errorCode,  string,  string,  ...interface{}) {
	 := .sprintf(, ...)
	var  *error_
	if compilerErrorMessages {
		 = newErrorf(, , "%s requires %s or later (-lang was set to %s; check go.mod)", , , .conf.GoVersion)
	} else {
		 = newErrorf(, , "%s requires %s or later", , )
	}
	.report()
}

func ( *Checker) ( positioner,  string,  ...any) {
	.errorf(, 0, "invalid AST: "+, ...)
}

func ( *Checker) ( positioner,  errorCode,  string,  ...any) {
	.errorf(, , "invalid argument: "+, ...)
}

func ( *Checker) ( positioner,  errorCode,  string,  ...any) {
	.errorf(, , "invalid operation: "+, ...)
}

// The positioner interface is used to extract the position of type-checker
// errors.
type positioner interface {
	Pos() token.Pos
}

// posSpan holds a position range along with a highlighted position within that
// range. This is used for positioning errors, with pos by convention being the
// first position in the source where the error is known to exist, and start
// and end defining the full span of syntax being considered when the error was
// detected. Invariant: start <= pos < end || start == pos == end.
type posSpan struct {
	start, pos, end token.Pos
}

func ( posSpan) () token.Pos {
	return .pos
}

// inNode creates a posSpan for the given node.
// Invariant: node.Pos() <= pos < node.End() (node.End() is the position of the
// first byte after node within the source).
func inNode( ast.Node,  token.Pos) posSpan {
	,  := .Pos(), .End()
	if debug {
		assert( <=  &&  < )
	}
	return posSpan{, , }
}

// atPos wraps a token.Pos to implement the positioner interface.
type atPos token.Pos

func ( atPos) () token.Pos {
	return token.Pos()
}

// spanOf extracts an error span from the given positioner. By default this is
// the trivial span starting and ending at pos, but this span is expanded when
// the argument naturally corresponds to a span of source code.
func spanOf( positioner) posSpan {
	switch x := .(type) {
	case nil:
		panic("nil positioner")
	case posSpan:
		return 
	case ast.Node:
		 := .Pos()
		return posSpan{, , .End()}
	case *operand:
		if .expr != nil {
			 := .Pos()
			return posSpan{, , .expr.End()}
		}
		return posSpan{token.NoPos, token.NoPos, token.NoPos}
	default:
		 := .Pos()
		return posSpan{, , }
	}
}

// stripAnnotations removes internal (type) annotations from s.
func stripAnnotations( string) string {
	var  strings.Builder
	for ,  := range  {
		// strip #'s and subscript digits
		if  < '₀' || '₀'+10 <=  { // '₀' == U+2080
			.WriteRune()
		}
	}
	if .Len() < len() {
		return .String()
	}
	return 
}