| 1 | package interp |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | "io/fs" |
| 7 | "path" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | // importSrc calls gta on the source code for the package identified by |
| 13 | // importPath. rPath is the relative path to the directory containing the source |
| 14 | // code for the package. It can also be "main" as a special value. |
| 15 | func (interp *Interpreter) importSrc(rPath, importPath string, skipTest bool) (string, error) { |
| 16 | var dir string |
| 17 | var err error |
| 18 | |
| 19 | if interp.srcPkg[importPath] != nil { |
| 20 | name, ok := interp.pkgNames[importPath] |
| 21 | if !ok { |
| 22 | return "", fmt.Errorf("inconsistent knowledge about %s", importPath) |
| 23 | } |
| 24 | return name, nil |
| 25 | } |
| 26 | |
| 27 | // For relative import paths in the form "./xxx" or "../xxx", the initial |
| 28 | // base path is the directory of the interpreter input file, or "." if no file |
| 29 | // was provided. |
| 30 | // In all other cases, absolute import paths are resolved from the GOPATH |
| 31 | // and the nested "vendor" directories. |
| 32 | if isPathRelative(importPath) { |
| 33 | if rPath == mainID { |
| 34 | rPath = "." |
| 35 | } |
| 36 | dir = path.Join(path.Dir(interp.name), rPath, importPath) |
| 37 | } else if dir, rPath, err = interp.pkgDir(filepath.ToSlash(interp.context.GOPATH), rPath, importPath); err != nil { |
| 38 | // Try again, assuming a root dir at the source location. |
| 39 | if rPath, err = interp.rootFromSourceLocation(); err != nil { |
| 40 | return "", err |
| 41 | } |
| 42 | if dir, rPath, err = interp.pkgDir(filepath.ToSlash(interp.context.GOPATH), rPath, importPath); err != nil { |
| 43 | return "", err |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | if interp.rdir[importPath] { |
| 48 | return "", fmt.Errorf("import cycle not allowed\n\timports %s", importPath) |
| 49 | } |
| 50 | interp.rdir[importPath] = true |
| 51 | |
| 52 | files, err := fs.ReadDir(interp.opt.filesystem, dir) |
| 53 | if err != nil { |
| 54 | return "", err |
| 55 | } |
| 56 | |
| 57 | var initNodes []*node |
| 58 | var rootNodes []*node |
| 59 | revisit := make(map[string][]*node) |
| 60 | |
| 61 | var root *node |
| 62 | var pkgName string |
| 63 | |
| 64 | // Parse source files. |
| 65 | for _, file := range files { |
| 66 | name := file.Name() |
| 67 | if skipFile(&interp.context, name, skipTest) { |
| 68 | continue |
| 69 | } |
| 70 | |
| 71 | name = path.Join(dir, name) |
| 72 | var buf []byte |
| 73 | if buf, err = fs.ReadFile(interp.opt.filesystem, name); err != nil { |
| 74 | return "", err |
| 75 | } |
| 76 | |
| 77 | n, err := interp.parse(string(buf), name, false) |
| 78 | if err != nil { |
| 79 | return "", err |
| 80 | } |
| 81 | if n == nil { |
| 82 | continue |
| 83 | } |
| 84 | |
| 85 | var pname string |
| 86 | if pname, root, err = interp.ast(n); err != nil { |
| 87 | return "", err |
| 88 | } |
| 89 | if root == nil { |
| 90 | continue |
| 91 | } |
| 92 | |
| 93 | if interp.astDot { |
| 94 | dotCmd := interp.dotCmd |
| 95 | if dotCmd == "" { |
| 96 | dotCmd = defaultDotCmd(name, "yaegi-ast-") |
| 97 | } |
| 98 | root.astDot(dotWriter(dotCmd), name) |
| 99 | } |
| 100 | if pkgName == "" { |
| 101 | pkgName = pname |
| 102 | } else if pkgName != pname && skipTest { |
| 103 | return "", fmt.Errorf("found packages %s and %s in %s", pkgName, pname, dir) |
| 104 | } |
| 105 | rootNodes = append(rootNodes, root) |
| 106 | |
| 107 | subRPath := effectivePkg(rPath, importPath) |
| 108 | var list []*node |
| 109 | list, err = interp.gta(root, subRPath, importPath, pkgName) |
| 110 | if err != nil { |
| 111 | return "", err |
| 112 | } |
| 113 | revisit[subRPath] = append(revisit[subRPath], list...) |
| 114 | } |
| 115 | |
| 116 | // Revisit incomplete nodes where GTA could not complete. |
| 117 | for _, nodes := range revisit { |
| 118 | if err = interp.gtaRetry(nodes, importPath, pkgName); err != nil { |
| 119 | return "", err |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | // Generate control flow graphs. |
| 124 | for _, root := range rootNodes { |
| 125 | var nodes []*node |
| 126 | if nodes, err = interp.cfg(root, nil, importPath, pkgName); err != nil { |
| 127 | return "", err |
| 128 | } |
| 129 | initNodes = append(initNodes, nodes...) |
| 130 | } |
| 131 | |
| 132 | // Register source package in the interpreter. The package contains only |
| 133 | // the global symbols in the package scope. |
| 134 | interp.mutex.Lock() |
| 135 | gs := interp.scopes[importPath] |
| 136 | if gs == nil { |
| 137 | interp.mutex.Unlock() |
| 138 | // A nil scope means that no even an empty package is created from source. |
| 139 | return "", fmt.Errorf("no Go files in %s", dir) |
| 140 | } |
| 141 | interp.srcPkg[importPath] = gs.sym |
| 142 | interp.pkgNames[importPath] = pkgName |
| 143 | |
| 144 | interp.frame.mutex.Lock() |
| 145 | interp.resizeFrame() |
| 146 | interp.frame.mutex.Unlock() |
| 147 | interp.mutex.Unlock() |
| 148 | |
| 149 | // Once all package sources have been parsed, execute entry points then init functions. |
| 150 | for _, n := range rootNodes { |
| 151 | if err = genRun(n); err != nil { |
| 152 | return "", err |
| 153 | } |
| 154 | interp.run(n, nil) |
| 155 | } |
| 156 | |
| 157 | // Wire and execute global vars in global scope gs. |
| 158 | n, err := genGlobalVars(rootNodes, gs) |
| 159 | if err != nil { |
| 160 | return "", err |
| 161 | } |
| 162 | interp.run(n, nil) |
| 163 | |
| 164 | // Add main to list of functions to run, after all inits. |
| 165 | if m := gs.sym[mainID]; pkgName == mainID && m != nil && skipTest { |
| 166 | initNodes = append(initNodes, m.node) |
| 167 | } |
| 168 | |
| 169 | for _, n := range initNodes { |
| 170 | interp.run(n, interp.frame) |
| 171 | } |
| 172 | |
| 173 | return pkgName, nil |
| 174 | } |
| 175 | |
| 176 | // rootFromSourceLocation returns the path to the directory containing the input |
| 177 | // Go file given to the interpreter, relative to $GOPATH/src. |
| 178 | // It is meant to be called in the case when the initial input is a main package. |
| 179 | func (interp *Interpreter) rootFromSourceLocation() (string, error) { |
| 180 | sourceFile := interp.name |
| 181 | if sourceFile == DefaultSourceName { |
| 182 | return "", nil |
| 183 | } |
| 184 | |
| 185 | _, isRealFS := interp.opt.filesystem.(*realFS) |
| 186 | if isRealFS { |
| 187 | // In the "real" FS, GOPATH will be an absolute path, so we need to convert |
| 188 | // the source file to an absolute path to compare them. |
| 189 | absPath, err := filepath.Abs(filepath.FromSlash(sourceFile)) |
| 190 | if err != nil { |
| 191 | return "", err |
| 192 | } |
| 193 | sourceFile = filepath.ToSlash(absPath) |
| 194 | } |
| 195 | pkgDir := path.Dir(sourceFile) |
| 196 | goPath := path.Join(filepath.ToSlash(interp.context.GOPATH), "src") + "/" |
| 197 | if !strings.HasPrefix(pkgDir, goPath) { |
| 198 | return "", fmt.Errorf("package location %s not in GOPATH", pkgDir) |
| 199 | } |
| 200 | return strings.TrimPrefix(pkgDir, goPath), nil |
| 201 | } |
| 202 | |
| 203 | // pkgDir returns the absolute path in filesystem for a package given its import path |
| 204 | // and the root of the subtree dependencies. |
| 205 | func (interp *Interpreter) pkgDir(goPath string, root, importPath string) (string, string, error) { |
| 206 | rPath := path.Join(root, "vendor") |
| 207 | dir := path.Join(goPath, "src", rPath, importPath) |
| 208 | |
| 209 | if _, err := fs.Stat(interp.opt.filesystem, dir); err == nil { |
| 210 | return dir, rPath, nil // found! |
| 211 | } |
| 212 | |
| 213 | dir = path.Join(goPath, "src", effectivePkg(root, importPath)) |
| 214 | |
| 215 | if _, err := fs.Stat(interp.opt.filesystem, dir); err == nil { |
| 216 | return dir, root, nil // found! |
| 217 | } |
| 218 | |
| 219 | if root == "" { |
| 220 | if interp.context.GOPATH == "" { |
| 221 | return "", "", fmt.Errorf("unable to find source related to: %q. Either the GOPATH environment variable, or the Interpreter.Options.GoPath needs to be set", importPath) |
| 222 | } |
| 223 | return "", "", fmt.Errorf("unable to find source related to: %q", importPath) |
| 224 | } |
| 225 | |
| 226 | rootPath := path.Join(goPath, "src", root) |
| 227 | prevRoot, err := previousRoot(interp.opt.filesystem, rootPath, root) |
| 228 | if err != nil { |
| 229 | return "", "", err |
| 230 | } |
| 231 | |
| 232 | return interp.pkgDir(goPath, prevRoot, importPath) |
| 233 | } |
| 234 | |
| 235 | const vendor = "vendor" |
| 236 | |
| 237 | // Find the previous source root (vendor > vendor > ... > GOPATH). |
| 238 | func previousRoot(filesystem fs.FS, rootPath, root string) (string, error) { |
| 239 | rootPath = path.Clean(rootPath) |
| 240 | parent, final := path.Split(rootPath) |
| 241 | parent = path.Clean(parent) |
| 242 | |
| 243 | // TODO(mpl): maybe it works for the special case main, but can't be bothered for now. |
| 244 | if root != mainID && final != vendor { |
| 245 | root = strings.TrimSuffix(root, "/") |
| 246 | prefix := strings.TrimSuffix(strings.TrimSuffix(rootPath, root), "/") |
| 247 | |
| 248 | // look for the closest vendor in one of our direct ancestors, as it takes priority. |
| 249 | var vendored string |
| 250 | for { |
| 251 | fi, err := fs.Stat(filesystem, path.Join(parent, vendor)) |
| 252 | if err == nil && fi.IsDir() { |
| 253 | vendored = strings.TrimPrefix(strings.TrimPrefix(parent, prefix), "/") |
| 254 | break |
| 255 | } |
| 256 | if !errors.Is(err, fs.ErrNotExist) { |
| 257 | return "", err |
| 258 | } |
| 259 | // stop when we reach GOPATH/src |
| 260 | if parent == prefix { |
| 261 | break |
| 262 | } |
| 263 | |
| 264 | // stop when we reach GOPATH/src/blah |
| 265 | parent = path.Dir(parent) |
| 266 | if parent == prefix { |
| 267 | break |
| 268 | } |
| 269 | |
| 270 | // just an additional failsafe, stop if we reach the filesystem root, or dot (if |
| 271 | // we are dealing with relative paths). |
| 272 | // TODO(mpl): It should probably be a critical error actually, |
| 273 | // as we shouldn't have gone that high up in the tree. |
| 274 | // TODO(dennwc): This partially fails on Windows, since it cannot recognize drive letters as "root". |
| 275 | if parent == "/" || parent == "." || parent == "" { |
| 276 | break |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | if vendored != "" { |
| 281 | return vendored, nil |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | // TODO(mpl): the algorithm below might be redundant with the one above, |
| 286 | // but keeping it for now. Investigate/simplify/remove later. |
| 287 | splitRoot := strings.Split(root, "/") |
| 288 | var index int |
| 289 | for i := len(splitRoot) - 1; i >= 0; i-- { |
| 290 | if splitRoot[i] == "vendor" { |
| 291 | index = i |
| 292 | break |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | if index == 0 { |
| 297 | return "", nil |
| 298 | } |
| 299 | |
| 300 | return path.Join(splitRoot[:index]...), nil |
| 301 | } |
| 302 | |
| 303 | func effectivePkg(root, p string) string { |
| 304 | splitRoot := strings.Split(root, "/") |
| 305 | splitPath := strings.Split(p, "/") |
| 306 | |
| 307 | var result []string |
| 308 | |
| 309 | rootIndex := 0 |
| 310 | prevRootIndex := 0 |
| 311 | for i := 0; i < len(splitPath); i++ { |
| 312 | part := splitPath[len(splitPath)-1-i] |
| 313 | |
| 314 | index := len(splitRoot) - 1 - rootIndex |
| 315 | if index > 0 && part == splitRoot[index] && i != 0 { |
| 316 | prevRootIndex = rootIndex |
| 317 | rootIndex++ |
| 318 | } else if prevRootIndex == rootIndex { |
| 319 | result = append(result, part) |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | var frag string |
| 324 | for i := len(result) - 1; i >= 0; i-- { |
| 325 | frag = path.Join(frag, result[i]) |
| 326 | } |
| 327 | |
| 328 | return path.Join(root, frag) |
| 329 | } |
| 330 | |
| 331 | // isPathRelative returns true if path starts with "./" or "../". |
| 332 | // It is intended for use on import paths, where "/" is always the directory separator. |
| 333 | func isPathRelative(s string) bool { |
| 334 | return strings.HasPrefix(s, "./") || strings.HasPrefix(s, "../") |
| 335 | } |