-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcommand.go
295 lines (249 loc) · 5.74 KB
/
command.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
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package main
import (
"bufio"
"bytes"
_ "embed"
"fmt"
"io"
"os"
"path"
"strconv"
"strings"
"github.com/chzyer/readline"
)
const PackFileMagicBytes = "oak \x19\x98\x10\x15"
//go:embed cmd/version.oak
var cmdversion string
//go:embed cmd/help.oak
var cmdhelp string
//go:embed cmd/cat.oak
var cmdcat string
//go:embed cmd/fmt.oak
var cmdfmt string
//go:embed cmd/pack.oak
var cmdpack string
//go:embed cmd/build.oak
var cmdbuild string
var cliCommands = map[string]string{
"version": cmdversion,
"help": cmdhelp,
"cat": cmdcat,
"fmt": cmdfmt,
"pack": cmdpack,
"build": cmdbuild,
}
func isStdinReadable() bool {
stdin, _ := os.Stdin.Stat()
return (stdin.Mode() & os.ModeCharDevice) == 0
}
func performCommandIfExists(command string) bool {
switch command {
case "repl":
runRepl()
return true
case "eval":
runEval()
return true
case "pipe":
runPipe()
return true
}
commandProgram, ok := cliCommands[command]
if !ok {
return false
}
ctx := NewContextWithCwd()
defer ctx.Wait()
ctx.LoadBuiltins()
if _, err := ctx.Eval(strings.NewReader(commandProgram)); err != nil {
fmt.Println(err)
os.Exit(1)
}
return true
}
func runPackFile() bool {
exeFilePath, err := os.Executable()
if err != nil {
// NOTE: os.Executable() isn't perfect, and fails in some less than
// ideal conditions (on certain operating systems, for example). So if
// we can't find an executable path we just bail.
return false
}
exeFile, err := os.Open(exeFilePath)
if err != nil {
return false
}
defer exeFile.Close()
info, err := exeFile.Stat()
if err != nil {
return false
}
exeFileSize := info.Size()
// 24 bundle size bytes, 8 magic bytes. See: cmd/pack.oak
readFrom := exeFileSize - 24 - 8
endOfFileBytes := make([]byte, 24+8, 24+8)
_, err = exeFile.ReadAt(endOfFileBytes, readFrom)
if err != nil {
return false
}
if !bytes.Equal(endOfFileBytes[24:], []byte(PackFileMagicBytes)) {
return false
}
bundleSizeString := bytes.TrimLeft(endOfFileBytes[0:24], " ")
bundleSize, err := strconv.ParseInt(string(bundleSizeString), 10, 64)
if err != nil {
// invalid bundle size
return false
}
if bundleSize > readFrom {
// bundle size too large
return false
}
readBundleFrom := readFrom - bundleSize
bundleBytes := make([]byte, bundleSize, bundleSize)
_, err = exeFile.ReadAt(bundleBytes, readBundleFrom)
if err != nil {
return false
}
ctx := NewContextWithCwd()
defer ctx.Wait()
ctx.LoadBuiltins()
if _, err := ctx.Eval(bytes.NewReader(bundleBytes)); err != nil {
fmt.Println(err)
os.Exit(1)
}
return true
}
func runFile(filePath string) {
file, err := os.Open(filePath)
if err != nil {
fmt.Printf("Could not open %s: %s\n", filePath, err)
os.Exit(1)
}
defer file.Close()
ctx := NewContext(path.Dir(filePath))
defer ctx.Wait()
ctx.LoadBuiltins()
if _, err = ctx.Eval(file); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func runStdin() {
ctx := NewContextWithCwd()
defer ctx.Wait()
ctx.LoadBuiltins()
if _, err := ctx.Eval(os.Stdin); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func runRepl() {
var historyFilePath string
homeDir, err := os.UserHomeDir()
if err == nil {
historyFilePath = path.Join(homeDir, ".oak_history")
}
rl, err := readline.NewEx(&readline.Config{
Prompt: "> ",
HistoryFile: historyFilePath,
})
if err != nil {
fmt.Println("Could not open the repl")
os.Exit(1)
}
defer rl.Close()
ctx := NewContextWithCwd()
ctx.LoadBuiltins()
ctx.mustLoadAllLibs()
for {
line, err := rl.Readline()
if err != nil { // io.EOF
break
}
// if no input, don't print the null output
if strings.TrimSpace(line) == "" {
continue
}
val, err := ctx.Eval(strings.NewReader(line))
if err != nil {
fmt.Println(err)
continue
}
fmt.Println(val)
// keep last evaluated result as __ in REPL
ctx.scope.put("__", val)
}
}
func runEval() {
ctx := NewContextWithCwd()
defer ctx.Wait()
ctx.LoadBuiltins()
ctx.mustLoadAllLibs()
if isStdinReadable() {
allInput, _ := io.ReadAll(os.Stdin)
allInputValue := StringValue(allInput)
ctx.scope.put("stdin", &allInputValue)
}
prog := strings.Join(os.Args[2:], " ")
if val, err := ctx.Eval(strings.NewReader(prog)); err == nil {
if stringVal, ok := val.(*StringValue); ok {
fmt.Println(string(*stringVal))
} else {
fmt.Println(val)
}
} else {
fmt.Println(err)
os.Exit(1)
}
}
func runPipe() {
if !isStdinReadable() {
return
}
ctx := NewContextWithCwd()
defer ctx.Wait()
ctx.LoadBuiltins()
ctx.mustLoadAllLibs()
rootScope := ctx.scope
stdin := bufio.NewReader(os.Stdin)
prog := strings.Join(os.Args[2:], " ")
for i := 0; ; i++ {
line, err := stdin.ReadBytes('\n')
if err == io.EOF {
break
} else if err != nil {
fmt.Println("Could not read piped input")
os.Exit(1)
}
line = bytes.TrimSuffix(line, []byte{'\n'})
lineValue := StringValue(line)
// each line gets its own top-level subscope to avoid collisions
ctx.subScope(&rootScope)
ctx.scope.put("line", &lineValue)
ctx.scope.put("i", IntValue(i))
// NOTE: currently, the same program is re-tokenized and re-parsed on
// every line. This is not efficient, and can be optimized in the
// future by parsing once and reusing a single AST.
outValue, err := ctx.Eval(strings.NewReader(prog))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
var outLine []byte
switch v := outValue.(type) {
case NullValue:
// lines that return ? are filtered out entirely, which lets Oak's
// shorthand `if pattern -> action` notation become very useful
continue
case *StringValue:
outLine = []byte(*v)
default:
outLine = []byte(outValue.String())
}
if _, err := os.Stdout.Write(append(outLine, '\n')); err != nil {
fmt.Println("Could not write piped output")
os.Exit(1)
}
}
}