-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
145 lines (115 loc) · 2.29 KB
/
main.go
File metadata and controls
145 lines (115 loc) · 2.29 KB
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package main
import (
"bufio"
"fmt"
"golox/interpreter"
"golox/parser"
"golox/scanner"
"golox/statement"
"os"
"time"
)
func PrintAst(stmt statement.Stmt) {
if stmt == nil {
return
}
switch t := stmt.(type) {
case *statement.Block:
fmt.Println("block")
fmt.Println(t.Statements)
case *statement.Expression:
fmt.Println("expression")
fmt.Println(t.Expression)
case *statement.Function:
fmt.Println("function")
fmt.Println(t.Name)
case *statement.If:
fmt.Println("if")
fmt.Println(t.Condition)
case *statement.Print:
fmt.Println("print")
fmt.Println(t.Expression)
case *statement.Return:
fmt.Println("return")
fmt.Println(t.Keyword)
case *statement.Variable:
fmt.Println("variable")
fmt.Println(t.Name)
case *statement.While:
fmt.Println("while")
fmt.Println(t.Body)
}
}
// TODO : move to somewhere else
type clock struct{}
func (c *clock) Arity() int {
return 0
}
func (c *clock) Call(
interpreter interpreter.Interpreter,
arguments []any,
) any {
return float64(time.Now().UnixMilli() / 1000)
}
func (c *clock) ToString() string {
return "<native fn>"
}
func main() {
// get arguments from program
args := os.Args
// golox command expects 1 argument
// which is the path of the script
if len(args) > 2 {
fmt.Println("Usage: golox [script]")
return
} else if len(args) == 2 {
runFile(args[1])
} else {
runPromt()
}
}
func runPromt() {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("> ")
text, err := reader.ReadString('\n')
if err != nil {
fmt.Println(err)
}
if text == "" {
break
}
run(text)
}
}
func runFile(path string) {
data, err := os.ReadFile(path)
if err != nil {
fmt.Println(err)
}
run(string(data))
}
func run(source string) {
scanner := scanner.New(source)
tokens := scanner.ScanTokens()
parser := parser.Parser{
Tokens: tokens,
}
statements, isError := parser.Parse()
if isError {
os.Exit(1)
}
// initialize global environment here for
// a fixed reference to the outermost global
// environment for the interpreter.
globalEnv := interpreter.Environment{
Enclosing: nil,
Values: make(map[string]any),
}
globalEnv.Define("clock", clock{})
interpreter := interpreter.Interpreter{
Environment: globalEnv,
Globals: globalEnv,
}
interpreter.Interpret(statements)
}