// Copyright 2011 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 the Check function, which drives type-checking.

package types

import (
	
	
	
	
)

// debugging/development support
const (
	debug = false // leave on during development
	trace = false // turn on for detailed type resolution traces
)

// If Strict is set, the type-checker enforces additional
// rules not specified by the Go 1 spec, but which will
// catch guaranteed run-time errors if the respective
// code is executed. In other words, programs passing in
// Strict mode are Go 1 compliant, but not all Go 1 programs
// will pass in Strict mode. The additional rules are:
//
// - A type assertion x.(T) where T is an interface type
//   is invalid if any (statically known) method that exists
//   for both x and T have different signatures.
//
const strict = false

// exprInfo stores information about an untyped expression.
type exprInfo struct {
	isLhs bool // expression is lhs operand of a shift with delayed type-check
	mode  operandMode
	typ   *Basic
	val   constant.Value // constant value; or nil (if not a constant)
}

// A context represents the context within which an object is type-checked.
type context struct {
	decl          *declInfo              // package-level declaration whose init expression/function body is checked
	scope         *Scope                 // top-most scope for lookups
	pos           token.Pos              // if valid, identifiers are looked up as if at position pos (used by Eval)
	iota          constant.Value         // value of iota in a constant declaration; nil otherwise
	errpos        positioner             // if set, identifier position of a constant with inherited initializer
	sig           *Signature             // function signature if inside a function; nil otherwise
	isPanic       map[*ast.CallExpr]bool // set of panic call expressions (used for termination check)
	hasLabel      bool                   // set if a function makes use of labels (only ~1% of functions); unused outside functions
	hasCallOrRecv bool                   // set if an expression contains a function call or channel receive operation
}

// lookup looks up name in the current context and returns the matching object, or nil.
func ( *context) ( string) Object {
	,  := .scope.LookupParent(, .pos)
	return 
}

// An importKey identifies an imported package by import path and source directory
// (directory containing the file containing the import). In practice, the directory
// may always be the same, or may not matter. Given an (import path, directory), an
// importer must always return the same package (but given two different import paths,
// an importer may still return the same package by mapping them to the same package
// paths).
type importKey struct {
	path, dir string
}

// A Checker maintains the state of the type checker.
// It must be created with NewChecker.
type Checker struct {
	// package information
	// (initialized by NewChecker, valid for the life-time of checker)
	conf *Config
	fset *token.FileSet
	pkg  *Package
	*Info
	objMap map[Object]*declInfo       // maps package-level objects and (non-interface) methods to declaration info
	impMap map[importKey]*Package     // maps (import path, source directory) to (complete or fake) package
	posMap map[*Interface][]token.Pos // maps interface types to lists of embedded interface positions
	pkgCnt map[string]int             // counts number of imported packages with a given name (for better error messages)

	// information collected during type-checking of a set of package files
	// (initialized by Files, valid only for the duration of check.Files;
	// maps and lists are allocated on demand)
	files            []*ast.File                             // package files
	unusedDotImports map[*Scope]map[*Package]*ast.ImportSpec // unused dot-imported packages

	firstErr error                 // first error encountered
	methods  map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
	untyped  map[ast.Expr]exprInfo // map of expressions without final type
	delayed  []func()              // stack of delayed action segments; segments are processed in FIFO order
	finals   []func()              // list of final actions; processed at the end of type-checking the current set of files
	objPath  []Object              // path of object dependencies during type inference (for cycle reporting)

	// context within which the current object is type-checked
	// (valid only for the duration of type-checking a specific object)
	context

	// debugging
	indent int // indentation for tracing
}

// addUnusedImport adds the position of a dot-imported package
// pkg to the map of dot imports for the given file scope.
func ( *Checker) ( *Scope,  *Package,  *ast.ImportSpec) {
	 := .unusedDotImports
	if  == nil {
		 = make(map[*Scope]map[*Package]*ast.ImportSpec)
		.unusedDotImports = 
	}
	 := []
	if  == nil {
		 = make(map[*Package]*ast.ImportSpec)
		[] = 
	}
	[] = 
}

// addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
func ( *Checker) ( Object) {
	 := .decl
	if  == nil {
		return // not in a package-level init expression
	}
	if ,  := .objMap[]; ! {
		return // to is not a package-level object
	}
	.addDep()
}

func ( *Checker) ( ast.Expr,  bool,  operandMode,  *Basic,  constant.Value) {
	 := .untyped
	if  == nil {
		 = make(map[ast.Expr]exprInfo)
		.untyped = 
	}
	[] = exprInfo{, , , }
}

// later pushes f on to the stack of actions that will be processed later;
// either at the end of the current statement, or in case of a local constant
// or variable declaration, before the constant or variable is in scope
// (so that f still sees the scope before any new declarations).
func ( *Checker) ( func()) {
	.delayed = append(.delayed, )
}

// atEnd adds f to the list of actions processed at the end
// of type-checking, before initialization order computation.
// Actions added by atEnd are processed after any actions
// added by later.
func ( *Checker) ( func()) {
	.finals = append(.finals, )
}

// push pushes obj onto the object path and returns its index in the path.
func ( *Checker) ( Object) int {
	.objPath = append(.objPath, )
	return len(.objPath) - 1
}

// pop pops and returns the topmost object from the object path.
func ( *Checker) () Object {
	 := len(.objPath) - 1
	 := .objPath[]
	.objPath[] = nil
	.objPath = .objPath[:]
	return 
}

// NewChecker returns a new Checker instance for a given package.
// Package files may be added incrementally via checker.Files.
func ( *Config,  *token.FileSet,  *Package,  *Info) *Checker {
	// make sure we have a configuration
	if  == nil {
		 = new(Config)
	}

	// make sure we have an info struct
	if  == nil {
		 = new(Info)
	}

	return &Checker{
		conf:   ,
		fset:   ,
		pkg:    ,
		Info:   ,
		objMap: make(map[Object]*declInfo),
		impMap: make(map[importKey]*Package),
		posMap: make(map[*Interface][]token.Pos),
		pkgCnt: make(map[string]int),
	}
}

// initFiles initializes the files-specific portion of checker.
// The provided files must all belong to the same package.
func ( *Checker) ( []*ast.File) {
	// start with a clean slate (check.Files may be called multiple times)
	.files = nil
	.unusedDotImports = nil

	.firstErr = nil
	.methods = nil
	.untyped = nil
	.delayed = nil
	.finals = nil

	// determine package name and collect valid files
	 := .pkg
	for ,  := range  {
		switch  := .Name.Name; .name {
		case "":
			if  != "_" {
				.name = 
			} else {
				.errorf(.Name, _BlankPkgName, "invalid package name _")
			}
			fallthrough

		case :
			.files = append(.files, )

		default:
			.errorf(atPos(.Package), _MismatchedPkgName, "package %s; expected %s", , .name)
			// ignore this file
		}
	}
}

// A bailout panic is used for early termination.
type bailout struct{}

func ( *Checker) ( *error) {
	switch p := recover().(type) {
	case nil, bailout:
		// normal return or early exit
		* = .firstErr
	default:
		// re-panic
		panic()
	}
}

// Files checks the provided files as part of the checker's package.
func ( *Checker) ( []*ast.File) error { return .checkFiles() }

var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")

func ( *Checker) ( []*ast.File) ( error) {
	if .conf.FakeImportC && .conf.go115UsesCgo {
		return errBadCgo
	}

	defer .handleBailout(&)

	.initFiles()

	.collectObjects()

	.packageObjects()

	.processDelayed(0) // incl. all functions
	.processFinals()

	.initOrder()

	if !.conf.DisableUnusedImportCheck {
		.unusedImports()
	}

	.recordUntyped()

	.pkg.complete = true
	return
}

// processDelayed processes all delayed actions pushed after top.
func ( *Checker) ( int) {
	// If each delayed action pushes a new action, the
	// stack will continue to grow during this loop.
	// However, it is only processing functions (which
	// are processed in a delayed fashion) that may
	// add more actions (such as nested functions), so
	// this is a sufficiently bounded process.
	for  := ;  < len(.delayed); ++ {
		.delayed[]() // may append to check.delayed
	}
	assert( <= len(.delayed)) // stack must not have shrunk
	.delayed = .delayed[:]
}

func ( *Checker) () {
	 := len(.finals)
	for ,  := range .finals {
		() // must not append to check.finals
	}
	if len(.finals) !=  {
		panic("internal error: final action list grew")
	}
}

func ( *Checker) () {
	if !debug && .Types == nil {
		return // nothing to do
	}

	for ,  := range .untyped {
		if debug && isTyped(.typ) {
			.dump("%v: %s (type %s) is typed", .Pos(), , .typ)
			unreachable()
		}
		.recordTypeAndValue(, .mode, .typ, .val)
	}
}

func ( *Checker) ( ast.Expr,  operandMode,  Type,  constant.Value) {
	assert( != nil)
	assert( != nil)
	if  == invalid {
		return // omit
	}
	if  == constant_ {
		assert( != nil)
		assert( == Typ[Invalid] || isConstType())
	}
	if  := .Types;  != nil {
		[] = TypeAndValue{, , }
	}
}

func ( *Checker) ( ast.Expr,  *Signature) {
	// f must be a (possibly parenthesized) identifier denoting a built-in
	// (built-ins in package unsafe always produce a constant result and
	// we don't record their signatures, so we don't see qualified idents
	// here): record the signature for f and possible children.
	for {
		.recordTypeAndValue(, builtin, , nil)
		switch p := .(type) {
		case *ast.Ident:
			return // we're done
		case *ast.ParenExpr:
			 = .X
		default:
			unreachable()
		}
	}
}

func ( *Checker) ( ast.Expr,  [2]Type) {
	assert( != nil)
	if [0] == nil || [1] == nil {
		return
	}
	assert(isTyped([0]) && isTyped([1]) && (isBoolean([1]) || [1] == universeError))
	if  := .Types;  != nil {
		for {
			 := []
			assert(.Type != nil) // should have been recorded already
			 := .Pos()
			.Type = NewTuple(
				NewVar(, .pkg, "", [0]),
				NewVar(, .pkg, "", [1]),
			)
			[] = 
			// if x is a parenthesized expression (p.X), update p.X
			,  := .(*ast.ParenExpr)
			if  == nil {
				break
			}
			 = .X
		}
	}
}

func ( *Checker) ( *ast.Ident,  Object) {
	assert( != nil)
	if  := .Defs;  != nil {
		[] = 
	}
}

func ( *Checker) ( *ast.Ident,  Object) {
	assert( != nil)
	assert( != nil)
	if  := .Uses;  != nil {
		[] = 
	}
}

func ( *Checker) ( ast.Node,  Object) {
	assert( != nil)
	assert( != nil)
	if  := .Implicits;  != nil {
		[] = 
	}
}

func ( *Checker) ( *ast.SelectorExpr,  SelectionKind,  Type,  Object,  []int,  bool) {
	assert( != nil && ( == nil || len() > 0))
	.recordUse(.Sel, )
	if  := .Selections;  != nil {
		[] = &Selection{, , , , }
	}
}

func ( *Checker) ( ast.Node,  *Scope) {
	assert( != nil)
	assert( != nil)
	if  := .Scopes;  != nil {
		[] = 
	}
}