-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
81 lines (73 loc) · 1.41 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"github.com/elves/posixsh/pkg/eval"
"github.com/elves/posixsh/pkg/parse"
"src.elv.sh/pkg/diag"
"src.elv.sh/pkg/sys"
)
var (
printAST = flag.Bool("print-ast", false, "print AST")
)
func main() {
flag.Parse()
args := flag.Args()
ev := eval.NewEvaler(os.Args, eval.StdFiles)
if len(args) > 0 {
f, err := os.Open(args[0])
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
evalAll(ev, f)
return
} else if sys.IsATTY(os.Stdin.Fd()) {
repl(ev)
} else {
evalAll(ev, os.Stdin)
}
}
func repl(ev *eval.Evaler) {
stdin := bufio.NewReader(os.Stdin)
for {
fmt.Print("posixsh> ")
input, err := stdin.ReadString('\n')
if err != nil {
if err != io.EOF {
fmt.Println(err)
}
break
}
doEval(ev, input)
}
}
func evalAll(ev *eval.Evaler, r io.Reader) {
buf, err := io.ReadAll(r)
if err != nil {
fmt.Println(err)
}
doEval(ev, string(buf))
}
func doEval(ev *eval.Evaler, input string) {
n, err := parse.Parse(input)
if *printAST {
fmt.Println("node:", parse.PprintAST(n))
}
if err != nil {
fmt.Println("err:", err)
for _, entry := range err.(parse.Error).Errors {
sr := diag.NewContext("input", input, diag.PointRanging(entry.Position))
fmt.Printf(" %s\n", entry.Message)
fmt.Printf(" %s\n", sr.ShowCompact(""))
}
}
status := ev.EvalChunk(n)
if status != 0 {
fmt.Println("status:", status)
}
}