github.com/switchupcb/yaegi@v0.10.2/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/switchupcb/yaegi/stdlib"
    10  )
    11  
    12  func TestCompileAST(t *testing.T) {
    13  	file, err := parser.ParseFile(token.NewFileSet(), "_.go", `
    14  		package main
    15  
    16  		import "fmt"
    17  
    18  		type Foo struct{}
    19  
    20  		var foo Foo
    21  		const bar = "asdf"
    22  
    23  		func main() {
    24  			fmt.Println(1)
    25  		}
    26  	`, 0)
    27  	if err != nil {
    28  		panic(err)
    29  	}
    30  	if len(file.Imports) != 1 || len(file.Decls) != 5 {
    31  		panic("wrong number of imports or decls")
    32  	}
    33  
    34  	dType := file.Decls[1].(*ast.GenDecl)
    35  	dVar := file.Decls[2].(*ast.GenDecl)
    36  	dConst := file.Decls[3].(*ast.GenDecl)
    37  	dFunc := file.Decls[4].(*ast.FuncDecl)
    38  
    39  	if dType.Tok != token.TYPE {
    40  		panic("decl[1] is not a type")
    41  	}
    42  	if dVar.Tok != token.VAR {
    43  		panic("decl[2] is not a var")
    44  	}
    45  	if dConst.Tok != token.CONST {
    46  		panic("decl[3] is not a const")
    47  	}
    48  
    49  	cases := []struct {
    50  		desc string
    51  		node ast.Node
    52  		skip string
    53  	}{
    54  		{desc: "file", node: file},
    55  		{desc: "import", node: file.Imports[0]},
    56  		{desc: "type", node: dType},
    57  		{desc: "var", node: dVar, skip: "not supported"},
    58  		{desc: "const", node: dConst},
    59  		{desc: "func", node: dFunc},
    60  		{desc: "block", node: dFunc.Body},
    61  		{desc: "expr", node: dFunc.Body.List[0]},
    62  	}
    63  
    64  	i := New(Options{})
    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  }