...

Source file src/go/ast/resolve.go

Documentation: go/ast

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // This file implements NewPackage.
     6  
     7  package ast
     8  
     9  import (
    10  	"fmt"
    11  	"go/scanner"
    12  	"go/token"
    13  	"strconv"
    14  )
    15  
    16  type pkgBuilder struct {
    17  	fset   *token.FileSet
    18  	errors scanner.ErrorList
    19  }
    20  
    21  func (p *pkgBuilder) error(pos token.Pos, msg string) {
    22  	p.errors.Add(p.fset.Position(pos), msg)
    23  }
    24  
    25  func (p *pkgBuilder) errorf(pos token.Pos, format string, args ...any) {
    26  	p.error(pos, fmt.Sprintf(format, args...))
    27  }
    28  
    29  func (p *pkgBuilder) declare(scope, altScope *Scope, obj *Object) {
    30  	alt := scope.Insert(obj)
    31  	if alt == nil && altScope != nil {
    32  		// see if there is a conflicting declaration in altScope
    33  		alt = altScope.Lookup(obj.Name)
    34  	}
    35  	if alt != nil {
    36  		prevDecl := ""
    37  		if pos := alt.Pos(); pos.IsValid() {
    38  			prevDecl = fmt.Sprintf("\n\tprevious declaration at %s", p.fset.Position(pos))
    39  		}
    40  		p.error(obj.Pos(), fmt.Sprintf("%s redeclared in this block%s", obj.Name, prevDecl))
    41  	}
    42  }
    43  
    44  func resolve(scope *Scope, ident *Ident) bool {
    45  	for ; scope != nil; scope = scope.Outer {
    46  		if obj := scope.Lookup(ident.Name); obj != nil {
    47  			ident.Obj = obj
    48  			return true
    49  		}
    50  	}
    51  	return false
    52  }
    53  
    54  // An Importer resolves import paths to package Objects.
    55  // The imports map records the packages already imported,
    56  // indexed by package id (canonical import path).
    57  // An Importer must determine the canonical import path and
    58  // check the map to see if it is already present in the imports map.
    59  // If so, the Importer can return the map entry. Otherwise, the
    60  // Importer should load the package data for the given path into
    61  // a new *Object (pkg), record pkg in the imports map, and then
    62  // return pkg.
    63  type Importer func(imports map[string]*Object, path string) (pkg *Object, err error)
    64  
    65  // NewPackage creates a new Package node from a set of File nodes. It resolves
    66  // unresolved identifiers across files and updates each file's Unresolved list
    67  // accordingly. If a non-nil importer and universe scope are provided, they are
    68  // used to resolve identifiers not declared in any of the package files. Any
    69  // remaining unresolved identifiers are reported as undeclared. If the files
    70  // belong to different packages, one package name is selected and files with
    71  // different package names are reported and then ignored.
    72  // The result is a package node and a scanner.ErrorList if there were errors.
    73  func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error) {
    74  	var p pkgBuilder
    75  	p.fset = fset
    76  
    77  	// complete package scope
    78  	pkgName := ""
    79  	pkgScope := NewScope(universe)
    80  	for _, file := range files {
    81  		// package names must match
    82  		switch name := file.Name.Name; {
    83  		case pkgName == "":
    84  			pkgName = name
    85  		case name != pkgName:
    86  			p.errorf(file.Package, "package %s; expected %s", name, pkgName)
    87  			continue // ignore this file
    88  		}
    89  
    90  		// collect top-level file objects in package scope
    91  		for _, obj := range file.Scope.Objects {
    92  			p.declare(pkgScope, nil, obj)
    93  		}
    94  	}
    95  
    96  	// package global mapping of imported package ids to package objects
    97  	imports := make(map[string]*Object)
    98  
    99  	// complete file scopes with imports and resolve identifiers
   100  	for _, file := range files {
   101  		// ignore file if it belongs to a different package
   102  		// (error has already been reported)
   103  		if file.Name.Name != pkgName {
   104  			continue
   105  		}
   106  
   107  		// build file scope by processing all imports
   108  		importErrors := false
   109  		fileScope := NewScope(pkgScope)
   110  		for _, spec := range file.Imports {
   111  			if importer == nil {
   112  				importErrors = true
   113  				continue
   114  			}
   115  			path, _ := strconv.Unquote(spec.Path.Value)
   116  			pkg, err := importer(imports, path)
   117  			if err != nil {
   118  				p.errorf(spec.Path.Pos(), "could not import %s (%s)", path, err)
   119  				importErrors = true
   120  				continue
   121  			}
   122  			// TODO(gri) If a local package name != "." is provided,
   123  			// global identifier resolution could proceed even if the
   124  			// import failed. Consider adjusting the logic here a bit.
   125  
   126  			// local name overrides imported package name
   127  			name := pkg.Name
   128  			if spec.Name != nil {
   129  				name = spec.Name.Name
   130  			}
   131  
   132  			// add import to file scope
   133  			if name == "." {
   134  				// merge imported scope with file scope
   135  				for _, obj := range pkg.Data.(*Scope).Objects {
   136  					p.declare(fileScope, pkgScope, obj)
   137  				}
   138  			} else if name != "_" {
   139  				// declare imported package object in file scope
   140  				// (do not re-use pkg in the file scope but create
   141  				// a new object instead; the Decl field is different
   142  				// for different files)
   143  				obj := NewObj(Pkg, name)
   144  				obj.Decl = spec
   145  				obj.Data = pkg.Data
   146  				p.declare(fileScope, pkgScope, obj)
   147  			}
   148  		}
   149  
   150  		// resolve identifiers
   151  		if importErrors {
   152  			// don't use the universe scope without correct imports
   153  			// (objects in the universe may be shadowed by imports;
   154  			// with missing imports, identifiers might get resolved
   155  			// incorrectly to universe objects)
   156  			pkgScope.Outer = nil
   157  		}
   158  		i := 0
   159  		for _, ident := range file.Unresolved {
   160  			if !resolve(fileScope, ident) {
   161  				p.errorf(ident.Pos(), "undeclared name: %s", ident.Name)
   162  				file.Unresolved[i] = ident
   163  				i++
   164  			}
   165  
   166  		}
   167  		file.Unresolved = file.Unresolved[0:i]
   168  		pkgScope.Outer = universe // reset universe scope
   169  	}
   170  
   171  	p.errors.Sort()
   172  	return &Package{pkgName, pkgScope, imports, files}, p.errors.Err()
   173  }
   174  

View as plain text