loader.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package loader
  14. import (
  15. "fmt"
  16. "go/ast"
  17. "go/parser"
  18. "go/scanner"
  19. "go/token"
  20. "go/types"
  21. "io/ioutil"
  22. "os"
  23. "sync"
  24. "golang.org/x/tools/go/packages"
  25. )
  26. // Much of this is strongly inspired by the contents of go/packages,
  27. // except that it allows for lazy loading of syntax and type-checking
  28. // information to speed up cases where full traversal isn't needed.
  29. // PrintErrors print errors associated with all packages
  30. // in the given package graph, starting at the given root
  31. // packages and traversing through all imports. It will skip
  32. // any errors of the kinds specified in filterKinds. It will
  33. // return true if any errors were printed.
  34. func PrintErrors(pkgs []*Package, filterKinds ...packages.ErrorKind) bool {
  35. pkgsRaw := make([]*packages.Package, len(pkgs))
  36. for i, pkg := range pkgs {
  37. pkgsRaw[i] = pkg.Package
  38. }
  39. toSkip := make(map[packages.ErrorKind]struct{})
  40. for _, errKind := range filterKinds {
  41. toSkip[errKind] = struct{}{}
  42. }
  43. hadErrors := false
  44. packages.Visit(pkgsRaw, nil, func(pkgRaw *packages.Package) {
  45. for _, err := range pkgRaw.Errors {
  46. if _, skip := toSkip[err.Kind]; skip {
  47. continue
  48. }
  49. hadErrors = true
  50. fmt.Fprintln(os.Stderr, err)
  51. }
  52. })
  53. return hadErrors
  54. }
  55. // Package is a single, unique Go package that can be
  56. // lazily parsed and type-checked. Packages should not
  57. // be constructed directly -- instead, use LoadRoots.
  58. // For a given call to LoadRoots, only a single instance
  59. // of each package exists, and thus they may be used as keys
  60. // and for comparison.
  61. type Package struct {
  62. *packages.Package
  63. imports map[string]*Package
  64. loader *loader
  65. sync.Mutex
  66. }
  67. // Imports returns the imports for the given package, indexed by
  68. // package path (*not* name in any particular file).
  69. func (p *Package) Imports() map[string]*Package {
  70. if p.imports == nil {
  71. p.imports = p.loader.packagesFor(p.Package.Imports)
  72. }
  73. return p.imports
  74. }
  75. // NeedTypesInfo indicates that type-checking information is needed for this package.
  76. // Actual type-checking information can be accessed via the Types and TypesInfo fields.
  77. func (p *Package) NeedTypesInfo() {
  78. if p.TypesInfo != nil {
  79. return
  80. }
  81. p.NeedSyntax()
  82. p.loader.typeCheck(p)
  83. }
  84. // NeedSyntax indicates that a parsed AST is needed for this package.
  85. // Actual ASTs can be accessed via the Syntax field.
  86. func (p *Package) NeedSyntax() {
  87. if p.Syntax != nil {
  88. return
  89. }
  90. out := make([]*ast.File, len(p.CompiledGoFiles))
  91. var wg sync.WaitGroup
  92. wg.Add(len(p.CompiledGoFiles))
  93. for i, filename := range p.CompiledGoFiles {
  94. go func(i int, filename string) {
  95. defer wg.Done()
  96. src, err := ioutil.ReadFile(filename)
  97. if err != nil {
  98. p.AddError(err)
  99. return
  100. }
  101. out[i], err = p.loader.parseFile(filename, src)
  102. if err != nil {
  103. p.AddError(err)
  104. return
  105. }
  106. }(i, filename)
  107. }
  108. wg.Wait()
  109. for _, file := range out {
  110. if file == nil {
  111. return
  112. }
  113. }
  114. p.Syntax = out
  115. }
  116. // AddError adds an error to the errors associated with the given package.
  117. func (p *Package) AddError(err error) {
  118. switch typedErr := err.(type) {
  119. case *os.PathError:
  120. // file-reading errors
  121. p.Errors = append(p.Errors, packages.Error{
  122. Pos: typedErr.Path + ":1",
  123. Msg: typedErr.Err.Error(),
  124. Kind: packages.ParseError,
  125. })
  126. case scanner.ErrorList:
  127. // parsing/scanning errors
  128. for _, subErr := range typedErr {
  129. p.Errors = append(p.Errors, packages.Error{
  130. Pos: subErr.Pos.String(),
  131. Msg: subErr.Msg,
  132. Kind: packages.ParseError,
  133. })
  134. }
  135. case types.Error:
  136. // type-checking errors
  137. p.Errors = append(p.Errors, packages.Error{
  138. Pos: typedErr.Fset.Position(typedErr.Pos).String(),
  139. Msg: typedErr.Msg,
  140. Kind: packages.TypeError,
  141. })
  142. case ErrList:
  143. for _, subErr := range typedErr {
  144. p.AddError(subErr)
  145. }
  146. case PositionedError:
  147. p.Errors = append(p.Errors, packages.Error{
  148. Pos: p.loader.cfg.Fset.Position(typedErr.Pos).String(),
  149. Msg: typedErr.Error(),
  150. Kind: packages.UnknownError,
  151. })
  152. default:
  153. // should only happen for external errors, like ref checking
  154. p.Errors = append(p.Errors, packages.Error{
  155. Pos: p.ID + ":-",
  156. Msg: err.Error(),
  157. Kind: packages.UnknownError,
  158. })
  159. }
  160. }
  161. // loader loads packages and their imports. Loaded packages will have
  162. // type size, imports, and exports file information populated. Additional
  163. // information, like ASTs and type-checking information, can be accessed
  164. // via methods on individual packages.
  165. type loader struct {
  166. // Roots are the loaded "root" packages in the package graph loaded via
  167. // LoadRoots.
  168. Roots []*Package
  169. // cfg contains the package loading config (initialized on demand)
  170. cfg *packages.Config
  171. // packages contains the cache of Packages indexed by the underlying
  172. // package.Package, so that we don't ever produce two Packages with
  173. // the same underlying packages.Package.
  174. packages map[*packages.Package]*Package
  175. packagesMu sync.Mutex
  176. }
  177. // packageFor returns a wrapped Package for the given packages.Package,
  178. // ensuring that there's a one-to-one mapping between the two.
  179. // It's *not* threadsafe -- use packagesFor for that.
  180. func (l *loader) packageFor(pkgRaw *packages.Package) *Package {
  181. if l.packages[pkgRaw] == nil {
  182. l.packages[pkgRaw] = &Package{
  183. Package: pkgRaw,
  184. loader: l,
  185. }
  186. }
  187. return l.packages[pkgRaw]
  188. }
  189. // packagesFor returns a map of Package objects for each packages.Package in the input
  190. // map, ensuring that there's a one-to-one mapping between package.Package and Package
  191. // (as per packageFor).
  192. func (l *loader) packagesFor(pkgsRaw map[string]*packages.Package) map[string]*Package {
  193. l.packagesMu.Lock()
  194. defer l.packagesMu.Unlock()
  195. out := make(map[string]*Package, len(pkgsRaw))
  196. for name, rawPkg := range pkgsRaw {
  197. out[name] = l.packageFor(rawPkg)
  198. }
  199. return out
  200. }
  201. // typeCheck type-checks the given package.
  202. func (l *loader) typeCheck(pkg *Package) {
  203. // don't conflict with typeCheckFromExportData
  204. pkg.TypesInfo = &types.Info{
  205. Types: make(map[ast.Expr]types.TypeAndValue),
  206. Defs: make(map[*ast.Ident]types.Object),
  207. Uses: make(map[*ast.Ident]types.Object),
  208. Implicits: make(map[ast.Node]types.Object),
  209. Scopes: make(map[ast.Node]*types.Scope),
  210. Selections: make(map[*ast.SelectorExpr]*types.Selection),
  211. }
  212. pkg.Fset = l.cfg.Fset
  213. pkg.Types = types.NewPackage(pkg.PkgPath, pkg.Name)
  214. importer := importerFunc(func(path string) (*types.Package, error) {
  215. if path == "unsafe" {
  216. return types.Unsafe, nil
  217. }
  218. // The imports map is keyed by import path.
  219. importedPkg := pkg.Imports()[path]
  220. if importedPkg == nil {
  221. return nil, fmt.Errorf("package %q possibly creates an import loop", path)
  222. }
  223. // it's possible to have a call to check in parallel to a call to this
  224. // if one package in the package graph gets its dependency filtered out,
  225. // but another doesn't (so one wants a "dummy" package here, and another
  226. // wants the full check).
  227. //
  228. // Thus, we need to lock here (at least for the time being) to avoid
  229. // races between the above write to `pkg.Types` and this checking of
  230. // importedPkg.Types.
  231. importedPkg.Lock()
  232. defer importedPkg.Unlock()
  233. if importedPkg.Types != nil && importedPkg.Types.Complete() {
  234. return importedPkg.Types, nil
  235. }
  236. // if we haven't already loaded typecheck data, we don't care about this package's types
  237. return types.NewPackage(importedPkg.PkgPath, importedPkg.Name), nil
  238. })
  239. var errs []error
  240. // type-check
  241. checkConfig := &types.Config{
  242. Importer: importer,
  243. IgnoreFuncBodies: true, // we only need decl-level info
  244. Error: func(err error) {
  245. errs = append(errs, err)
  246. },
  247. Sizes: pkg.TypesSizes,
  248. }
  249. if err := types.NewChecker(checkConfig, l.cfg.Fset, pkg.Types, pkg.TypesInfo).Files(pkg.Syntax); err != nil {
  250. errs = append(errs, err)
  251. }
  252. // make sure that if a given sub-import is ill-typed, we mark this package as ill-typed as well.
  253. illTyped := len(errs) > 0
  254. if !illTyped {
  255. for _, importedPkg := range pkg.Imports() {
  256. if importedPkg.IllTyped {
  257. illTyped = true
  258. break
  259. }
  260. }
  261. }
  262. pkg.IllTyped = illTyped
  263. // publish errors to the package error list.
  264. for _, err := range errs {
  265. pkg.AddError(err)
  266. }
  267. }
  268. // parseFile parses the given file, including comments.
  269. func (l *loader) parseFile(filename string, src []byte) (*ast.File, error) {
  270. // skip function bodies
  271. file, err := parser.ParseFile(l.cfg.Fset, filename, src, parser.AllErrors|parser.ParseComments)
  272. if err != nil {
  273. return nil, err
  274. }
  275. return file, nil
  276. }
  277. // LoadRoots loads the given "root" packages by path, transitively loading
  278. // and all imports as well.
  279. //
  280. // Loaded packages will have type size, imports, and exports file information
  281. // populated. Additional information, like ASTs and type-checking information,
  282. // can be accessed via methods on individual packages.
  283. func LoadRoots(roots ...string) ([]*Package, error) {
  284. return LoadRootsWithConfig(&packages.Config{}, roots...)
  285. }
  286. // LoadRootsWithConfig functions like LoadRoots, except that it allows passing
  287. // a custom loading config. The config will be modified to suit the needs of
  288. // the loader.
  289. //
  290. // This is generally only useful for use in testing when you need to modify
  291. // loading settings to load from a fake location.
  292. func LoadRootsWithConfig(cfg *packages.Config, roots ...string) ([]*Package, error) {
  293. l := &loader{
  294. cfg: cfg,
  295. packages: make(map[*packages.Package]*Package),
  296. }
  297. l.cfg.Mode |= packages.LoadImports | packages.NeedTypesSizes
  298. if l.cfg.Fset == nil {
  299. l.cfg.Fset = token.NewFileSet()
  300. }
  301. // put our build flags first so that callers can override them
  302. l.cfg.BuildFlags = append([]string{"-tags", "ignore_autogenerated"}, l.cfg.BuildFlags...)
  303. rawPkgs, err := packages.Load(l.cfg, roots...)
  304. if err != nil {
  305. return nil, err
  306. }
  307. for _, rawPkg := range rawPkgs {
  308. l.Roots = append(l.Roots, l.packageFor(rawPkg))
  309. }
  310. return l.Roots, nil
  311. }
  312. // importFunc is an implementation of the single-method
  313. // types.Importer interface based on a function value.
  314. type importerFunc func(path string) (*types.Package, error)
  315. func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }