// 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) environment.
// For the meaning of def, see Checker.definedType, in typexpr.go.
func ( *Checker) ( Object,  *TypeName) {
	if .conf._Trace && .Type() == nil {
		if .indent == 0 {
			fmt.Println() // empty line between top-level objects for readability
		}
		.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 (possibly invalid) 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 !.validCycle() || .typ == nil {
				.typ = Typ[Invalid]
			}

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

		case *TypeName:
			if !.validCycle() {
				// 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 !.validCycle() {
				// 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 environment and set up object environment
	defer func( environment) {
		.environment = 
	}(.environment)
	.environment = environment{
		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(, .vtyp, .init, .inherited)
	case *Var:
		.decl =  // new package-level var decl
		.varDecl(, .lhs, .vtyp, .init)
	case *TypeName:
		// invalid recursive types are detected via path
		.typeDecl(, .tdecl, )
		.collectMethods() // methods can only be added to top-level types
	case *Func:
		// functions may be recursive - no need to track dependencies
		.funcDecl(, )
	default:
		unreachable()
	}
}

// validCycle 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[:]
	 := false // if set, the cycle is through a type parameter list
	 := 0          // number of (constant or variable) values in the cycle; valid if !generic
	 := 0          // number of type definitions in the cycle; valid if !generic
:
	for ,  := range  {
		switch obj := .(type) {
		case *Const, *Var:
			++
		case *TypeName:
			// If we reach a generic type that is part of a cycle
			// and we are in a type parameter list, we have a cycle
			// through a type parameter list, which is invalid.
			if .inTParamList && isGeneric(.typ) {
				 = true
				break 
			}

			// 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 .enableAlias {
				 = .IsAlias()
			} else {
				if  := .objMap[];  != nil {
					 = .tdecl.Assign.IsValid() // package-level object
				} else {
					 = .IsAlias() // function local object
				}
			}
			if ! {
				++
			}
		case *Func:
			// ignored for now
		default:
			unreachable()
		}
	}

	if .conf._Trace {
		.trace(.Pos(), "## cycle detected: objPath = %s->%s (len = %d)", pathString(), .Name(), len())
		if  {
			.trace(.Pos(), "## cycle contains: generic type in a type parameter list")
		} else {
			.trace(.Pos(), "## cycle contains: %d values, %d type definitions", , )
		}
		defer func() {
			if  {
				.trace(.Pos(), "=> cycle is valid")
			} else {
				.trace(.Pos(), "=> error: cycle is invalid")
			}
		}()
	}

	if ! {
		// 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 true
		}

		// 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 true
		}
	}

	.cycleError()
	return false
}

// cycleError reports a declaration cycle starting with
// the object in cycle that is "first" in the source.
func ( *Checker) ( []Object) {
	// name returns the (possibly qualified) object name.
	// This is needed because with generic types, cycles
	// may refer to imported types. See go.dev/issue/50788.
	// TODO(gri) Thus functionality is used elsewhere. Factor it out.
	 := func( Object) string {
		return packagePrefix(.Pkg(), .qualifier) + .Name()
	}

	// 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()
	 := []
	 := ()
	// If obj is a type alias, mark it as valid (not broken) in order to avoid follow-on errors.
	,  := .(*TypeName)
	if  != nil && .IsAlias() {
		// If we use Alias nodes, it is initialized with Typ[Invalid].
		// TODO(gri) Adjust this code if we initialize with nil.
		if !.enableAlias {
			.validAlias(, Typ[Invalid])
		}
	}

	// report a more concise error for self references
	if len() == 1 {
		if  != nil {
			.errorf(, InvalidDeclCycle, "invalid recursive type: %s refers to itself", )
		} else {
			.errorf(, InvalidDeclCycle, "invalid cycle in declaration: %s refers to itself", )
		}
		return
	}

	if  != nil {
		.errorf(, InvalidDeclCycle, "invalid recursive type %s", )
	} else {
		.errorf(, InvalidDeclCycle, "invalid cycle in declaration of %s", )
	}
	for range  {
		.errorf(, InvalidDeclCycle, "\t%s refers to", ) // secondary error, \t indented
		++
		if  >= len() {
			 = 0
		}
		 = []
		 = ()
	}
	.errorf(, InvalidDeclCycle, "\t%s", )
}

// 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 cmpPos(.Pos(), ) < 0 {
			,  = +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:
					.errorf(, InvalidSyntaxTree, "invalid token %s", .Tok)
				}
			case *ast.TypeSpec:
				(typeDecl{})
			default:
				.errorf(, InvalidSyntaxTree, "unknown ast.Spec node %T", )
			}
		}
	case *ast.FuncDecl:
		(funcDecl{})
	default:
		.errorf(, InvalidSyntaxTree, "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
			// (go.dev/issue/22090)
			if isValid(under()) {
				.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 go.dev/issue/42991, go.dev/issue/42992).
			.errpos = atPos(.pos)
		}
		.expr(nil, &, )
	}
	.initConst(, &)
}

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

	// determine type, if any
	if  != nil {
		.typ = .varType()
		// 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(newTarget(.typ, .name), &, )
		.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 go.dev/issue/15755).
	if  != nil {
		for ,  := range  {
			.typ = .typ
		}
	}

	.initVars(, []ast.Expr{}, nil)
}

// isImportedConstraint reports whether typ is an imported type constraint.
func ( *Checker) ( Type) bool {
	 := asNamed()
	if  == nil || .obj.pkg == .pkg || .obj.pkg == nil {
		return false
	}
	,  := .under().(*Interface)
	return  != nil && !.IsMethodSet()
}

func ( *Checker) ( *TypeName,  *ast.TypeSpec,  *TypeName) {
	assert(.typ == nil)

	var  Type
	.later(func() {
		if  := asNamed(.typ);  != nil { // type may be invalid
			.validType()
		}
		// If typ is local, an error was already reported where typ is specified/defined.
		_ = .isImportedConstraint() && .verifyVersionf(.Type, go1_18, "using type constraint %s", )
	}).describef(, "validType(%s)", .Name())

	 := .Assign.IsValid()
	if  && .TypeParams.NumFields() != 0 {
		// The parser will ensure this but we may still get an invalid AST.
		// Complain and continue as regular type definition.
		.error(atPos(.Assign), BadDecl, "generic type cannot be alias")
		 = false
	}

	// alias declaration
	if  {
		.verifyVersionf(atPos(.Assign), go1_9, "type aliases")
		if .enableAlias {
			// TODO(gri) Should be able to use nil instead of Typ[Invalid] to mark
			//           the alias as incomplete. Currently this causes problems
			//           with certain cycles. Investigate.
			 := .newAlias(, Typ[Invalid])
			setDefType(, )
			 = .definedType(.Type, )
			assert( != nil)
			.fromRHS = 
			Unalias() // resolve alias.actual
		} else {
			.brokenAlias()
			 = .typ(.Type)
			.validAlias(, )
		}
		return
	}

	// type definition or generic type declaration
	 := .newNamed(, nil, nil)
	setDefType(, )

	if .TypeParams != nil {
		.openScope(, "type parameters")
		defer .closeScope()
		.collectTypeParams(&.tparams, .TypeParams)
	}

	// determine underlying type of named
	 = .definedType(.Type, )
	assert( != nil)
	.fromRHS = 

	// If the underlying type was not set while type-checking the right-hand
	// side, it is invalid and an error should have been reported elsewhere.
	if .underlying == nil {
		.underlying = Typ[Invalid]
	}

	// Disallow a lone type parameter as the RHS of a type declaration (go.dev/issue/45639).
	// We don't need this restriction anymore if we make the underlying type of a type
	// parameter its constraint interface: if the RHS is a lone type parameter, we will
	// use its underlying type (like we do for any RHS in a type declaration), and its
	// underlying type is an interface and the type declaration is well defined.
	if isTypeParam() {
		.error(.Type, MisplacedTypeParam, "cannot use a type parameter as RHS in type declaration")
		.underlying = Typ[Invalid]
	}
}

func ( *Checker) ( **TypeParamList,  *ast.FieldList) {
	var  []*TypeParam
	// Declare type parameters up-front, with empty interface as type bound.
	// The scope of type parameters starts at the beginning of the type parameter
	// list (so we can have mutually recursive parameterized interfaces).
	 := .Pos()
	for ,  := range .List {
		 = .declareTypeParams(, .Names, )
	}

	// Set the type parameters before collecting the type constraints because
	// the parameterized type may be used by the constraints (go.dev/issue/47887).
	// Example: type T[P T[P]] interface{}
	* = bindTParams()

	// Signal to cycle detection that we are in a type parameter list.
	// We can only be inside one type parameter list at any given time:
	// function closures may appear inside a type parameter list but they
	// cannot be generic, and their bodies are processed in delayed and
	// sequential fashion. Note that with each new declaration, we save
	// the existing environment and restore it when done; thus inTPList is
	// true exactly only when we are in a specific type parameter list.
	assert(!.inTParamList)
	.inTParamList = true
	defer func() {
		.inTParamList = false
	}()

	 := 0
	for ,  := range .List {
		var  Type
		// NOTE: we may be able to assert that f.Type != nil here, but this is not
		// an invariant of the AST, so we are cautious.
		if .Type != nil {
			 = .bound(.Type)
			if isTypeParam() {
				// We may be able to allow this since it is now well-defined what
				// the underlying type and thus type set of a type parameter is.
				// But we may need some additional form of cycle detection within
				// type parameter lists.
				.error(.Type, MisplacedTypeParam, "cannot use a type parameter as constraint")
				 = Typ[Invalid]
			}
		} else {
			 = Typ[Invalid]
		}
		for  := range .Names {
			[+].bound = 
		}
		 += len(.Names)
	}
}

func ( *Checker) ( ast.Expr) Type {
	// A type set literal of the form ~T and A|B may only appear as constraint;
	// embed it in an implicit interface so that only interface type-checking
	// needs to take care of such type expressions.
	 := false
	switch op := .(type) {
	case *ast.UnaryExpr:
		 = .Op == token.TILDE
	case *ast.BinaryExpr:
		 = .Op == token.OR
	}
	if  {
		 = &ast.InterfaceType{Methods: &ast.FieldList{List: []*ast.Field{{Type: }}}}
		 := .typ()
		// mark t as implicit interface if all went well
		if ,  := .(*Interface);  != nil {
			.implicit = true
		}
		return 
	}
	return .typ()
}

func ( *Checker) ( []*TypeParam,  []*ast.Ident,  token.Pos) []*TypeParam {
	// Use Typ[Invalid] for the type constraint to ensure that a type
	// is present even if the actual constraint has not been assigned
	// yet.
	// TODO(gri) Need to systematically review all uses of type parameter
	//           constraints to make sure we don't rely on them if they
	//           are not properly set yet.
	for ,  := range  {
		 := NewTypeName(.Pos(), .pkg, .Name, nil)
		 := .newTypeParam(, Typ[Invalid]) // assigns type to tpar as a side-effect
		.declare(.scope, , , )
		 = append(, )
	}

	if .conf._Trace && len() > 0 {
		.trace([0].Pos(), "type params = %v", [len()-len():])
	}

	return 
}

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[].tdecl.Assign.IsValid()) // 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."
	 := asNamed(.typ) // shouldn't fail but be conservative
	if  != nil {
		assert(.TypeArgs().Len() == 0) // collectMethods should not be called on an instantiated type

		// See go.dev/issue/52529: we must delay the expansion of underlying here, as
		// base may not be fully set-up.
		.later(func() {
			.checkFieldUniqueness()
		}).describef(, "verifying field uniqueness for %v", )

		// 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  := 0;  < .NumMethods(); ++ {
			 := .Method()
			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 {
			if .Pos().IsValid() {
				.errorf(, DuplicateMethod, "method %s.%s already declared at %s", .Name(), .name, .Pos())
			} else {
				.errorf(, DuplicateMethod, "method %s.%s already declared", .Name(), .name)
			}
			continue
		}

		if  != nil {
			.AddMethod()
		}
	}
}

func ( *Checker) ( *Named) {
	if ,  := .under().(*Struct);  != nil {
		var  objset
		for  := 0;  < .NumMethods(); ++ {
			 := .Method()
			assert(.name != "_")
			assert(.insert() == nil)
		}

		// Check that any non-blank field names of base are distinct from its
		// method names.
		for ,  := range .fields {
			if .name != "_" {
				if  := .insert();  != nil {
					// Struct fields should already be unique, so we should only
					// encounter an alternate via collision with a method name.
					_ = .(*Func)

					// For historical consistency, we report the primary error on the
					// method, and the alt decl on the field.
					.errorf(, DuplicateFieldAndMethod, "field and method with the same name %s", .name)
					.reportAltDecl()
				}
			}
		}
	}
}

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

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

	 := new(Signature)
	.typ =  // guard against cycles

	// Avoid cycle error when referring to method while type-checking the signature.
	// This avoids a nuisance in the best case (non-parameterized receiver type) and
	// since the method is not a type, we get an error. If we have a parameterized
	// receiver type, instantiating the receiver type leads to the instantiation of
	// its methods, and we don't want a cycle error in that case.
	// TODO(gri) review if this is correct and/or whether we still need this?
	 := .color_
	.color_ = black
	 := .fdecl
	.funcType(, .Recv, .Type)
	.color_ = 

	// Set the scope's extent to the complete "func (...) { ... }"
	// so that Scope.Innermost works correctly.
	.scope.pos = .Pos()
	.scope.end = .End()

	if .Type.TypeParams.NumFields() > 0 && .Body == nil {
		.softErrorf(.Name, BadDecl, "generic function is missing function body")
	}

	// 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)
		}).describef(, "func %s", .name)
	}
}

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, nil)
			.pop().setColor(black)
		default:
			.errorf(.node(), InvalidSyntaxTree, "unknown ast.Decl node %T", .node())
		}
	})
}