// Copyright 2014 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.

package types

import (
	
	
	
)

func ( *Checker) ( Object) {
	if  := .Pos(); .IsValid() {
		// We use "other" rather than "previous" here because
		// the first declaration seen may not be textually
		// earlier in the source.
		.errorf(, _DuplicateDecl, "\tother declaration of %s", .Name()) // secondary error, \t indented
	}
}

func ( *Checker) ( *Scope,  *ast.Ident,  Object,  token.Pos) {
	// spec: "The blank identifier, represented by the underscore
	// character _, may be used in a declaration like any other
	// identifier but the declaration does not introduce a new
	// binding."
	if .Name() != "_" {
		if  := .Insert();  != nil {
			.errorf(, _DuplicateDecl, "%s redeclared in this block", .Name())
			.reportAltDecl()
			return
		}
		.setScopePos()
	}
	if  != nil {
		.recordDef(, )
	}
}

// pathString returns a string of the form a->b-> ... ->g for a path [a, b, ... g].
func pathString( []Object) string {
	var  string
	for ,  := range  {
		if  > 0 {
			 += "->"
		}
		 += .Name()
	}
	return 
}

// objDecl type-checks the declaration of obj in its respective (file) context.
// For the meaning of def, see Checker.definedType, in typexpr.go.
func ( *Checker) ( Object,  *Named) {
	if trace {
		.trace(.Pos(), "-- checking %s (%s, objPath = %s)", , .color(), pathString(.objPath))
		.indent++
		defer func() {
			.indent--
			.trace(.Pos(), "=> %s (%s)", , .color())
		}()
	}

	// Checking the declaration of obj means inferring its type
	// (and possibly its value, for constants).
	// An object's type (and thus the object) may be in one of
	// three states which are expressed by colors:
	//
	// - an object whose type is not yet known is painted white (initial color)
	// - an object whose type is in the process of being inferred is painted grey
	// - an object whose type is fully inferred is painted black
	//
	// During type inference, an object's color changes from white to grey
	// to black (pre-declared objects are painted black from the start).
	// A black object (i.e., its type) can only depend on (refer to) other black
	// ones. White and grey objects may depend on white and black objects.
	// A dependency on a grey object indicates a cycle which may or may not be
	// valid.
	//
	// When objects turn grey, they are pushed on the object path (a stack);
	// they are popped again when they turn black. Thus, if a grey object (a
	// cycle) is encountered, it is on the object path, and all the objects
	// it depends on are the remaining objects on that path. Color encoding
	// is such that the color value of a grey object indicates the index of
	// that object in the object path.

	// During type-checking, white objects may be assigned a type without
	// traversing through objDecl; e.g., when initializing constants and
	// variables. Update the colors of those objects here (rather than
	// everywhere where we set the type) to satisfy the color invariants.
	if .color() == white && .Type() != nil {
		.setColor(black)
		return
	}

	switch .color() {
	case white:
		assert(.Type() == nil)
		// All color values other than white and black are considered grey.
		// Because black and white are < grey, all values >= grey are grey.
		// Use those values to encode the object's index into the object path.
		.setColor(grey + color(.push()))
		defer func() {
			.pop().setColor(black)
		}()

	case black:
		assert(.Type() != nil)
		return

	default:
		// Color values other than white or black are considered grey.
		fallthrough

	case grey:
		// We have a cycle.
		// In the existing code, this is marked by a non-nil type
		// for the object except for constants and variables whose
		// type may be non-nil (known), or nil if it depends on the
		// not-yet known initialization value.
		// In the former case, set the type to Typ[Invalid] because
		// we have an initialization cycle. The cycle error will be
		// reported later, when determining initialization order.
		// TODO(gri) Report cycle here and simplify initialization
		// order code.
		switch obj := .(type) {
		case *Const:
			if .cycle() || .typ == nil {
				.typ = Typ[Invalid]
			}

		case *Var:
			if .cycle() || .typ == nil {
				.typ = Typ[Invalid]
			}

		case *TypeName:
			if .cycle() {
				// break cycle
				// (without this, calling underlying()
				// below may lead to an endless loop
				// if we have a cycle for a defined
				// (*Named) type)
				.typ = Typ[Invalid]
			}

		case *Func:
			if .cycle() {
				// Don't set obj.typ to Typ[Invalid] here
				// because plenty of code type-asserts that
				// functions have a *Signature type. Grey
				// functions have their type set to an empty
				// signature which makes it impossible to
				// initialize a variable with the function.
			}

		default:
			unreachable()
		}
		assert(.Type() != nil)
		return
	}

	 := .objMap[]
	if  == nil {
		.dump("%v: %s should have been declared", .Pos(), )
		unreachable()
	}

	// save/restore current context and setup object context
	defer func( context) {
		.context = 
	}(.context)
	.context = context{
		scope: .file,
	}

	// Const and var declarations must not have initialization
	// cycles. We track them by remembering the current declaration
	// in check.decl. Initialization expressions depending on other
	// consts, vars, or functions, add dependencies to the current
	// check.decl.
	switch obj := .(type) {
	case *Const:
		.decl =  // new package-level const decl
		.constDecl(, .typ, .init, .inherited)
	case *Var:
		.decl =  // new package-level var decl
		.varDecl(, .lhs, .typ, .init)
	case *TypeName:
		// invalid recursive types are detected via path
		.typeDecl(, .typ, , .alias)
	case *Func:
		// functions may be recursive - no need to track dependencies
		.funcDecl(, )
	default:
		unreachable()
	}
}

// cycle checks if the cycle starting with obj is valid and
// reports an error if it is not.
func ( *Checker) ( Object) ( bool) {
	// The object map contains the package scope objects and the non-interface methods.
	if debug {
		 := .objMap[]
		 :=  != nil && (.fdecl == nil || .fdecl.Recv == nil) // exclude methods
		 := .Parent() == .pkg.scope
		if  !=  {
			.dump("%v: inconsistent object map for %s (isPkgObj = %v, inObjMap = %v)", .Pos(), , , )
			unreachable()
		}
	}

	// Count cycle objects.
	assert(.color() >= grey)
	 := .color() - grey // index of obj in objPath
	 := .objPath[:]
	 := 0 // number of (constant or variable) values in the cycle
	 := 0 // number of type definitions in the cycle
	for ,  := range  {
		switch obj := .(type) {
		case *Const, *Var:
			++
		case *TypeName:
			// Determine if the type name is an alias or not. For
			// package-level objects, use the object map which
			// provides syntactic information (which doesn't rely
			// on the order in which the objects are set up). For
			// local objects, we can rely on the order, so use
			// the object's predicate.
			// TODO(gri) It would be less fragile to always access
			// the syntactic information. We should consider storing
			// this information explicitly in the object.
			var  bool
			if  := .objMap[];  != nil {
				 = .alias // package-level object
			} else {
				 = .IsAlias() // function local object
			}
			if ! {
				++
			}
		case *Func:
			// ignored for now
		default:
			unreachable()
		}
	}

	if trace {
		.trace(.Pos(), "## cycle detected: objPath = %s->%s (len = %d)", pathString(), .Name(), len())
		.trace(.Pos(), "## cycle contains: %d values, %d type definitions", , )
		defer func() {
			if  {
				.trace(.Pos(), "=> error: cycle is invalid")
			}
		}()
	}

	// A cycle involving only constants and variables is invalid but we
	// ignore them here because they are reported via the initialization
	// cycle check.
	if  == len() {
		return false
	}

	// A cycle involving only types (and possibly functions) must have at least
	// one type definition to be permitted: If there is no type definition, we
	// have a sequence of alias type names which will expand ad infinitum.
	if  == 0 &&  > 0 {
		return false // cycle is permitted
	}

	.cycleError()

	return true
}

type typeInfo uint

// validType verifies that the given type does not "expand" infinitely
// producing a cycle in the type graph. Cycles are detected by marking
// defined types.
// (Cycles involving alias types, as in "type A = [10]A" are detected
// earlier, via the objDecl cycle detection mechanism.)
func ( *Checker) ( Type,  []Object) typeInfo {
	const (
		 typeInfo = iota
		
		
		
	)

	switch t := .(type) {
	case *Array:
		return .(.elem, )

	case *Struct:
		for ,  := range .fields {
			if .(.typ, ) ==  {
				return 
			}
		}

	case *Interface:
		for ,  := range .embeddeds {
			if .(, ) ==  {
				return 
			}
		}

	case *Named:
		// don't touch the type if it is from a different package or the Universe scope
		// (doing so would lead to a race condition - was issue #35049)
		if .obj.pkg != .pkg {
			return 
		}

		// don't report a 2nd error if we already know the type is invalid
		// (e.g., if a cycle was detected earlier, via Checker.underlying).
		if .underlying == Typ[Invalid] {
			.info = 
			return 
		}

		switch .info {
		case :
			.info = 
			.info = .(.orig, append(, .obj)) // only types of current package added to path
		case :
			// cycle detected
			for ,  := range  {
				if .obj.pkg != .pkg {
					panic("internal error: type cycle via package-external type")
				}
				if  == .obj {
					.cycleError([:])
					.info = 
					.underlying = Typ[Invalid]
					return .info
				}
			}
			panic("internal error: cycle start not found")
		}
		return .info
	}

	return 
}

// cycleError reports a declaration cycle starting with
// the object in cycle that is "first" in the source.
func ( *Checker) ( []Object) {
	// TODO(gri) Should we start with the last (rather than the first) object in the cycle
	//           since that is the earliest point in the source where we start seeing the
	//           cycle? That would be more consistent with other error messages.
	 := firstInSrc()
	 := []
	.errorf(, _InvalidDeclCycle, "illegal cycle in declaration of %s", .Name())
	for range  {
		.errorf(, _InvalidDeclCycle, "\t%s refers to", .Name()) // secondary error, \t indented
		++
		if  >= len() {
			 = 0
		}
		 = []
	}
	.errorf(, _InvalidDeclCycle, "\t%s", .Name())
}

// firstInSrc reports the index of the object with the "smallest"
// source position in path. path must not be empty.
func firstInSrc( []Object) int {
	,  := 0, [0].Pos()
	for ,  := range [1:] {
		if .Pos() <  {
			,  = +1, .Pos()
		}
	}
	return 
}

type (
	decl interface {
		node() ast.Node
	}

	importDecl struct{ spec *ast.ImportSpec }
	constDecl  struct {
		spec      *ast.ValueSpec
		iota      int
		typ       ast.Expr
		init      []ast.Expr
		inherited bool
	}
	varDecl  struct{ spec *ast.ValueSpec }
	typeDecl struct{ spec *ast.TypeSpec }
	funcDecl struct{ decl *ast.FuncDecl }
)

func ( importDecl) () ast.Node { return .spec }
func ( constDecl) () ast.Node  { return .spec }
func ( varDecl) () ast.Node    { return .spec }
func ( typeDecl) () ast.Node   { return .spec }
func ( funcDecl) () ast.Node   { return .decl }

func ( *Checker) ( []ast.Decl,  func(decl)) {
	for ,  := range  {
		.walkDecl(, )
	}
}

func ( *Checker) ( ast.Decl,  func(decl)) {
	switch d := .(type) {
	case *ast.BadDecl:
		// ignore
	case *ast.GenDecl:
		var  *ast.ValueSpec // last ValueSpec with type or init exprs seen
		for ,  := range .Specs {
			switch s := .(type) {
			case *ast.ImportSpec:
				(importDecl{})
			case *ast.ValueSpec:
				switch .Tok {
				case token.CONST:
					// determine which initialization expressions to use
					 := true
					switch {
					case .Type != nil || len(.Values) > 0:
						 = 
						 = false
					case  == nil:
						 = new(ast.ValueSpec) // make sure last exists
						 = false
					}
					.arityMatch(, )
					(constDecl{spec: , iota: , typ: .Type, init: .Values, inherited: })
				case token.VAR:
					.arityMatch(, nil)
					(varDecl{})
				default:
					.invalidAST(, "invalid token %s", .Tok)
				}
			case *ast.TypeSpec:
				(typeDecl{})
			default:
				.invalidAST(, "unknown ast.Spec node %T", )
			}
		}
	case *ast.FuncDecl:
		(funcDecl{})
	default:
		.invalidAST(, "unknown ast.Decl node %T", )
	}
}

func ( *Checker) ( *Const, ,  ast.Expr,  bool) {
	assert(.typ == nil)

	// use the correct value of iota
	defer func( constant.Value,  positioner) {
		.iota = 
		.errpos = 
	}(.iota, .errpos)
	.iota = .val
	.errpos = nil

	// provide valid constant value under all circumstances
	.val = constant.MakeUnknown()

	// determine type, if any
	if  != nil {
		 := .typ()
		if !isConstType() {
			// don't report an error if the type is an invalid C (defined) type
			// (issue #22090)
			if .Underlying() != Typ[Invalid] {
				.errorf(, _InvalidConstType, "invalid constant type %s", )
			}
			.typ = Typ[Invalid]
			return
		}
		.typ = 
	}

	// check initialization
	var  operand
	if  != nil {
		if  {
			// The initialization expression is inherited from a previous
			// constant declaration, and (error) positions refer to that
			// expression and not the current constant declaration. Use
			// the constant identifier position for any errors during
			// init expression evaluation since that is all we have
			// (see issues #42991, #42992).
			.errpos = atPos(.pos)
		}
		.expr(&, )
	}
	.initConst(, &)
}

func ( *Checker) ( *Var,  []*Var, ,  ast.Expr) {
	assert(.typ == nil)

	// determine type, if any
	if  != nil {
		.typ = .typ()
		// We cannot spread the type to all lhs variables if there
		// are more than one since that would mark them as checked
		// (see Checker.objDecl) and the assignment of init exprs,
		// if any, would not be checked.
		//
		// TODO(gri) If we have no init expr, we should distribute
		// a given type otherwise we need to re-evalate the type
		// expr for each lhs variable, leading to duplicate work.
	}

	// check initialization
	if  == nil {
		if  == nil {
			// error reported before by arityMatch
			.typ = Typ[Invalid]
		}
		return
	}

	if  == nil || len() == 1 {
		assert( == nil || [0] == )
		var  operand
		.expr(&, )
		.initVar(, &, "variable declaration")
		return
	}

	if debug {
		// obj must be one of lhs
		 := false
		for ,  := range  {
			if  ==  {
				 = true
				break
			}
		}
		if ! {
			panic("inconsistent lhs")
		}
	}

	// We have multiple variables on the lhs and one init expr.
	// Make sure all variables have been given the same type if
	// one was specified, otherwise they assume the type of the
	// init expression values (was issue #15755).
	if  != nil {
		for ,  := range  {
			.typ = .typ
		}
	}

	.initVars(, []ast.Expr{}, token.NoPos)
}

// underlying returns the underlying type of typ; possibly by following
// forward chains of named types. Such chains only exist while named types
// are incomplete. If an underlying type is found, resolve the chain by
// setting the underlying type for each defined type in the chain before
// returning it.
//
// If no underlying type is found, a cycle error is reported and Typ[Invalid]
// is used as underlying type for each defined type in the chain and returned
// as result.
func ( *Checker) ( Type) Type {
	// If typ is not a defined type, its underlying type is itself.
	,  := .(*Named)
	if  == nil {
		return  // nothing to do
	}

	// If the underlying type of a defined type is not a defined
	// type, then that is the desired underlying type.
	 = .underlying
	,  := .(*Named)
	if  == nil {
		return  // common case
	}

	// Otherwise, follow the forward chain.
	 := map[*Named]int{: 0}
	 := []Object{.obj}
	for {
		 = .underlying
		,  := .(*Named)
		if  == nil {
			break // end of chain
		}

		[] = len()
		 = append(, .obj)
		 = 

		if ,  := [];  {
			// cycle
			.cycleError([:])
			 = Typ[Invalid]
			break
		}
	}

	for  := range  {
		// We should never have to update the underlying type of an imported type;
		// those underlying types should have been resolved during the import.
		// Also, doing so would lead to a race condition (was issue #31749).
		if .obj.pkg != .pkg {
			panic("internal error: imported type with unresolved underlying type")
		}
		.underlying = 
	}

	return 
}

func ( *Named) ( Type) {
	if  != nil {
		.underlying = 
	}
}

func ( *Checker) ( *TypeName,  ast.Expr,  *Named,  bool) {
	assert(.typ == nil)

	.later(func() {
		.validType(.typ, nil)
	})

	if  {

		.typ = Typ[Invalid]
		.typ = .typ()

	} else {

		 := &Named{obj: }
		.setUnderlying()
		.typ =  // make sure recursive type declarations terminate

		// determine underlying type of named
		.orig = .definedType(, )

		// The underlying type of named may be itself a named type that is
		// incomplete:
		//
		//	type (
		//		A B
		//		B *C
		//		C A
		//	)
		//
		// The type of C is the (named) type of A which is incomplete,
		// and which has as its underlying type the named type B.
		// Determine the (final, unnamed) underlying type by resolving
		// any forward chain.
		.underlying = .underlying()

	}

	.addMethodDecls()
}

func ( *Checker) ( *TypeName) {
	// get associated methods
	// (Checker.collectObjects only collects methods with non-blank names;
	// Checker.resolveBaseTypeName ensures that obj is not an alias name
	// if it has attached methods.)
	 := .methods[]
	if  == nil {
		return
	}
	delete(.methods, )
	assert(!.objMap[].alias) // don't use TypeName.IsAlias (requires fully set up object)

	// use an objset to check for name conflicts
	var  objset

	// spec: "If the base type is a struct type, the non-blank method
	// and field names must be distinct."
	,  := .typ.(*Named) // shouldn't fail but be conservative
	if  != nil {
		if ,  := .underlying.(*Struct);  != nil {
			for ,  := range .fields {
				if .name != "_" {
					assert(.insert() == nil)
				}
			}
		}

		// Checker.Files may be called multiple times; additional package files
		// may add methods to already type-checked types. Add pre-existing methods
		// so that we can detect redeclarations.
		for ,  := range .methods {
			assert(.name != "_")
			assert(.insert() == nil)
		}
	}

	// add valid methods
	for ,  := range  {
		// spec: "For a base type, the non-blank names of methods bound
		// to it must be unique."
		assert(.name != "_")
		if  := .insert();  != nil {
			switch .(type) {
			case *Var:
				.errorf(, _DuplicateFieldAndMethod, "field and method with the same name %s", .name)
			case *Func:
				.errorf(, _DuplicateMethod, "method %s already declared for %s", .name, )
			default:
				unreachable()
			}
			.reportAltDecl()
			continue
		}

		if  != nil {
			.methods = append(.methods, )
		}
	}
}

func ( *Checker) ( *Func,  *declInfo) {
	assert(.typ == nil)

	// func declarations cannot use iota
	assert(.iota == nil)

	 := new(Signature)
	.typ =  // guard against cycles
	 := .fdecl
	.funcType(, .Recv, .Type)
	if .recv == nil && .name == "init" && (.params.Len() > 0 || .results.Len() > 0) {
		.errorf(, _InvalidInitSig, "func init must have no arguments and no return values")
		// ok to continue
	}

	// function body must be type-checked after global declarations
	// (functions implemented elsewhere have no body)
	if !.conf.IgnoreFuncBodies && .Body != nil {
		.later(func() {
			.funcBody(, .name, , .Body, nil)
		})
	}
}

func ( *Checker) ( ast.Decl) {
	 := .pkg

	.walkDecl(, func( decl) {
		switch d := .(type) {
		case constDecl:
			 := len(.delayed)

			// declare all constants
			 := make([]*Const, len(.spec.Names))
			for ,  := range .spec.Names {
				 := NewConst(.Pos(), , .Name, nil, constant.MakeInt64(int64(.iota)))
				[] = 

				var  ast.Expr
				if  < len(.init) {
					 = .init[]
				}

				.constDecl(, .typ, , .inherited)
			}

			// process function literals in init expressions before scope changes
			.processDelayed()

			// spec: "The scope of a constant or variable identifier declared
			// inside a function begins at the end of the ConstSpec or VarSpec
			// (ShortVarDecl for short variable declarations) and ends at the
			// end of the innermost containing block."
			 := .spec.End()
			for ,  := range .spec.Names {
				.declare(.scope, , [], )
			}

		case varDecl:
			 := len(.delayed)

			 := make([]*Var, len(.spec.Names))
			for ,  := range .spec.Names {
				[] = NewVar(.Pos(), , .Name, nil)
			}

			// initialize all variables
			for ,  := range  {
				var  []*Var
				var  ast.Expr
				switch len(.spec.Values) {
				case len(.spec.Names):
					// lhs and rhs match
					 = .spec.Values[]
				case 1:
					// rhs is expected to be a multi-valued expression
					 = 
					 = .spec.Values[0]
				default:
					if  < len(.spec.Values) {
						 = .spec.Values[]
					}
				}
				.varDecl(, , .spec.Type, )
				if len(.spec.Values) == 1 {
					// If we have a single lhs variable we are done either way.
					// If we have a single rhs expression, it must be a multi-
					// valued expression, in which case handling the first lhs
					// variable will cause all lhs variables to have a type
					// assigned, and we are done as well.
					if debug {
						for ,  := range  {
							assert(.typ != nil)
						}
					}
					break
				}
			}

			// process function literals in init expressions before scope changes
			.processDelayed()

			// declare all variables
			// (only at this point are the variable scopes (parents) set)
			 := .spec.End() // see constant declarations
			for ,  := range .spec.Names {
				// see constant declarations
				.declare(.scope, , [], )
			}

		case typeDecl:
			 := NewTypeName(.spec.Name.Pos(), , .spec.Name.Name, nil)
			// spec: "The scope of a type identifier declared inside a function
			// begins at the identifier in the TypeSpec and ends at the end of
			// the innermost containing block."
			 := .spec.Name.Pos()
			.declare(.scope, .spec.Name, , )
			// mark and unmark type before calling typeDecl; its type is still nil (see Checker.objDecl)
			.setColor(grey + color(.push()))
			.typeDecl(, .spec.Type, nil, .spec.Assign.IsValid())
			.pop().setColor(black)
		default:
			.invalidAST(.node(), "unknown ast.Decl node %T", .node())
		}
	})
}