-
Notifications
You must be signed in to change notification settings - Fork 5
/
igop_yaegi_ast.go
80 lines (70 loc) · 1.86 KB
/
igop_yaegi_ast.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//go:build yaegiast
// +build yaegiast
package yaigop
import (
"errors"
"go/token"
"log"
"os"
"path/filepath"
"github.com/goplus/gop/cl"
"github.com/goplus/gop/parser"
"github.com/goplus/gox"
"github.com/traefik/yaegi/interp"
)
// -----------------------------------------------------------------------------
func CompileDir(it *interp.Interpreter, srcDir string) (app *interp.Program, err error) {
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, srcDir, nil, 0)
if err != nil {
return
}
mainPkg, ok := pkgs["main"]
if !ok {
return nil, errors.New("not a main package")
}
modDir, noCacheFile := findGoModDir(srcDir)
conf := &cl.Config{
Dir: modDir, TargetDir: srcDir, Fset: fset, CacheLoadPkgs: true, PersistLoadPkgs: !noCacheFile}
out, err := cl.NewPackage("", mainPkg, conf)
if err != nil {
return
}
conf.PkgsLoader.Save()
file := gox.ASTFile(out, false)
return it.CompileAST(file)
}
/*
// astFileToPkg translate ast.File to ast.Package
func astFileToPkg(file *ast.File, fileName string) (pkg *ast.Package) {
pkg = &ast.Package{
Name: file.Name.Name,
Files: make(map[string]*ast.File),
}
pkg.Files[fileName] = file
return
}
*/
func findGoModFile(dir string) (modfile string, noCacheFile bool, err error) {
modfile, err = cl.FindGoModFile(dir)
if err != nil {
home := os.Getenv("HOME")
modfile = home + "/gop/go.mod"
if fi, e := os.Lstat(modfile); e == nil && !fi.IsDir() {
return modfile, true, nil
}
modfile = home + "/goplus/go.mod"
if fi, e := os.Lstat(modfile); e == nil && !fi.IsDir() {
return modfile, true, nil
}
}
return
}
func findGoModDir(dir string) (string, bool) {
modfile, nocachefile, err := findGoModFile(dir)
if err != nil {
log.Fatalln("findGoModFile:", err)
}
return filepath.Dir(modfile), nocachefile
}
// -----------------------------------------------------------------------------