Source file src/go/types/resolver.go

Documentation: go/types

     1  // Copyright 2013 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  package types
     6  
     7  import (
     8  	"fmt"
     9  	"go/ast"
    10  	"go/constant"
    11  	"go/token"
    12  	"sort"
    13  	"strconv"
    14  	"strings"
    15  	"unicode"
    16  )
    17  
    18  // A declInfo describes a package-level const, type, var, or func declaration.
    19  type declInfo struct {
    20  	file  *Scope        // scope of file containing this declaration
    21  	lhs   []*Var        // lhs of n:1 variable declarations, or nil
    22  	typ   ast.Expr      // type, or nil
    23  	init  ast.Expr      // init/orig expression, or nil
    24  	fdecl *ast.FuncDecl // func declaration, or nil
    25  	alias bool          // type alias declaration
    26  
    27  	// The deps field tracks initialization expression dependencies.
    28  	deps map[Object]bool // lazily initialized
    29  }
    30  
    31  // hasInitializer reports whether the declared object has an initialization
    32  // expression or function body.
    33  func (d *declInfo) hasInitializer() bool {
    34  	return d.init != nil || d.fdecl != nil && d.fdecl.Body != nil
    35  }
    36  
    37  // addDep adds obj to the set of objects d's init expression depends on.
    38  func (d *declInfo) addDep(obj Object) {
    39  	m := d.deps
    40  	if m == nil {
    41  		m = make(map[Object]bool)
    42  		d.deps = m
    43  	}
    44  	m[obj] = true
    45  }
    46  
    47  // arityMatch checks that the lhs and rhs of a const or var decl
    48  // have the appropriate number of names and init exprs. For const
    49  // decls, init is the value spec providing the init exprs; for
    50  // var decls, init is nil (the init exprs are in s in this case).
    51  func (check *Checker) arityMatch(s, init *ast.ValueSpec) {
    52  	l := len(s.Names)
    53  	r := len(s.Values)
    54  	if init != nil {
    55  		r = len(init.Values)
    56  	}
    57  
    58  	switch {
    59  	case init == nil && r == 0:
    60  		// var decl w/o init expr
    61  		if s.Type == nil {
    62  			check.errorf(s.Pos(), "missing type or init expr")
    63  		}
    64  	case l < r:
    65  		if l < len(s.Values) {
    66  			// init exprs from s
    67  			n := s.Values[l]
    68  			check.errorf(n.Pos(), "extra init expr %s", n)
    69  			// TODO(gri) avoid declared but not used error here
    70  		} else {
    71  			// init exprs "inherited"
    72  			check.errorf(s.Pos(), "extra init expr at %s", check.fset.Position(init.Pos()))
    73  			// TODO(gri) avoid declared but not used error here
    74  		}
    75  	case l > r && (init != nil || r != 1):
    76  		n := s.Names[r]
    77  		check.errorf(n.Pos(), "missing init expr for %s", n)
    78  	}
    79  }
    80  
    81  func validatedImportPath(path string) (string, error) {
    82  	s, err := strconv.Unquote(path)
    83  	if err != nil {
    84  		return "", err
    85  	}
    86  	if s == "" {
    87  		return "", fmt.Errorf("empty string")
    88  	}
    89  	const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
    90  	for _, r := range s {
    91  		if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
    92  			return s, fmt.Errorf("invalid character %#U", r)
    93  		}
    94  	}
    95  	return s, nil
    96  }
    97  
    98  // declarePkgObj declares obj in the package scope, records its ident -> obj mapping,
    99  // and updates check.objMap. The object must not be a function or method.
   100  func (check *Checker) declarePkgObj(ident *ast.Ident, obj Object, d *declInfo) {
   101  	assert(ident.Name == obj.Name())
   102  
   103  	// spec: "A package-scope or file-scope identifier with name init
   104  	// may only be declared to be a function with this (func()) signature."
   105  	if ident.Name == "init" {
   106  		check.errorf(ident.Pos(), "cannot declare init - must be func")
   107  		return
   108  	}
   109  
   110  	// spec: "The main package must have package name main and declare
   111  	// a function main that takes no arguments and returns no value."
   112  	if ident.Name == "main" && check.pkg.name == "main" {
   113  		check.errorf(ident.Pos(), "cannot declare main - must be func")
   114  		return
   115  	}
   116  
   117  	check.declare(check.pkg.scope, ident, obj, token.NoPos)
   118  	check.objMap[obj] = d
   119  	obj.setOrder(uint32(len(check.objMap)))
   120  }
   121  
   122  // filename returns a filename suitable for debugging output.
   123  func (check *Checker) filename(fileNo int) string {
   124  	file := check.files[fileNo]
   125  	if pos := file.Pos(); pos.IsValid() {
   126  		return check.fset.File(pos).Name()
   127  	}
   128  	return fmt.Sprintf("file[%d]", fileNo)
   129  }
   130  
   131  func (check *Checker) importPackage(pos token.Pos, path, dir string) *Package {
   132  	// If we already have a package for the given (path, dir)
   133  	// pair, use it instead of doing a full import.
   134  	// Checker.impMap only caches packages that are marked Complete
   135  	// or fake (dummy packages for failed imports). Incomplete but
   136  	// non-fake packages do require an import to complete them.
   137  	key := importKey{path, dir}
   138  	imp := check.impMap[key]
   139  	if imp != nil {
   140  		return imp
   141  	}
   142  
   143  	// no package yet => import it
   144  	if path == "C" && check.conf.FakeImportC {
   145  		imp = NewPackage("C", "C")
   146  		imp.fake = true
   147  	} else {
   148  		// ordinary import
   149  		var err error
   150  		if importer := check.conf.Importer; importer == nil {
   151  			err = fmt.Errorf("Config.Importer not installed")
   152  		} else if importerFrom, ok := importer.(ImporterFrom); ok {
   153  			imp, err = importerFrom.ImportFrom(path, dir, 0)
   154  			if imp == nil && err == nil {
   155  				err = fmt.Errorf("Config.Importer.ImportFrom(%s, %s, 0) returned nil but no error", path, dir)
   156  			}
   157  		} else {
   158  			imp, err = importer.Import(path)
   159  			if imp == nil && err == nil {
   160  				err = fmt.Errorf("Config.Importer.Import(%s) returned nil but no error", path)
   161  			}
   162  		}
   163  		// make sure we have a valid package name
   164  		// (errors here can only happen through manipulation of packages after creation)
   165  		if err == nil && imp != nil && (imp.name == "_" || imp.name == "") {
   166  			err = fmt.Errorf("invalid package name: %q", imp.name)
   167  			imp = nil // create fake package below
   168  		}
   169  		if err != nil {
   170  			check.errorf(pos, "could not import %s (%s)", path, err)
   171  			if imp == nil {
   172  				// create a new fake package
   173  				// come up with a sensible package name (heuristic)
   174  				name := path
   175  				if i := len(name); i > 0 && name[i-1] == '/' {
   176  					name = name[:i-1]
   177  				}
   178  				if i := strings.LastIndex(name, "/"); i >= 0 {
   179  					name = name[i+1:]
   180  				}
   181  				imp = NewPackage(path, name)
   182  			}
   183  			// continue to use the package as best as we can
   184  			imp.fake = true // avoid follow-up lookup failures
   185  		}
   186  	}
   187  
   188  	// package should be complete or marked fake, but be cautious
   189  	if imp.complete || imp.fake {
   190  		check.impMap[key] = imp
   191  		check.pkgCnt[imp.name]++
   192  		return imp
   193  	}
   194  
   195  	// something went wrong (importer may have returned incomplete package without error)
   196  	return nil
   197  }
   198  
   199  // collectObjects collects all file and package objects and inserts them
   200  // into their respective scopes. It also performs imports and associates
   201  // methods with receiver base type names.
   202  func (check *Checker) collectObjects() {
   203  	pkg := check.pkg
   204  
   205  	// pkgImports is the set of packages already imported by any package file seen
   206  	// so far. Used to avoid duplicate entries in pkg.imports. Allocate and populate
   207  	// it (pkg.imports may not be empty if we are checking test files incrementally).
   208  	// Note that pkgImports is keyed by package (and thus package path), not by an
   209  	// importKey value. Two different importKey values may map to the same package
   210  	// which is why we cannot use the check.impMap here.
   211  	var pkgImports = make(map[*Package]bool)
   212  	for _, imp := range pkg.imports {
   213  		pkgImports[imp] = true
   214  	}
   215  
   216  	var methods []*Func // list of methods with non-blank _ names
   217  	for fileNo, file := range check.files {
   218  		// The package identifier denotes the current package,
   219  		// but there is no corresponding package object.
   220  		check.recordDef(file.Name, nil)
   221  
   222  		// Use the actual source file extent rather than *ast.File extent since the
   223  		// latter doesn't include comments which appear at the start or end of the file.
   224  		// Be conservative and use the *ast.File extent if we don't have a *token.File.
   225  		pos, end := file.Pos(), file.End()
   226  		if f := check.fset.File(file.Pos()); f != nil {
   227  			pos, end = token.Pos(f.Base()), token.Pos(f.Base()+f.Size())
   228  		}
   229  		fileScope := NewScope(check.pkg.scope, pos, end, check.filename(fileNo))
   230  		check.recordScope(file, fileScope)
   231  
   232  		// determine file directory, necessary to resolve imports
   233  		// FileName may be "" (typically for tests) in which case
   234  		// we get "." as the directory which is what we would want.
   235  		fileDir := dir(check.fset.Position(file.Name.Pos()).Filename)
   236  
   237  		for _, decl := range file.Decls {
   238  			switch d := decl.(type) {
   239  			case *ast.BadDecl:
   240  				// ignore
   241  
   242  			case *ast.GenDecl:
   243  				var last *ast.ValueSpec // last ValueSpec with type or init exprs seen
   244  				for iota, spec := range d.Specs {
   245  					switch s := spec.(type) {
   246  					case *ast.ImportSpec:
   247  						// import package
   248  						path, err := validatedImportPath(s.Path.Value)
   249  						if err != nil {
   250  							check.errorf(s.Path.Pos(), "invalid import path (%s)", err)
   251  							continue
   252  						}
   253  
   254  						imp := check.importPackage(s.Path.Pos(), path, fileDir)
   255  						if imp == nil {
   256  							continue
   257  						}
   258  
   259  						// add package to list of explicit imports
   260  						// (this functionality is provided as a convenience
   261  						// for clients; it is not needed for type-checking)
   262  						if !pkgImports[imp] {
   263  							pkgImports[imp] = true
   264  							pkg.imports = append(pkg.imports, imp)
   265  						}
   266  
   267  						// local name overrides imported package name
   268  						name := imp.name
   269  						if s.Name != nil {
   270  							name = s.Name.Name
   271  							if path == "C" {
   272  								// match cmd/compile (not prescribed by spec)
   273  								check.errorf(s.Name.Pos(), `cannot rename import "C"`)
   274  								continue
   275  							}
   276  							if name == "init" {
   277  								check.errorf(s.Name.Pos(), "cannot declare init - must be func")
   278  								continue
   279  							}
   280  						}
   281  
   282  						obj := NewPkgName(s.Pos(), pkg, name, imp)
   283  						if s.Name != nil {
   284  							// in a dot-import, the dot represents the package
   285  							check.recordDef(s.Name, obj)
   286  						} else {
   287  							check.recordImplicit(s, obj)
   288  						}
   289  
   290  						if path == "C" {
   291  							// match cmd/compile (not prescribed by spec)
   292  							obj.used = true
   293  						}
   294  
   295  						// add import to file scope
   296  						if name == "." {
   297  							// merge imported scope with file scope
   298  							for _, obj := range imp.scope.elems {
   299  								// A package scope may contain non-exported objects,
   300  								// do not import them!
   301  								if obj.Exported() {
   302  									// declare dot-imported object
   303  									// (Do not use check.declare because it modifies the object
   304  									// via Object.setScopePos, which leads to a race condition;
   305  									// the object may be imported into more than one file scope
   306  									// concurrently. See issue #32154.)
   307  									if alt := fileScope.Insert(obj); alt != nil {
   308  										check.errorf(s.Name.Pos(), "%s redeclared in this block", obj.Name())
   309  										check.reportAltDecl(alt)
   310  									}
   311  								}
   312  							}
   313  							// add position to set of dot-import positions for this file
   314  							// (this is only needed for "imported but not used" errors)
   315  							check.addUnusedDotImport(fileScope, imp, s.Pos())
   316  						} else {
   317  							// declare imported package object in file scope
   318  							// (no need to provide s.Name since we called check.recordDef earlier)
   319  							check.declare(fileScope, nil, obj, token.NoPos)
   320  						}
   321  
   322  					case *ast.ValueSpec:
   323  						switch d.Tok {
   324  						case token.CONST:
   325  							// determine which initialization expressions to use
   326  							switch {
   327  							case s.Type != nil || len(s.Values) > 0:
   328  								last = s
   329  							case last == nil:
   330  								last = new(ast.ValueSpec) // make sure last exists
   331  							}
   332  
   333  							// declare all constants
   334  							for i, name := range s.Names {
   335  								obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(iota)))
   336  
   337  								var init ast.Expr
   338  								if i < len(last.Values) {
   339  									init = last.Values[i]
   340  								}
   341  
   342  								d := &declInfo{file: fileScope, typ: last.Type, init: init}
   343  								check.declarePkgObj(name, obj, d)
   344  							}
   345  
   346  							check.arityMatch(s, last)
   347  
   348  						case token.VAR:
   349  							lhs := make([]*Var, len(s.Names))
   350  							// If there's exactly one rhs initializer, use
   351  							// the same declInfo d1 for all lhs variables
   352  							// so that each lhs variable depends on the same
   353  							// rhs initializer (n:1 var declaration).
   354  							var d1 *declInfo
   355  							if len(s.Values) == 1 {
   356  								// The lhs elements are only set up after the for loop below,
   357  								// but that's ok because declareVar only collects the declInfo
   358  								// for a later phase.
   359  								d1 = &declInfo{file: fileScope, lhs: lhs, typ: s.Type, init: s.Values[0]}
   360  							}
   361  
   362  							// declare all variables
   363  							for i, name := range s.Names {
   364  								obj := NewVar(name.Pos(), pkg, name.Name, nil)
   365  								lhs[i] = obj
   366  
   367  								d := d1
   368  								if d == nil {
   369  									// individual assignments
   370  									var init ast.Expr
   371  									if i < len(s.Values) {
   372  										init = s.Values[i]
   373  									}
   374  									d = &declInfo{file: fileScope, typ: s.Type, init: init}
   375  								}
   376  
   377  								check.declarePkgObj(name, obj, d)
   378  							}
   379  
   380  							check.arityMatch(s, nil)
   381  
   382  						default:
   383  							check.invalidAST(s.Pos(), "invalid token %s", d.Tok)
   384  						}
   385  
   386  					case *ast.TypeSpec:
   387  						obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Name, nil)
   388  						check.declarePkgObj(s.Name, obj, &declInfo{file: fileScope, typ: s.Type, alias: s.Assign.IsValid()})
   389  
   390  					default:
   391  						check.invalidAST(s.Pos(), "unknown ast.Spec node %T", s)
   392  					}
   393  				}
   394  
   395  			case *ast.FuncDecl:
   396  				name := d.Name.Name
   397  				obj := NewFunc(d.Name.Pos(), pkg, name, nil)
   398  				if d.Recv == nil {
   399  					// regular function
   400  					if name == "init" {
   401  						// don't declare init functions in the package scope - they are invisible
   402  						obj.parent = pkg.scope
   403  						check.recordDef(d.Name, obj)
   404  						// init functions must have a body
   405  						if d.Body == nil {
   406  							check.softErrorf(obj.pos, "missing function body")
   407  						}
   408  					} else {
   409  						check.declare(pkg.scope, d.Name, obj, token.NoPos)
   410  					}
   411  				} else {
   412  					// method
   413  					// (Methods with blank _ names are never found; no need to collect
   414  					// them for later type association. They will still be type-checked
   415  					// with all the other functions.)
   416  					if name != "_" {
   417  						methods = append(methods, obj)
   418  					}
   419  					check.recordDef(d.Name, obj)
   420  				}
   421  				info := &declInfo{file: fileScope, fdecl: d}
   422  				// Methods are not package-level objects but we still track them in the
   423  				// object map so that we can handle them like regular functions (if the
   424  				// receiver is invalid); also we need their fdecl info when associating
   425  				// them with their receiver base type, below.
   426  				check.objMap[obj] = info
   427  				obj.setOrder(uint32(len(check.objMap)))
   428  
   429  			default:
   430  				check.invalidAST(d.Pos(), "unknown ast.Decl node %T", d)
   431  			}
   432  		}
   433  	}
   434  
   435  	// verify that objects in package and file scopes have different names
   436  	for _, scope := range check.pkg.scope.children /* file scopes */ {
   437  		for _, obj := range scope.elems {
   438  			if alt := pkg.scope.Lookup(obj.Name()); alt != nil {
   439  				if pkg, ok := obj.(*PkgName); ok {
   440  					check.errorf(alt.Pos(), "%s already declared through import of %s", alt.Name(), pkg.Imported())
   441  					check.reportAltDecl(pkg)
   442  				} else {
   443  					check.errorf(alt.Pos(), "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
   444  					// TODO(gri) dot-imported objects don't have a position; reportAltDecl won't print anything
   445  					check.reportAltDecl(obj)
   446  				}
   447  			}
   448  		}
   449  	}
   450  
   451  	// Now that we have all package scope objects and all methods,
   452  	// associate methods with receiver base type name where possible.
   453  	// Ignore methods that have an invalid receiver. They will be
   454  	// type-checked later, with regular functions.
   455  	if methods == nil {
   456  		return // nothing to do
   457  	}
   458  	check.methods = make(map[*TypeName][]*Func)
   459  	for _, f := range methods {
   460  		fdecl := check.objMap[f].fdecl
   461  		if list := fdecl.Recv.List; len(list) > 0 {
   462  			// f is a method.
   463  			// Determine the receiver base type and associate f with it.
   464  			ptr, base := check.resolveBaseTypeName(list[0].Type)
   465  			if base != nil {
   466  				f.hasPtrRecv = ptr
   467  				check.methods[base] = append(check.methods[base], f)
   468  			}
   469  		}
   470  	}
   471  }
   472  
   473  // resolveBaseTypeName returns the non-alias base type name for typ, and whether
   474  // there was a pointer indirection to get to it. The base type name must be declared
   475  // in package scope, and there can be at most one pointer indirection. If no such type
   476  // name exists, the returned base is nil.
   477  func (check *Checker) resolveBaseTypeName(typ ast.Expr) (ptr bool, base *TypeName) {
   478  	// Algorithm: Starting from a type expression, which may be a name,
   479  	// we follow that type through alias declarations until we reach a
   480  	// non-alias type name. If we encounter anything but pointer types or
   481  	// parentheses we're done. If we encounter more than one pointer type
   482  	// we're done.
   483  	var seen map[*TypeName]bool
   484  	for {
   485  		typ = unparen(typ)
   486  
   487  		// check if we have a pointer type
   488  		if pexpr, _ := typ.(*ast.StarExpr); pexpr != nil {
   489  			// if we've already seen a pointer, we're done
   490  			if ptr {
   491  				return false, nil
   492  			}
   493  			ptr = true
   494  			typ = unparen(pexpr.X) // continue with pointer base type
   495  		}
   496  
   497  		// typ must be a name
   498  		name, _ := typ.(*ast.Ident)
   499  		if name == nil {
   500  			return false, nil
   501  		}
   502  
   503  		// name must denote an object found in the current package scope
   504  		// (note that dot-imported objects are not in the package scope!)
   505  		obj := check.pkg.scope.Lookup(name.Name)
   506  		if obj == nil {
   507  			return false, nil
   508  		}
   509  
   510  		// the object must be a type name...
   511  		tname, _ := obj.(*TypeName)
   512  		if tname == nil {
   513  			return false, nil
   514  		}
   515  
   516  		// ... which we have not seen before
   517  		if seen[tname] {
   518  			return false, nil
   519  		}
   520  
   521  		// we're done if tdecl defined tname as a new type
   522  		// (rather than an alias)
   523  		tdecl := check.objMap[tname] // must exist for objects in package scope
   524  		if !tdecl.alias {
   525  			return ptr, tname
   526  		}
   527  
   528  		// otherwise, continue resolving
   529  		typ = tdecl.typ
   530  		if seen == nil {
   531  			seen = make(map[*TypeName]bool)
   532  		}
   533  		seen[tname] = true
   534  	}
   535  }
   536  
   537  // packageObjects typechecks all package objects, but not function bodies.
   538  func (check *Checker) packageObjects() {
   539  	// process package objects in source order for reproducible results
   540  	objList := make([]Object, len(check.objMap))
   541  	i := 0
   542  	for obj := range check.objMap {
   543  		objList[i] = obj
   544  		i++
   545  	}
   546  	sort.Sort(inSourceOrder(objList))
   547  
   548  	// add new methods to already type-checked types (from a prior Checker.Files call)
   549  	for _, obj := range objList {
   550  		if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil {
   551  			check.addMethodDecls(obj)
   552  		}
   553  	}
   554  
   555  	// We process non-alias declarations first, in order to avoid situations where
   556  	// the type of an alias declaration is needed before it is available. In general
   557  	// this is still not enough, as it is possible to create sufficiently convoluted
   558  	// recursive type definitions that will cause a type alias to be needed before it
   559  	// is available (see issue #25838 for examples).
   560  	// As an aside, the cmd/compiler suffers from the same problem (#25838).
   561  	var aliasList []*TypeName
   562  	// phase 1
   563  	for _, obj := range objList {
   564  		// If we have a type alias, collect it for the 2nd phase.
   565  		if tname, _ := obj.(*TypeName); tname != nil && check.objMap[tname].alias {
   566  			aliasList = append(aliasList, tname)
   567  			continue
   568  		}
   569  
   570  		check.objDecl(obj, nil)
   571  	}
   572  	// phase 2
   573  	for _, obj := range aliasList {
   574  		check.objDecl(obj, nil)
   575  	}
   576  
   577  	// At this point we may have a non-empty check.methods map; this means that not all
   578  	// entries were deleted at the end of typeDecl because the respective receiver base
   579  	// types were not found. In that case, an error was reported when declaring those
   580  	// methods. We can now safely discard this map.
   581  	check.methods = nil
   582  }
   583  
   584  // inSourceOrder implements the sort.Sort interface.
   585  type inSourceOrder []Object
   586  
   587  func (a inSourceOrder) Len() int           { return len(a) }
   588  func (a inSourceOrder) Less(i, j int) bool { return a[i].order() < a[j].order() }
   589  func (a inSourceOrder) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
   590  
   591  // unusedImports checks for unused imports.
   592  func (check *Checker) unusedImports() {
   593  	// if function bodies are not checked, packages' uses are likely missing - don't check
   594  	if check.conf.IgnoreFuncBodies {
   595  		return
   596  	}
   597  
   598  	// spec: "It is illegal (...) to directly import a package without referring to
   599  	// any of its exported identifiers. To import a package solely for its side-effects
   600  	// (initialization), use the blank identifier as explicit package name."
   601  
   602  	// check use of regular imported packages
   603  	for _, scope := range check.pkg.scope.children /* file scopes */ {
   604  		for _, obj := range scope.elems {
   605  			if obj, ok := obj.(*PkgName); ok {
   606  				// Unused "blank imports" are automatically ignored
   607  				// since _ identifiers are not entered into scopes.
   608  				if !obj.used {
   609  					path := obj.imported.path
   610  					base := pkgName(path)
   611  					if obj.name == base {
   612  						check.softErrorf(obj.pos, "%q imported but not used", path)
   613  					} else {
   614  						check.softErrorf(obj.pos, "%q imported but not used as %s", path, obj.name)
   615  					}
   616  				}
   617  			}
   618  		}
   619  	}
   620  
   621  	// check use of dot-imported packages
   622  	for _, unusedDotImports := range check.unusedDotImports {
   623  		for pkg, pos := range unusedDotImports {
   624  			check.softErrorf(pos, "%q imported but not used", pkg.path)
   625  		}
   626  	}
   627  }
   628  
   629  // pkgName returns the package name (last element) of an import path.
   630  func pkgName(path string) string {
   631  	if i := strings.LastIndex(path, "/"); i >= 0 {
   632  		path = path[i+1:]
   633  	}
   634  	return path
   635  }
   636  
   637  // dir makes a good-faith attempt to return the directory
   638  // portion of path. If path is empty, the result is ".".
   639  // (Per the go/build package dependency tests, we cannot import
   640  // path/filepath and simply use filepath.Dir.)
   641  func dir(path string) string {
   642  	if i := strings.LastIndexAny(path, `/\`); i > 0 {
   643  		return path[:i]
   644  	}
   645  	// i <= 0
   646  	return "."
   647  }
   648  

View as plain text