-
Notifications
You must be signed in to change notification settings - Fork 24
/
compiler.go
115 lines (95 loc) · 2.73 KB
/
compiler.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package gscript
import (
"fmt"
"github.com/antlr/antlr4/runtime/Go/antlr"
"github.com/crossoverJie/gscript/internal"
"github.com/crossoverJie/gscript/log"
"github.com/crossoverJie/gscript/parser"
"github.com/crossoverJie/gscript/resolver"
"os"
"strings"
)
var Args []string
const (
RuntimeError = "RuntimeError"
)
type Compiler struct {
}
func NewCompiler() *Compiler {
return &Compiler{}
}
// CompilerWithoutNative 不包含标准库运行
func (c *Compiler) CompilerWithoutNative(script string) interface{} {
return c.compile(script)
}
// GetCompileInfo 获取编译的 AST 以及符号表
func (c *Compiler) GetCompileInfo(script string, isAST bool) string {
input := antlr.NewInputStream(script)
lexer := parser.NewGScriptLexer(input)
stream := antlr.NewCommonTokenStream(lexer, 0)
scriptParser := parser.NewGScriptParser(stream)
tree := scriptParser.Prog()
at := resolver.NewAnnotatedTree(tree, scriptParser)
walker := antlr.NewParseTreeWalker()
// 识别所有的类型、函数、scope
walker.Walk(resolver.NewTypeScopeResolver(at), tree)
// 变量、类型解析,所有使用到 typeType 的地方
walker.Walk(resolver.NewTypeResolver(at), tree)
if isAST {
return at.DumpAST()
} else {
return at.DumpSymbol()
}
}
func (c *Compiler) compile(script string) interface{} {
input := antlr.NewInputStream(script)
lexer := parser.NewGScriptLexer(input)
stream := antlr.NewCommonTokenStream(lexer, 0)
scriptParser := parser.NewGScriptParser(stream)
tree := scriptParser.Prog()
at := resolver.NewAnnotatedTree(tree, scriptParser)
walker := antlr.NewParseTreeWalker()
// 识别所有的类型、函数、scope
walker.Walk(resolver.NewTypeScopeResolver(at), tree)
// 变量、类型解析,所有使用到 typeType 的地方
walker.Walk(resolver.NewTypeResolver(at), tree)
// 消解变量、函数的引用
walker.Walk(resolver.NewRefResolver(at), tree)
// 语义检查
walker.Walk(NewSemanticResolver(at), tree)
// 闭包分析
resolver.NewClosureResolver(at).Analyze()
if at.IsCompileFail() {
return nil
}
visitor := NewVisitor(at)
return visitor.Visit(tree)
}
func (c *Compiler) Compiler(script string) interface{} {
runtimeError := os.Getenv(RuntimeError)
if runtimeError != "" {
defer func() {
if r := recover(); r != nil {
switch x := r.(type) {
case *log.Log:
fmt.Printf("runtime error: %s \n", x.String())
default:
panic(x)
}
}
}()
}
native := c.loadInternal()
script = native + script
return c.compile(script)
}
func (c *Compiler) loadInternal() string {
bytes, err := internal.Asset("internal/internal.gs")
//file, err := os.ReadFile("internal/internal.gs")
if err != nil {
panic(err)
}
v := string(bytes)
log.NativeLine = strings.Count(v, "\n") + 1
return v
}