This repository has been archived by the owner on Jan 18, 2022. It is now read-only.
/
function.go
99 lines (81 loc) · 1.76 KB
/
function.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package function
import (
"fmt"
"go/ast"
"github.com/Akatsuki-py/gbdk-go/compiler/pkg/block"
"github.com/Akatsuki-py/gbdk-go/compiler/pkg/expr"
"golang.org/x/tools/go/analysis"
)
var Pass *analysis.Pass
type Function struct {
Name string
Body string
Args []Arg
Return string
}
type Arg struct {
Name string
Type string
}
func (f *Function) String() string {
args := ""
for i, arg := range f.Args {
if i == len(f.Args)-1 {
args += fmt.Sprintf("%s %s", arg.Type, arg.Name)
} else {
args += fmt.Sprintf("%s %s, ", arg.Type, arg.Name)
}
}
body := f.Body
return fmt.Sprintf(`%s %s(%s) %s
`, f.Return, f.Name, args, body)
}
func CompileFunc(funcDecl *ast.FuncDecl, pass *analysis.Pass) Function {
Pass = pass
f := Function{
Name: funcDecl.Name.String(),
Body: "",
Args: []Arg{},
}
ast.Inspect(funcDecl, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.FuncType:
f.Args, f.Return = compileFuncType(n)
return false
case *ast.BlockStmt:
f.Body = block.CompileBlock(n, pass)
return false
}
return true
})
return f
}
func compileFuncType(typeDecl *ast.FuncType) ([]Arg, string) {
params := typeDecl.Params
args := compileParams(params)
results := typeDecl.Results
result := compileResult(results)
return args, result
}
func compileParams(paramsDecl *ast.FieldList) []Arg {
args := []Arg{}
for _, field := range paramsDecl.List {
for _, ident := range field.Names {
a := Arg{
Name: ident.Name,
}
a.Type = string(expr.CompileExpr(field.Type))
args = append(args, a)
}
}
return args
}
func compileResult(resultDecl *ast.FieldList) string {
if resultDecl == nil {
return "void"
}
for _, field := range resultDecl.List {
return string(expr.CompileExpr(field.Type))
}
return string("void")
}