github.com/traefik/yaegi@v0.15.1/interp/compile_test.go (about) 1 package interp 2 3 import ( 4 "go/ast" 5 "go/parser" 6 "go/token" 7 "testing" 8 9 "github.com/traefik/yaegi/stdlib" 10 ) 11 12 func TestCompileAST(t *testing.T) { 13 i := New(Options{}) 14 file, err := parser.ParseFile(i.FileSet(), "_.go", ` 15 package main 16 17 import "fmt" 18 19 type Foo struct{} 20 21 var foo Foo 22 const bar = "asdf" 23 24 func main() { 25 fmt.Println(1) 26 } 27 `, 0) 28 if err != nil { 29 panic(err) 30 } 31 if len(file.Imports) != 1 || len(file.Decls) != 5 { 32 panic("wrong number of imports or decls") 33 } 34 35 dType := file.Decls[1].(*ast.GenDecl) 36 dVar := file.Decls[2].(*ast.GenDecl) 37 dConst := file.Decls[3].(*ast.GenDecl) 38 dFunc := file.Decls[4].(*ast.FuncDecl) 39 40 if dType.Tok != token.TYPE { 41 panic("decl[1] is not a type") 42 } 43 if dVar.Tok != token.VAR { 44 panic("decl[2] is not a var") 45 } 46 if dConst.Tok != token.CONST { 47 panic("decl[3] is not a const") 48 } 49 50 cases := []struct { 51 desc string 52 node ast.Node 53 skip string 54 }{ 55 {desc: "file", node: file, skip: "temporary ignore"}, 56 {desc: "import", node: file.Imports[0]}, 57 {desc: "type", node: dType}, 58 {desc: "var", node: dVar, skip: "not supported"}, 59 {desc: "const", node: dConst}, 60 {desc: "func", node: dFunc}, 61 {desc: "block", node: dFunc.Body}, 62 {desc: "expr", node: dFunc.Body.List[0]}, 63 } 64 65 _ = i.Use(stdlib.Symbols) 66 67 for _, c := range cases { 68 t.Run(c.desc, func(t *testing.T) { 69 if c.skip != "" { 70 t.Skip(c.skip) 71 } 72 73 i := i 74 if _, ok := c.node.(*ast.File); ok { 75 i = New(Options{}) 76 _ = i.Use(stdlib.Symbols) 77 } 78 _, err := i.CompileAST(c.node) 79 if err != nil { 80 t.Fatalf("Failed to compile %s: %v", c.desc, err) 81 } 82 }) 83 } 84 }