-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
67 lines (56 loc) · 1.16 KB
/
main.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
package main
import (
"crisp/ast"
"crisp/eval"
"crisp/lexer"
"crisp/parser"
"crisp/repl"
"fmt"
"io/ioutil"
"os"
)
func main() {
if len(os.Args) < 2 {
// no filename passed in, so start the REPL
repl.Start(os.Stdin, os.Stdout, run)
return
}
// run the given program
filename := os.Args[1]
file, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Print("file not found: " + filename)
return
}
output, ok := run(string(file))
if !ok {
fmt.Println("Crisp encountered an error:")
}
fmt.Print(output)
}
func run(code string) (string, bool) {
l := lexer.New(code)
p := parser.New(l)
pTree, err := p.ParseProgram()
if err != nil {
return err.Error(), false
}
tr := ast.NewTranslator(eval.CreateNativeFuncs())
program := tr.Translate(pTree)
// check for translation errors
errStr := ""
errors := tr.Errors()
if len(errors) > 0 {
for _, msg := range errors {
errStr += fmt.Sprintf(" translator error: %q\n", msg)
}
return errStr, false
}
val, err := eval.Eval(eval.TopLevelEnv, program)
if err != nil {
errStr = fmt.Sprintf(" runtime error: %q\n", err)
return errStr, false
}
output := val.Inspect()
return output, true
}