-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
105 lines (86 loc) · 2.15 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
_ "embed"
"fmt"
"github.com/gravataLonga/ninja/evaluator"
"github.com/gravataLonga/ninja/lexer"
"github.com/gravataLonga/ninja/object"
"github.com/gravataLonga/ninja/parser"
"github.com/gravataLonga/ninja/repl"
flag "github.com/spf13/pflag"
"io"
"os"
"strings"
)
//go:embed version.txt
var version string
var exec = flag.StringP("exec", "e", "", "Runs the given code.")
var astS = flag.BoolP("ast", "a", false, "Return AST structure")
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Version: %s. \nUsage: ninja [flags] [program file] [arguments]\n\nAvailable flags:\n", version)
flag.PrintDefaults()
}
flag.Parse()
args := flag.Args()
object.StandardInput = os.Stdin
object.StandardOutput = os.Stdout
object.Arguments = args
object.ExitFunction = os.Exit
if len(os.Args) == 1 {
runRepl(os.Stdin, os.Stdout)
return
}
if len(*exec) > 0 {
execCode(*exec, os.Stdout)
return
}
file, err := os.ReadFile(os.Args[1])
if err != nil {
_, err := fmt.Fprintf(os.Stderr, "%v", err)
if err != nil {
os.Exit(1)
return
}
os.Exit(1)
return
}
execCode(string(file), os.Stdout)
}
func runRepl(in io.Reader, out io.Writer) {
replProgram := repl.NewRepel(out, in)
replProgram.Version(version)
replProgram.Start()
}
func execCode(input string, writer io.Writer) {
env := object.NewEnvironment()
l := lexer.New(strings.NewReader(input))
p := parser.New(l)
// s := semantic.New()
program := p.ParseProgram()
if len(p.Errors()) > 0 {
printParserErrors(p.Errors(), writer)
return
}
/*program = s.Analysis(program)
if len(s.Errors()) != 0 {
printSemanticErrorsErrors(s.Errors(), writer)
return
}*/
evaluated := evaluator.Eval(program, env)
if evaluated != nil {
fmt.Fprintf(writer, evaluated.Inspect())
}
}
func printParserErrors(errors []string, writer io.Writer) {
fmt.Fprintf(writer, "🔥 Fire at core! parser errors:")
for _, msg := range errors {
fmt.Fprintf(writer, "\t %s\n", msg)
}
}
func printSemanticErrorsErrors(errors []string, writer io.Writer) {
fmt.Fprintf(writer, "🔥 Fire at core! semantic errors:")
for _, msg := range errors {
fmt.Fprintf(writer, "\t %s\n", msg)
}
}