github.com/zebozhuang/go@v0.0.0-20200207033046-f8a98f6f5c5d/src/go/internal/srcimporter/srcimporter.go (about) 1 // Copyright 2017 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 srcimporter implements importing directly 6 // from source files rather than installed packages. 7 package srcimporter // import "go/internal/srcimporter" 8 9 import ( 10 "fmt" 11 "go/ast" 12 "go/build" 13 "go/parser" 14 "go/token" 15 "go/types" 16 "path/filepath" 17 "sync" 18 ) 19 20 // An Importer provides the context for importing packages from source code. 21 // 从源码导入包 22 type Importer struct { 23 ctxt *build.Context // 构建上下文 24 fset *token.FileSet // 文件集合 25 sizes types.Sizes // 大小 26 packages map[string]*types.Package // 包 27 } 28 29 // NewImporter returns a new Importer for the given context, file set, and map 30 // of packages. The context is used to resolve import paths to package paths, 31 // and identifying the files belonging to the package. If the context provides 32 // non-nil file system functions, they are used instead of the regular package 33 // os functions. The file set is used to track position information of package 34 // files; and imported packages are added to the packages map. 35 // 创建一个新的 36 func New(ctxt *build.Context, fset *token.FileSet, packages map[string]*types.Package) *Importer { 37 return &Importer{ 38 ctxt: ctxt, 39 fset: fset, 40 sizes: types.SizesFor(ctxt.Compiler, ctxt.GOARCH), // uses go/types default if GOARCH not found 41 packages: packages, 42 } 43 } 44 45 // Importing is a sentinel taking the place in Importer.packages 46 // for a package that is in the process of being imported. 47 var importing types.Package 48 49 // Import(path) is a shortcut for ImportFrom(path, "", 0). 50 func (p *Importer) Import(path string) (*types.Package, error) { 51 return p.ImportFrom(path, "", 0) 52 } 53 54 // ImportFrom imports the package with the given import path resolved from the given srcDir, 55 // adds the new package to the set of packages maintained by the importer, and returns the 56 // package. Package path resolution and file system operations are controlled by the context 57 // maintained with the importer. The import mode must be zero but is otherwise ignored. 58 // Packages that are not comprised entirely of pure Go files may fail to import because the 59 // type checker may not be able to determine all exported entities (e.g. due to cgo dependencies). 60 // 从源码导入 61 func (p *Importer) ImportFrom(path, srcDir string, mode types.ImportMode) (*types.Package, error) { 62 if mode != 0 { 63 panic("non-zero import mode") 64 } 65 66 // determine package path (do vendor resolution) 67 var bp *build.Package 68 var err error 69 switch { 70 default: 71 if abs, err := p.absPath(srcDir); err == nil { // see issue #14282 72 srcDir = abs 73 } 74 bp, err = p.ctxt.Import(path, srcDir, build.FindOnly) 75 76 case build.IsLocalImport(path): 77 // "./x" -> "srcDir/x" 78 bp, err = p.ctxt.ImportDir(filepath.Join(srcDir, path), build.FindOnly) 79 80 case p.isAbsPath(path): 81 return nil, fmt.Errorf("invalid absolute import path %q", path) 82 } 83 if err != nil { 84 return nil, err // err may be *build.NoGoError - return as is 85 } 86 87 // unsafe包特殊处理 88 // package unsafe is known to the type checker 89 if bp.ImportPath == "unsafe" { 90 return types.Unsafe, nil 91 } 92 93 // no need to re-import if the package was imported completely before 94 // 如果包有导过 95 pkg := p.packages[bp.ImportPath] 96 if pkg != nil { 97 if pkg == &importing { // 判断是否为当前包,如果是就返回循环应用 98 return nil, fmt.Errorf("import cycle through package %q", bp.ImportPath) 99 } 100 if !pkg.Complete() { 101 // Package exists but is not complete - we cannot handle this 102 // at the moment since the source importer replaces the package 103 // wholesale rather than augmenting it (see #19337 for details). 104 // Return incomplete package with error (see #16088). 105 return pkg, fmt.Errorf("reimported partially imported package %q", bp.ImportPath) 106 } 107 return pkg, nil 108 } 109 110 p.packages[bp.ImportPath] = &importing 111 defer func() { 112 // clean up in case of error 113 // TODO(gri) Eventually we may want to leave a (possibly empty) 114 // package in the map in all cases (and use that package to 115 // identify cycles). See also issue 16088. 116 if p.packages[bp.ImportPath] == &importing { 117 p.packages[bp.ImportPath] = nil 118 } 119 }() 120 121 // collect package files 122 bp, err = p.ctxt.ImportDir(bp.Dir, 0) 123 if err != nil { 124 return nil, err // err may be *build.NoGoError - return as is 125 } 126 var filenames []string 127 filenames = append(filenames, bp.GoFiles...) 128 filenames = append(filenames, bp.CgoFiles...) 129 130 files, err := p.parseFiles(bp.Dir, filenames) 131 if err != nil { 132 return nil, err 133 } 134 135 // type-check package files 136 conf := types.Config{ 137 IgnoreFuncBodies: true, 138 FakeImportC: true, 139 Importer: p, 140 Sizes: p.sizes, 141 } 142 // 检测 143 pkg, err = conf.Check(bp.ImportPath, p.fset, files, nil) 144 if err != nil { 145 // Type-checking stops after the first error (types.Config.Error is not set), 146 // so the returned package is very likely incomplete. Don't return it since 147 // we don't know its condition: It's very likely unsafe to use and it's also 148 // not added to p.packages which may cause further problems (issue #20837). 149 return nil, fmt.Errorf("type-checking package %q failed (%v)", bp.ImportPath, err) 150 } 151 152 p.packages[bp.ImportPath] = pkg 153 return pkg, nil 154 } 155 156 // 解析文件 157 func (p *Importer) parseFiles(dir string, filenames []string) ([]*ast.File, error) { 158 open := p.ctxt.OpenFile // possibly nil 159 160 files := make([]*ast.File, len(filenames)) 161 errors := make([]error, len(filenames)) 162 163 var wg sync.WaitGroup 164 wg.Add(len(filenames)) 165 for i, filename := range filenames { 166 go func(i int, filepath string) { 167 defer wg.Done() 168 if open != nil { 169 src, err := open(filepath) 170 if err != nil { 171 errors[i] = fmt.Errorf("opening package file %s failed (%v)", filepath, err) 172 return 173 } 174 // 解析文件 175 files[i], errors[i] = parser.ParseFile(p.fset, filepath, src, 0) 176 src.Close() // ignore Close error - parsing may have succeeded which is all we need 177 } else { 178 // Special-case when ctxt doesn't provide a custom OpenFile and use the 179 // parser's file reading mechanism directly. This appears to be quite a 180 // bit faster than opening the file and providing an io.ReaderCloser in 181 // both cases. 182 // TODO(gri) investigate performance difference (issue #19281) 183 files[i], errors[i] = parser.ParseFile(p.fset, filepath, nil, 0) 184 } 185 }(i, p.joinPath(dir, filename)) 186 } 187 wg.Wait() 188 189 // if there are errors, return the first one for deterministic results 190 for _, err := range errors { 191 if err != nil { 192 return nil, err 193 } 194 } 195 196 return files, nil 197 } 198 199 // context-controlled file system operations 200 // 返回路径的绝对路径 201 func (p *Importer) absPath(path string) (string, error) { 202 // TODO(gri) This should be using p.ctxt.AbsPath which doesn't 203 // exist but probably should. See also issue #14282. 204 return filepath.Abs(path) 205 } 206 207 // 判读是否为绝对路径 208 func (p *Importer) isAbsPath(path string) bool { 209 if f := p.ctxt.IsAbsPath; f != nil { 210 return f(path) 211 } 212 return filepath.IsAbs(path) 213 } 214 215 // 加入路径 216 func (p *Importer) joinPath(elem ...string) string { 217 if f := p.ctxt.JoinPath; f != nil { 218 return f(elem...) 219 } 220 return filepath.Join(elem...) 221 }