| 1 |
/* |
| 2 |
Copyright 2015 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package parser |
| 18 |
|
| 19 |
import ( |
| 20 |
"fmt" |
| 21 |
"go/ast" |
| 22 |
"go/build" |
| 23 |
"go/constant" |
| 24 |
"go/parser" |
| 25 |
"go/token" |
| 26 |
tc "go/types" |
| 27 |
"io/ioutil" |
| 28 |
"os" |
| 29 |
"os/exec" |
| 30 |
"path" |
| 31 |
"path/filepath" |
| 32 |
"regexp" |
| 33 |
"sort" |
| 34 |
"strings" |
| 35 |
|
| 36 |
"k8s.io/gengo/types" |
| 37 |
"k8s.io/klog/v2" |
| 38 |
) |
| 39 |
|
| 40 |
// This clarifies when a pkg path has been canonicalized. |
| 41 |
type importPathString string |
| 42 |
|
| 43 |
// Builder lets you add all the go files in all the packages that you care |
| 44 |
// about, then constructs the type source data. |
| 45 |
type Builder struct { |
| 46 |
context *build.Context |
| 47 |
|
| 48 |
// If true, include *_test.go |
| 49 |
IncludeTestFiles bool |
| 50 |
|
| 51 |
// Map of package names to more canonical information about the package. |
| 52 |
// This might hold the same value for multiple names, e.g. if someone |
| 53 |
// referenced ./pkg/name or in the case of vendoring, which canonicalizes |
| 54 |
// differently that what humans would type. |
| 55 |
// |
| 56 |
// This must only be accessed via getLoadedBuildPackage and setLoadedBuildPackage |
| 57 |
buildPackages map[importPathString]*build.Package |
| 58 |
|
| 59 |
fset *token.FileSet |
| 60 |
// map of package path to list of parsed files |
| 61 |
parsed map[importPathString][]parsedFile |
| 62 |
// map of package path to absolute path (to prevent overlap) |
| 63 |
absPaths map[importPathString]string |
| 64 |
|
| 65 |
// Set by typeCheckPackage(), used by importPackage() and friends. |
| 66 |
typeCheckedPackages map[importPathString]*tc.Package |
| 67 |
|
| 68 |
// Map of package path to whether the user requested it or it was from |
| 69 |
// an import. |
| 70 |
userRequested map[importPathString]bool |
| 71 |
|
| 72 |
// All comments from everywhere in every parsed file. |
| 73 |
endLineToCommentGroup map[fileLine]*ast.CommentGroup |
| 74 |
|
| 75 |
// map of package to list of packages it imports. |
| 76 |
importGraph map[importPathString]map[string]struct{} |
| 77 |
} |
| 78 |
|
| 79 |
// parsedFile is for tracking files with name |
| 80 |
type parsedFile struct { |
| 81 |
name string |
| 82 |
file *ast.File |
| 83 |
} |
| 84 |
|
| 85 |
// key type for finding comments. |
| 86 |
type fileLine struct { |
| 87 |
file string |
| 88 |
line int |
| 89 |
} |
| 90 |
|
| 91 |
// New constructs a new builder. |
| 92 |
func New() *Builder { |
| 93 |
c := build.Default |
| 94 |
if c.GOROOT == "" { |
| 95 |
if p, err := exec.Command("which", "go").CombinedOutput(); err == nil { |
| 96 |
// The returned string will have some/path/bin/go, so remove the last two elements. |
| 97 |
c.GOROOT = filepath.Dir(filepath.Dir(strings.Trim(string(p), "\n"))) |
| 98 |
} else { |
| 99 |
klog.Warningf("Warning: $GOROOT not set, and unable to run `which go` to find it: %v\n", err) |
| 100 |
} |
| 101 |
} |
| 102 |
// Force this to off, since we don't properly parse CGo. All symbols must |
| 103 |
// have non-CGo equivalents. |
| 104 |
c.CgoEnabled = false |
| 105 |
return &Builder{ |
| 106 |
context: &c, |
| 107 |
buildPackages: map[importPathString]*build.Package{}, |
| 108 |
typeCheckedPackages: map[importPathString]*tc.Package{}, |
| 109 |
fset: token.NewFileSet(), |
| 110 |
parsed: map[importPathString][]parsedFile{}, |
| 111 |
absPaths: map[importPathString]string{}, |
| 112 |
userRequested: map[importPathString]bool{}, |
| 113 |
endLineToCommentGroup: map[fileLine]*ast.CommentGroup{}, |
| 114 |
importGraph: map[importPathString]map[string]struct{}{}, |
| 115 |
} |
| 116 |
} |
| 117 |
|
| 118 |
// AddBuildTags adds the specified build tags to the parse context. |
| 119 |
func (b *Builder) AddBuildTags(tags ...string) { |
| 120 |
b.context.BuildTags = append(b.context.BuildTags, tags...) |
| 121 |
} |
| 122 |
|
| 123 |
func (b *Builder) getLoadedBuildPackage(importPath string) (*build.Package, bool) { |
| 124 |
canonicalized := canonicalizeImportPath(importPath) |
| 125 |
if string(canonicalized) != importPath { |
| 126 |
klog.V(5).Infof("getLoadedBuildPackage: %s normalized to %s", importPath, canonicalized) |
| 127 |
} |
| 128 |
buildPkg, ok := b.buildPackages[canonicalized] |
| 129 |
return buildPkg, ok |
| 130 |
} |
| 131 |
func (b *Builder) setLoadedBuildPackage(importPath string, buildPkg *build.Package) { |
| 132 |
canonicalizedImportPath := canonicalizeImportPath(importPath) |
| 133 |
if string(canonicalizedImportPath) != importPath { |
| 134 |
klog.V(5).Infof("setLoadedBuildPackage: importPath %s normalized to %s", importPath, canonicalizedImportPath) |
| 135 |
} |
| 136 |
|
| 137 |
canonicalizedBuildPkgImportPath := canonicalizeImportPath(buildPkg.ImportPath) |
| 138 |
if string(canonicalizedBuildPkgImportPath) != buildPkg.ImportPath { |
| 139 |
klog.V(5).Infof("setLoadedBuildPackage: buildPkg.ImportPath %s normalized to %s", buildPkg.ImportPath, canonicalizedBuildPkgImportPath) |
| 140 |
} |
| 141 |
|
| 142 |
if canonicalizedImportPath != canonicalizedBuildPkgImportPath { |
| 143 |
klog.V(5).Infof("setLoadedBuildPackage: normalized importPath (%s) differs from buildPkg.ImportPath (%s)", canonicalizedImportPath, canonicalizedBuildPkgImportPath) |
| 144 |
} |
| 145 |
b.buildPackages[canonicalizedImportPath] = buildPkg |
| 146 |
b.buildPackages[canonicalizedBuildPkgImportPath] = buildPkg |
| 147 |
} |
| 148 |
|
| 149 |
// Get package information from the go/build package. Automatically excludes |
| 150 |
// e.g. test files and files for other platforms-- there is quite a bit of |
| 151 |
// logic of that nature in the build package. |
| 152 |
func (b *Builder) importBuildPackage(dir string) (*build.Package, error) { |
| 153 |
if buildPkg, ok := b.getLoadedBuildPackage(dir); ok { |
| 154 |
return buildPkg, nil |
| 155 |
} |
| 156 |
// This validates the `package foo // github.com/bar/foo` comments. |
| 157 |
buildPkg, err := b.importWithMode(dir, build.ImportComment) |
| 158 |
if err != nil { |
| 159 |
if _, ok := err.(*build.NoGoError); !ok { |
| 160 |
return nil, fmt.Errorf("unable to import %q: %v", dir, err) |
| 161 |
} |
| 162 |
} |
| 163 |
if buildPkg == nil { |
| 164 |
// Might be an empty directory. Try to just find the dir. |
| 165 |
buildPkg, err = b.importWithMode(dir, build.FindOnly) |
| 166 |
if err != nil { |
| 167 |
return nil, err |
| 168 |
} |
| 169 |
} |
| 170 |
|
| 171 |
// Remember it under the user-provided name. |
| 172 |
klog.V(5).Infof("saving buildPackage %s", dir) |
| 173 |
b.setLoadedBuildPackage(dir, buildPkg) |
| 174 |
|
| 175 |
return buildPkg, nil |
| 176 |
} |
| 177 |
|
| 178 |
// AddFileForTest adds a file to the set, without verifying that the provided |
| 179 |
// pkg actually exists on disk. The pkg must be of the form "canonical/pkg/path" |
| 180 |
// and the path must be the absolute path to the file. Because this bypasses |
| 181 |
// the normal recursive finding of package dependencies (on disk), test should |
| 182 |
// sort their test files topologically first, so all deps are resolved by the |
| 183 |
// time we need them. |
| 184 |
func (b *Builder) AddFileForTest(pkg string, path string, src []byte) error { |
| 185 |
if err := b.addFile(importPathString(pkg), path, src, true); err != nil { |
| 186 |
return err |
| 187 |
} |
| 188 |
if _, err := b.typeCheckPackage(importPathString(pkg), true); err != nil { |
| 189 |
return err |
| 190 |
} |
| 191 |
return nil |
| 192 |
} |
| 193 |
|
| 194 |
// addFile adds a file to the set. The pkgPath must be of the form |
| 195 |
// "canonical/pkg/path" and the path must be the absolute path to the file. A |
| 196 |
// flag indicates whether this file was user-requested or just from following |
| 197 |
// the import graph. |
| 198 |
func (b *Builder) addFile(pkgPath importPathString, path string, src []byte, userRequested bool) error { |
| 199 |
for _, p := range b.parsed[pkgPath] { |
| 200 |
if path == p.name { |
| 201 |
klog.V(5).Infof("addFile %s %s already parsed, skipping", pkgPath, path) |
| 202 |
return nil |
| 203 |
} |
| 204 |
} |
| 205 |
klog.V(6).Infof("addFile %s %s", pkgPath, path) |
| 206 |
p, err := parser.ParseFile(b.fset, path, src, parser.DeclarationErrors|parser.ParseComments) |
| 207 |
if err != nil { |
| 208 |
return err |
| 209 |
} |
| 210 |
|
| 211 |
// This is redundant with addDir, but some tests call AddFileForTest, which |
| 212 |
// call into here without calling addDir. |
| 213 |
b.userRequested[pkgPath] = userRequested || b.userRequested[pkgPath] |
| 214 |
|
| 215 |
b.parsed[pkgPath] = append(b.parsed[pkgPath], parsedFile{path, p}) |
| 216 |
for _, c := range p.Comments { |
| 217 |
position := b.fset.Position(c.End()) |
| 218 |
b.endLineToCommentGroup[fileLine{position.Filename, position.Line}] = c |
| 219 |
} |
| 220 |
|
| 221 |
// We have to get the packages from this specific file, in case the |
| 222 |
// user added individual files instead of entire directories. |
| 223 |
if b.importGraph[pkgPath] == nil { |
| 224 |
b.importGraph[pkgPath] = map[string]struct{}{} |
| 225 |
} |
| 226 |
for _, im := range p.Imports { |
| 227 |
importedPath := strings.Trim(im.Path.Value, `"`) |
| 228 |
b.importGraph[pkgPath][importedPath] = struct{}{} |
| 229 |
} |
| 230 |
return nil |
| 231 |
} |
| 232 |
|
| 233 |
// AddDir adds an entire directory, scanning it for go files. 'dir' should have |
| 234 |
// a single go package in it. GOPATH, GOROOT, and the location of your go |
| 235 |
// binary (`which go`) will all be searched if dir doesn't literally resolve. |
| 236 |
func (b *Builder) AddDir(dir string) error { |
| 237 |
_, err := b.importPackage(dir, true) |
| 238 |
return err |
| 239 |
} |
| 240 |
|
| 241 |
// AddDirRecursive is just like AddDir, but it also recursively adds |
| 242 |
// subdirectories; it returns an error only if the path couldn't be resolved; |
| 243 |
// any directories recursed into without go source are ignored. |
| 244 |
func (b *Builder) AddDirRecursive(dir string) error { |
| 245 |
// Add the root. |
| 246 |
if _, err := b.importPackage(dir, true); err != nil { |
| 247 |
klog.Warningf("Ignoring directory %v: %v", dir, err) |
| 248 |
} |
| 249 |
|
| 250 |
// filepath.Walk does not follow symlinks. We therefore evaluate symlinks and use that with |
| 251 |
// filepath.Walk. |
| 252 |
buildPkg, ok := b.getLoadedBuildPackage(dir) |
| 253 |
if !ok { |
| 254 |
return fmt.Errorf("no loaded build package for %s", dir) |
| 255 |
} |
| 256 |
realPath, err := filepath.EvalSymlinks(buildPkg.Dir) |
| 257 |
if err != nil { |
| 258 |
return err |
| 259 |
} |
| 260 |
|
| 261 |
fn := func(filePath string, info os.FileInfo, err error) error { |
| 262 |
if info != nil && info.IsDir() { |
| 263 |
rel := filepath.ToSlash(strings.TrimPrefix(filePath, realPath)) |
| 264 |
if rel != "" { |
| 265 |
// Make a pkg path. |
| 266 |
buildPkg, ok := b.getLoadedBuildPackage(dir) |
| 267 |
if !ok { |
| 268 |
return fmt.Errorf("no loaded build package for %s", dir) |
| 269 |
} |
| 270 |
pkg := path.Join(string(canonicalizeImportPath(buildPkg.ImportPath)), rel) |
| 271 |
|
| 272 |
// Add it. |
| 273 |
if _, err := b.importPackage(pkg, true); err != nil { |
| 274 |
klog.Warningf("Ignoring child directory %v: %v", pkg, err) |
| 275 |
} |
| 276 |
} |
| 277 |
} |
| 278 |
return nil |
| 279 |
} |
| 280 |
if err := filepath.Walk(realPath, fn); err != nil { |
| 281 |
return err |
| 282 |
} |
| 283 |
return nil |
| 284 |
} |
| 285 |
|
| 286 |
// AddDirTo adds an entire directory to a given Universe. Unlike AddDir, this |
| 287 |
// processes the package immediately, which makes it safe to use from within a |
| 288 |
// generator (rather than just at init time. 'dir' must be a single go package. |
| 289 |
// GOPATH, GOROOT, and the location of your go binary (`which go`) will all be |
| 290 |
// searched if dir doesn't literally resolve. |
| 291 |
// Deprecated. Please use AddDirectoryTo. |
| 292 |
func (b *Builder) AddDirTo(dir string, u *types.Universe) error { |
| 293 |
// We want all types from this package, as if they were directly added |
| 294 |
// by the user. They WERE added by the user, in effect. |
| 295 |
if _, err := b.importPackage(dir, true); err != nil { |
| 296 |
return err |
| 297 |
} |
| 298 |
pkg, ok := b.getLoadedBuildPackage(dir) |
| 299 |
if !ok { |
| 300 |
return fmt.Errorf("no such package: %q", dir) |
| 301 |
} |
| 302 |
return b.findTypesIn(canonicalizeImportPath(pkg.ImportPath), u) |
| 303 |
} |
| 304 |
|
| 305 |
// AddDirectoryTo adds an entire directory to a given Universe. Unlike AddDir, |
| 306 |
// this processes the package immediately, which makes it safe to use from |
| 307 |
// within a generator (rather than just at init time. 'dir' must be a single go |
| 308 |
// package. GOPATH, GOROOT, and the location of your go binary (`which go`) |
| 309 |
// will all be searched if dir doesn't literally resolve. |
| 310 |
func (b *Builder) AddDirectoryTo(dir string, u *types.Universe) (*types.Package, error) { |
| 311 |
// We want all types from this package, as if they were directly added |
| 312 |
// by the user. They WERE added by the user, in effect. |
| 313 |
if _, err := b.importPackage(dir, true); err != nil { |
| 314 |
return nil, err |
| 315 |
} |
| 316 |
pkg, ok := b.getLoadedBuildPackage(dir) |
| 317 |
if !ok || pkg == nil { |
| 318 |
return nil, fmt.Errorf("no such package: %q", dir) |
| 319 |
} |
| 320 |
path := canonicalizeImportPath(pkg.ImportPath) |
| 321 |
if err := b.findTypesIn(path, u); err != nil { |
| 322 |
return nil, err |
| 323 |
} |
| 324 |
return u.Package(string(path)), nil |
| 325 |
} |
| 326 |
|
| 327 |
// The implementation of AddDir. A flag indicates whether this directory was |
| 328 |
// user-requested or just from following the import graph. |
| 329 |
func (b *Builder) addDir(dir string, userRequested bool) error { |
| 330 |
klog.V(5).Infof("addDir %s", dir) |
| 331 |
buildPkg, err := b.importBuildPackage(dir) |
| 332 |
if err != nil { |
| 333 |
return err |
| 334 |
} |
| 335 |
canonicalPackage := canonicalizeImportPath(buildPkg.ImportPath) |
| 336 |
pkgPath := canonicalPackage |
| 337 |
if dir != string(canonicalPackage) { |
| 338 |
klog.V(5).Infof("addDir %s, canonical path is %s", dir, pkgPath) |
| 339 |
} |
| 340 |
|
| 341 |
// Sanity check the pkg dir has not changed. |
| 342 |
if prev, found := b.absPaths[pkgPath]; found { |
| 343 |
if buildPkg.Dir != prev { |
| 344 |
return fmt.Errorf("package %q (%s) previously resolved to %s", pkgPath, buildPkg.Dir, prev) |
| 345 |
} |
| 346 |
} else { |
| 347 |
b.absPaths[pkgPath] = buildPkg.Dir |
| 348 |
} |
| 349 |
|
| 350 |
files := []string{} |
| 351 |
files = append(files, buildPkg.GoFiles...) |
| 352 |
if b.IncludeTestFiles { |
| 353 |
files = append(files, buildPkg.TestGoFiles...) |
| 354 |
} |
| 355 |
|
| 356 |
for _, file := range files { |
| 357 |
if !strings.HasSuffix(file, ".go") { |
| 358 |
continue |
| 359 |
} |
| 360 |
absPath := filepath.Join(buildPkg.Dir, file) |
| 361 |
data, err := ioutil.ReadFile(absPath) |
| 362 |
if err != nil { |
| 363 |
return fmt.Errorf("while loading %q: %v", absPath, err) |
| 364 |
} |
| 365 |
err = b.addFile(pkgPath, absPath, data, userRequested) |
| 366 |
if err != nil { |
| 367 |
return fmt.Errorf("while parsing %q: %v", absPath, err) |
| 368 |
} |
| 369 |
} |
| 370 |
return nil |
| 371 |
} |
| 372 |
|
| 373 |
// regexErrPackageNotFound helps test the expected error for not finding a package. |
| 374 |
var regexErrPackageNotFound = regexp.MustCompile(`^unable to import ".*?":.*`) |
| 375 |
|
| 376 |
func isErrPackageNotFound(err error) bool { |
| 377 |
return regexErrPackageNotFound.MatchString(err.Error()) |
| 378 |
} |
| 379 |
|
| 380 |
// importPackage is a function that will be called by the type check package when it |
| 381 |
// needs to import a go package. 'path' is the import path. |
| 382 |
func (b *Builder) importPackage(dir string, userRequested bool) (*tc.Package, error) { |
| 383 |
klog.V(5).Infof("importPackage %s", dir) |
| 384 |
|
| 385 |
var pkgPath = importPathString(dir) |
| 386 |
|
| 387 |
// Get the canonical path if we can. |
| 388 |
if buildPkg, _ := b.getLoadedBuildPackage(dir); buildPkg != nil { |
| 389 |
canonicalPackage := canonicalizeImportPath(buildPkg.ImportPath) |
| 390 |
klog.V(5).Infof("importPackage %s, canonical path is %s", dir, canonicalPackage) |
| 391 |
pkgPath = canonicalPackage |
| 392 |
} |
| 393 |
|
| 394 |
// If we have not seen this before, process it now. |
| 395 |
ignoreError := false |
| 396 |
if _, found := b.parsed[pkgPath]; !found { |
| 397 |
// Ignore errors in paths that we're importing solely because |
| 398 |
// they're referenced by other packages. |
| 399 |
ignoreError = true |
| 400 |
|
| 401 |
// Add it. |
| 402 |
if err := b.addDir(dir, userRequested); err != nil { |
| 403 |
if isErrPackageNotFound(err) { |
| 404 |
klog.V(6).Info(err) |
| 405 |
return nil, nil |
| 406 |
} |
| 407 |
|
| 408 |
return nil, err |
| 409 |
} |
| 410 |
|
| 411 |
// Get the canonical path now that it has been added. |
| 412 |
if buildPkg, _ := b.getLoadedBuildPackage(dir); buildPkg != nil { |
| 413 |
canonicalPackage := canonicalizeImportPath(buildPkg.ImportPath) |
| 414 |
klog.V(5).Infof("importPackage %s, canonical path is %s", dir, canonicalPackage) |
| 415 |
pkgPath = canonicalPackage |
| 416 |
} |
| 417 |
} |
| 418 |
|
| 419 |
// If it was previously known, just check that the user-requestedness hasn't |
| 420 |
// changed. |
| 421 |
b.userRequested[pkgPath] = userRequested || b.userRequested[pkgPath] |
| 422 |
|
| 423 |
// Run the type checker. We may end up doing this to pkgs that are already |
| 424 |
// done, or are in the queue to be done later, but it will short-circuit, |
| 425 |
// and we can't miss pkgs that are only depended on. |
| 426 |
pkg, err := b.typeCheckPackage(pkgPath, !ignoreError) |
| 427 |
if err != nil { |
| 428 |
switch { |
| 429 |
case ignoreError && pkg != nil: |
| 430 |
klog.V(4).Infof("type checking encountered some issues in %q, but ignoring.\n", pkgPath) |
| 431 |
case !ignoreError && pkg != nil: |
| 432 |
klog.V(3).Infof("type checking encountered some errors in %q\n", pkgPath) |
| 433 |
return nil, err |
| 434 |
default: |
| 435 |
return nil, err |
| 436 |
} |
| 437 |
} |
| 438 |
|
| 439 |
return pkg, nil |
| 440 |
} |
| 441 |
|
| 442 |
type importAdapter struct { |
| 443 |
b *Builder |
| 444 |
} |
| 445 |
|
| 446 |
func (a importAdapter) Import(path string) (*tc.Package, error) { |
| 447 |
return a.b.importPackage(path, false) |
| 448 |
} |
| 449 |
|
| 450 |
// typeCheckPackage will attempt to return the package even if there are some |
| 451 |
// errors, so you may check whether the package is nil or not even if you get |
| 452 |
// an error. |
| 453 |
func (b *Builder) typeCheckPackage(pkgPath importPathString, logErr bool) (*tc.Package, error) { |
| 454 |
klog.V(5).Infof("typeCheckPackage %s", pkgPath) |
| 455 |
if pkg, ok := b.typeCheckedPackages[pkgPath]; ok { |
| 456 |
if pkg != nil { |
| 457 |
klog.V(6).Infof("typeCheckPackage %s already done", pkgPath) |
| 458 |
return pkg, nil |
| 459 |
} |
| 460 |
// We store a nil right before starting work on a package. So |
| 461 |
// if we get here and it's present and nil, that means there's |
| 462 |
// another invocation of this function on the call stack |
| 463 |
// already processing this package. |
| 464 |
return nil, fmt.Errorf("circular dependency for %q", pkgPath) |
| 465 |
} |
| 466 |
parsedFiles, ok := b.parsed[pkgPath] |
| 467 |
if !ok { |
| 468 |
return nil, fmt.Errorf("No files for pkg %q", pkgPath) |
| 469 |
} |
| 470 |
files := make([]*ast.File, len(parsedFiles)) |
| 471 |
for i := range parsedFiles { |
| 472 |
files[i] = parsedFiles[i].file |
| 473 |
} |
| 474 |
b.typeCheckedPackages[pkgPath] = nil |
| 475 |
c := tc.Config{ |
| 476 |
IgnoreFuncBodies: true, |
| 477 |
// Note that importAdapter can call b.importPackage which calls this |
| 478 |
// method. So there can't be cycles in the import graph. |
| 479 |
Importer: importAdapter{b}, |
| 480 |
Error: func(err error) { |
| 481 |
if logErr { |
| 482 |
klog.V(2).Infof("type checker: %v\n", err) |
| 483 |
} else { |
| 484 |
klog.V(3).Infof("type checker: %v\n", err) |
| 485 |
} |
| 486 |
}, |
| 487 |
} |
| 488 |
pkg, err := c.Check(string(pkgPath), b.fset, files, nil) |
| 489 |
b.typeCheckedPackages[pkgPath] = pkg // record the result whether or not there was an error |
| 490 |
return pkg, err |
| 491 |
} |
| 492 |
|
| 493 |
// FindPackages fetches a list of the user-imported packages. |
| 494 |
// Note that you need to call b.FindTypes() first. |
| 495 |
func (b *Builder) FindPackages() []string { |
| 496 |
// Iterate packages in a predictable order. |
| 497 |
pkgPaths := []string{} |
| 498 |
for k := range b.typeCheckedPackages { |
| 499 |
pkgPaths = append(pkgPaths, string(k)) |
| 500 |
} |
| 501 |
sort.Strings(pkgPaths) |
| 502 |
|
| 503 |
result := []string{} |
| 504 |
for _, pkgPath := range pkgPaths { |
| 505 |
if b.userRequested[importPathString(pkgPath)] { |
| 506 |
// Since walkType is recursive, all types that are in packages that |
| 507 |
// were directly mentioned will be included. We don't need to |
| 508 |
// include all types in all transitive packages, though. |
| 509 |
result = append(result, pkgPath) |
| 510 |
} |
| 511 |
} |
| 512 |
return result |
| 513 |
} |
| 514 |
|
| 515 |
// FindTypes finalizes the package imports, and searches through all the |
| 516 |
// packages for types. |
| 517 |
func (b *Builder) FindTypes() (types.Universe, error) { |
| 518 |
// Take a snapshot of pkgs to iterate, since this will recursively mutate |
| 519 |
// b.parsed. Iterate in a predictable order. |
| 520 |
pkgPaths := []string{} |
| 521 |
for pkgPath := range b.parsed { |
| 522 |
pkgPaths = append(pkgPaths, string(pkgPath)) |
| 523 |
} |
| 524 |
sort.Strings(pkgPaths) |
| 525 |
|
| 526 |
u := types.Universe{} |
| 527 |
for _, pkgPath := range pkgPaths { |
| 528 |
if err := b.findTypesIn(importPathString(pkgPath), &u); err != nil { |
| 529 |
return nil, err |
| 530 |
} |
| 531 |
} |
| 532 |
return u, nil |
| 533 |
} |
| 534 |
|
| 535 |
// addCommentsToType takes any accumulated comment lines prior to obj and |
| 536 |
// attaches them to the type t. |
| 537 |
func (b *Builder) addCommentsToType(obj tc.Object, t *types.Type) { |
| 538 |
c1 := b.priorCommentLines(obj.Pos(), 1) |
| 539 |
// c1.Text() is safe if c1 is nil |
| 540 |
t.CommentLines = splitLines(c1.Text()) |
| 541 |
if c1 == nil { |
| 542 |
t.SecondClosestCommentLines = splitLines(b.priorCommentLines(obj.Pos(), 2).Text()) |
| 543 |
} else { |
| 544 |
t.SecondClosestCommentLines = splitLines(b.priorCommentLines(c1.List[0].Slash, 2).Text()) |
| 545 |
} |
| 546 |
} |
| 547 |
|
| 548 |
// findTypesIn finalizes the package import and searches through the package |
| 549 |
// for types. |
| 550 |
func (b *Builder) findTypesIn(pkgPath importPathString, u *types.Universe) error { |
| 551 |
klog.V(5).Infof("findTypesIn %s", pkgPath) |
| 552 |
pkg := b.typeCheckedPackages[pkgPath] |
| 553 |
if pkg == nil { |
| 554 |
return fmt.Errorf("findTypesIn(%s): package is not known", pkgPath) |
| 555 |
} |
| 556 |
if !b.userRequested[pkgPath] { |
| 557 |
// Since walkType is recursive, all types that the |
| 558 |
// packages they asked for depend on will be included. |
| 559 |
// But we don't need to include all types in all |
| 560 |
// *packages* they depend on. |
| 561 |
klog.V(5).Infof("findTypesIn %s: package is not user requested", pkgPath) |
| 562 |
return nil |
| 563 |
} |
| 564 |
|
| 565 |
// We're keeping this package. This call will create the record. |
| 566 |
u.Package(string(pkgPath)).Name = pkg.Name() |
| 567 |
u.Package(string(pkgPath)).Path = pkg.Path() |
| 568 |
u.Package(string(pkgPath)).SourcePath = b.absPaths[pkgPath] |
| 569 |
|
| 570 |
for _, f := range b.parsed[pkgPath] { |
| 571 |
if _, fileName := filepath.Split(f.name); fileName == "doc.go" { |
| 572 |
tp := u.Package(string(pkgPath)) |
| 573 |
// findTypesIn might be called multiple times. Clean up tp.Comments |
| 574 |
// to avoid repeatedly fill same comments to it. |
| 575 |
tp.Comments = []string{} |
| 576 |
for i := range f.file.Comments { |
| 577 |
tp.Comments = append(tp.Comments, splitLines(f.file.Comments[i].Text())...) |
| 578 |
} |
| 579 |
if f.file.Doc != nil { |
| 580 |
tp.DocComments = splitLines(f.file.Doc.Text()) |
| 581 |
} |
| 582 |
} |
| 583 |
} |
| 584 |
|
| 585 |
s := pkg.Scope() |
| 586 |
for _, n := range s.Names() { |
| 587 |
obj := s.Lookup(n) |
| 588 |
tn, ok := obj.(*tc.TypeName) |
| 589 |
if ok { |
| 590 |
t := b.walkType(*u, nil, tn.Type()) |
| 591 |
b.addCommentsToType(obj, t) |
| 592 |
} |
| 593 |
tf, ok := obj.(*tc.Func) |
| 594 |
// We only care about functions, not concrete/abstract methods. |
| 595 |
if ok && tf.Type() != nil && tf.Type().(*tc.Signature).Recv() == nil { |
| 596 |
t := b.addFunction(*u, nil, tf) |
| 597 |
b.addCommentsToType(obj, t) |
| 598 |
} |
| 599 |
tv, ok := obj.(*tc.Var) |
| 600 |
if ok && !tv.IsField() { |
| 601 |
t := b.addVariable(*u, nil, tv) |
| 602 |
b.addCommentsToType(obj, t) |
| 603 |
} |
| 604 |
tconst, ok := obj.(*tc.Const) |
| 605 |
if ok { |
| 606 |
t := b.addConstant(*u, nil, tconst) |
| 607 |
b.addCommentsToType(obj, t) |
| 608 |
} |
| 609 |
} |
| 610 |
|
| 611 |
importedPkgs := []string{} |
| 612 |
for k := range b.importGraph[pkgPath] { |
| 613 |
importedPkgs = append(importedPkgs, string(k)) |
| 614 |
} |
| 615 |
sort.Strings(importedPkgs) |
| 616 |
for _, p := range importedPkgs { |
| 617 |
u.AddImports(string(pkgPath), p) |
| 618 |
} |
| 619 |
return nil |
| 620 |
} |
| 621 |
|
| 622 |
func (b *Builder) importWithMode(dir string, mode build.ImportMode) (*build.Package, error) { |
| 623 |
// This is a bit of a hack. The srcDir argument to Import() should |
| 624 |
// properly be the dir of the file which depends on the package to be |
| 625 |
// imported, so that vendoring can work properly and local paths can |
| 626 |
// resolve. We assume that there is only one level of vendoring, and that |
| 627 |
// the CWD is inside the GOPATH, so this should be safe. Nobody should be |
| 628 |
// using local (relative) paths except on the CLI, so CWD is also |
| 629 |
// sufficient. |
| 630 |
cwd, err := os.Getwd() |
| 631 |
if err != nil { |
| 632 |
return nil, fmt.Errorf("unable to get current directory: %v", err) |
| 633 |
} |
| 634 |
|
| 635 |
// normalize to drop /vendor/ if present |
| 636 |
dir = string(canonicalizeImportPath(dir)) |
| 637 |
|
| 638 |
buildPkg, err := b.context.Import(filepath.ToSlash(dir), cwd, mode) |
| 639 |
if err != nil { |
| 640 |
return nil, err |
| 641 |
} |
| 642 |
return buildPkg, nil |
| 643 |
} |
| 644 |
|
| 645 |
// if there's a comment on the line `lines` before pos, return its text, otherwise "". |
| 646 |
func (b *Builder) priorCommentLines(pos token.Pos, lines int) *ast.CommentGroup { |
| 647 |
position := b.fset.Position(pos) |
| 648 |
key := fileLine{position.Filename, position.Line - lines} |
| 649 |
return b.endLineToCommentGroup[key] |
| 650 |
} |
| 651 |
|
| 652 |
func splitLines(str string) []string { |
| 653 |
return strings.Split(strings.TrimRight(str, "\n"), "\n") |
| 654 |
} |
| 655 |
|
| 656 |
func tcFuncNameToName(in string) types.Name { |
| 657 |
name := strings.TrimPrefix(in, "func ") |
| 658 |
nameParts := strings.Split(name, "(") |
| 659 |
return tcNameToName(nameParts[0]) |
| 660 |
} |
| 661 |
|
| 662 |
func tcVarNameToName(in string) types.Name { |
| 663 |
nameParts := strings.Split(in, " ") |
| 664 |
// nameParts[0] is "var". |
| 665 |
// nameParts[2:] is the type of the variable, we ignore it for now. |
| 666 |
return tcNameToName(nameParts[1]) |
| 667 |
} |
| 668 |
|
| 669 |
func tcNameToName(in string) types.Name { |
| 670 |
// Detect anonymous type names. (These may have '.' characters because |
| 671 |
// embedded types may have packages, so we detect them specially.) |
| 672 |
if strings.HasPrefix(in, "struct{") || |
| 673 |
strings.HasPrefix(in, "<-chan") || |
| 674 |
strings.HasPrefix(in, "chan<-") || |
| 675 |
strings.HasPrefix(in, "chan ") || |
| 676 |
strings.HasPrefix(in, "func(") || |
| 677 |
strings.HasPrefix(in, "func (") || |
| 678 |
strings.HasPrefix(in, "*") || |
| 679 |
strings.HasPrefix(in, "map[") || |
| 680 |
strings.HasPrefix(in, "[") { |
| 681 |
return types.Name{Name: in} |
| 682 |
} |
| 683 |
|
| 684 |
// Otherwise, if there are '.' characters present, the name has a |
| 685 |
// package path in front. |
| 686 |
nameParts := strings.Split(in, ".") |
| 687 |
name := types.Name{Name: in} |
| 688 |
if n := len(nameParts); n >= 2 { |
| 689 |
// The final "." is the name of the type--previous ones must |
| 690 |
// have been in the package path. |
| 691 |
name.Package, name.Name = strings.Join(nameParts[:n-1], "."), nameParts[n-1] |
| 692 |
} |
| 693 |
return name |
| 694 |
} |
| 695 |
|
| 696 |
func (b *Builder) convertSignature(u types.Universe, t *tc.Signature) *types.Signature { |
| 697 |
signature := &types.Signature{} |
| 698 |
for i := 0; i < t.Params().Len(); i++ { |
| 699 |
signature.Parameters = append(signature.Parameters, b.walkType(u, nil, t.Params().At(i).Type())) |
| 700 |
signature.ParameterNames = append(signature.ParameterNames, t.Params().At(i).Name()) |
| 701 |
} |
| 702 |
for i := 0; i < t.Results().Len(); i++ { |
| 703 |
signature.Results = append(signature.Results, b.walkType(u, nil, t.Results().At(i).Type())) |
| 704 |
signature.ResultNames = append(signature.ResultNames, t.Results().At(i).Name()) |
| 705 |
} |
| 706 |
if r := t.Recv(); r != nil { |
| 707 |
signature.Receiver = b.walkType(u, nil, r.Type()) |
| 708 |
} |
| 709 |
signature.Variadic = t.Variadic() |
| 710 |
return signature |
| 711 |
} |
| 712 |
|
| 713 |
// walkType adds the type, and any necessary child types. |
| 714 |
func (b *Builder) walkType(u types.Universe, useName *types.Name, in tc.Type) *types.Type { |
| 715 |
// Most of the cases are underlying types of the named type. |
| 716 |
name := tcNameToName(in.String()) |
| 717 |
if useName != nil { |
| 718 |
name = *useName |
| 719 |
} |
| 720 |
|
| 721 |
switch t := in.(type) { |
| 722 |
case *tc.Struct: |
| 723 |
out := u.Type(name) |
| 724 |
if out.Kind != types.Unknown { |
| 725 |
return out |
| 726 |
} |
| 727 |
out.Kind = types.Struct |
| 728 |
for i := 0; i < t.NumFields(); i++ { |
| 729 |
f := t.Field(i) |
| 730 |
m := types.Member{ |
| 731 |
Name: f.Name(), |
| 732 |
Embedded: f.Anonymous(), |
| 733 |
Tags: t.Tag(i), |
| 734 |
Type: b.walkType(u, nil, f.Type()), |
| 735 |
CommentLines: splitLines(b.priorCommentLines(f.Pos(), 1).Text()), |
| 736 |
} |
| 737 |
out.Members = append(out.Members, m) |
| 738 |
} |
| 739 |
return out |
| 740 |
case *tc.Map: |
| 741 |
out := u.Type(name) |
| 742 |
if out.Kind != types.Unknown { |
| 743 |
return out |
| 744 |
} |
| 745 |
out.Kind = types.Map |
| 746 |
out.Elem = b.walkType(u, nil, t.Elem()) |
| 747 |
out.Key = b.walkType(u, nil, t.Key()) |
| 748 |
return out |
| 749 |
case *tc.Pointer: |
| 750 |
out := u.Type(name) |
| 751 |
if out.Kind != types.Unknown { |
| 752 |
return out |
| 753 |
} |
| 754 |
out.Kind = types.Pointer |
| 755 |
out.Elem = b.walkType(u, nil, t.Elem()) |
| 756 |
return out |
| 757 |
case *tc.Slice: |
| 758 |
out := u.Type(name) |
| 759 |
if out.Kind != types.Unknown { |
| 760 |
return out |
| 761 |
} |
| 762 |
out.Kind = types.Slice |
| 763 |
out.Elem = b.walkType(u, nil, t.Elem()) |
| 764 |
return out |
| 765 |
case *tc.Array: |
| 766 |
out := u.Type(name) |
| 767 |
if out.Kind != types.Unknown { |
| 768 |
return out |
| 769 |
} |
| 770 |
out.Kind = types.Array |
| 771 |
out.Elem = b.walkType(u, nil, t.Elem()) |
| 772 |
out.Len = in.(*tc.Array).Len() |
| 773 |
return out |
| 774 |
case *tc.Chan: |
| 775 |
out := u.Type(name) |
| 776 |
if out.Kind != types.Unknown { |
| 777 |
return out |
| 778 |
} |
| 779 |
out.Kind = types.Chan |
| 780 |
out.Elem = b.walkType(u, nil, t.Elem()) |
| 781 |
// TODO: need to store direction, otherwise raw type name |
| 782 |
// cannot be properly written. |
| 783 |
return out |
| 784 |
case *tc.Basic: |
| 785 |
out := u.Type(types.Name{ |
| 786 |
Package: "", |
| 787 |
Name: t.Name(), |
| 788 |
}) |
| 789 |
if out.Kind != types.Unknown { |
| 790 |
return out |
| 791 |
} |
| 792 |
out.Kind = types.Unsupported |
| 793 |
return out |
| 794 |
case *tc.Signature: |
| 795 |
out := u.Type(name) |
| 796 |
if out.Kind != types.Unknown { |
| 797 |
return out |
| 798 |
} |
| 799 |
out.Kind = types.Func |
| 800 |
out.Signature = b.convertSignature(u, t) |
| 801 |
return out |
| 802 |
case *tc.Interface: |
| 803 |
out := u.Type(name) |
| 804 |
if out.Kind != types.Unknown { |
| 805 |
return out |
| 806 |
} |
| 807 |
out.Kind = types.Interface |
| 808 |
t.Complete() |
| 809 |
for i := 0; i < t.NumMethods(); i++ { |
| 810 |
if out.Methods == nil { |
| 811 |
out.Methods = map[string]*types.Type{} |
| 812 |
} |
| 813 |
method := t.Method(i) |
| 814 |
name := tcNameToName(method.String()) |
| 815 |
mt := b.walkType(u, &name, method.Type()) |
| 816 |
mt.CommentLines = splitLines(b.priorCommentLines(method.Pos(), 1).Text()) |
| 817 |
out.Methods[method.Name()] = mt |
| 818 |
} |
| 819 |
return out |
| 820 |
case *tc.Named: |
| 821 |
var out *types.Type |
| 822 |
switch t.Underlying().(type) { |
| 823 |
case *tc.Named, *tc.Basic, *tc.Map, *tc.Slice: |
| 824 |
name := tcNameToName(t.String()) |
| 825 |
out = u.Type(name) |
| 826 |
if out.Kind != types.Unknown { |
| 827 |
return out |
| 828 |
} |
| 829 |
out.Kind = types.Alias |
| 830 |
out.Underlying = b.walkType(u, nil, t.Underlying()) |
| 831 |
default: |
| 832 |
// tc package makes everything "named" with an |
| 833 |
// underlying anonymous type--we remove that annoying |
| 834 |
// "feature" for users. This flattens those types |
| 835 |
// together. |
| 836 |
name := tcNameToName(t.String()) |
| 837 |
if out := u.Type(name); out.Kind != types.Unknown { |
| 838 |
return out // short circuit if we've already made this. |
| 839 |
} |
| 840 |
out = b.walkType(u, &name, t.Underlying()) |
| 841 |
} |
| 842 |
// If the underlying type didn't already add methods, add them. |
| 843 |
// (Interface types will have already added methods.) |
| 844 |
if len(out.Methods) == 0 { |
| 845 |
for i := 0; i < t.NumMethods(); i++ { |
| 846 |
if out.Methods == nil { |
| 847 |
out.Methods = map[string]*types.Type{} |
| 848 |
} |
| 849 |
method := t.Method(i) |
| 850 |
name := tcNameToName(method.String()) |
| 851 |
mt := b.walkType(u, &name, method.Type()) |
| 852 |
mt.CommentLines = splitLines(b.priorCommentLines(method.Pos(), 1).Text()) |
| 853 |
out.Methods[method.Name()] = mt |
| 854 |
} |
| 855 |
} |
| 856 |
return out |
| 857 |
default: |
| 858 |
out := u.Type(name) |
| 859 |
if out.Kind != types.Unknown { |
| 860 |
return out |
| 861 |
} |
| 862 |
out.Kind = types.Unsupported |
| 863 |
klog.Warningf("Making unsupported type entry %q for: %#v\n", out, t) |
| 864 |
return out |
| 865 |
} |
| 866 |
} |
| 867 |
|
| 868 |
func (b *Builder) addFunction(u types.Universe, useName *types.Name, in *tc.Func) *types.Type { |
| 869 |
name := tcFuncNameToName(in.String()) |
| 870 |
if useName != nil { |
| 871 |
name = *useName |
| 872 |
} |
| 873 |
out := u.Function(name) |
| 874 |
out.Kind = types.DeclarationOf |
| 875 |
out.Underlying = b.walkType(u, nil, in.Type()) |
| 876 |
return out |
| 877 |
} |
| 878 |
|
| 879 |
func (b *Builder) addVariable(u types.Universe, useName *types.Name, in *tc.Var) *types.Type { |
| 880 |
name := tcVarNameToName(in.String()) |
| 881 |
if useName != nil { |
| 882 |
name = *useName |
| 883 |
} |
| 884 |
out := u.Variable(name) |
| 885 |
out.Kind = types.DeclarationOf |
| 886 |
out.Underlying = b.walkType(u, nil, in.Type()) |
| 887 |
return out |
| 888 |
} |
| 889 |
|
| 890 |
func (b *Builder) addConstant(u types.Universe, useName *types.Name, in *tc.Const) *types.Type { |
| 891 |
name := tcVarNameToName(in.String()) |
| 892 |
if useName != nil { |
| 893 |
name = *useName |
| 894 |
} |
| 895 |
out := u.Constant(name) |
| 896 |
out.Kind = types.DeclarationOf |
| 897 |
out.Underlying = b.walkType(u, nil, in.Type()) |
| 898 |
|
| 899 |
var constval string |
| 900 |
|
| 901 |
// For strings, we use `StringVal()` to get the un-truncated, |
| 902 |
// un-quoted string. For other values, `.String()` is preferable to |
| 903 |
// get something relatively human readable (especially since for |
| 904 |
// floating point types, `ExactString()` will generate numeric |
| 905 |
// expressions using `big.(*Float).Text()`. |
| 906 |
switch in.Val().Kind() { |
| 907 |
case constant.String: |
| 908 |
constval = constant.StringVal(in.Val()) |
| 909 |
default: |
| 910 |
constval = in.Val().String() |
| 911 |
} |
| 912 |
|
| 913 |
out.ConstValue = &constval |
| 914 |
return out |
| 915 |
} |
| 916 |
|
| 917 |
// canonicalizeImportPath takes an import path and returns the actual package. |
| 918 |
// It doesn't support nested vendoring. |
| 919 |
func canonicalizeImportPath(importPath string) importPathString { |
| 920 |
if !strings.Contains(importPath, "/vendor/") { |
| 921 |
return importPathString(importPath) |
| 922 |
} |
| 923 |
|
| 924 |
return importPathString(importPath[strings.Index(importPath, "/vendor/")+len("/vendor/"):]) |
| 925 |
} |