-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
88 lines (79 loc) · 1.65 KB
/
Copy pathmain.go
File metadata and controls
88 lines (79 loc) · 1.65 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
package main
import (
"bufio"
"errors"
"fmt"
"os"
interpreter "github.com/shubhdevelop/YAPL/Interpreter"
"github.com/shubhdevelop/YAPL/Scanner"
"github.com/shubhdevelop/YAPL/environment"
"github.com/shubhdevelop/YAPL/parser"
"github.com/shubhdevelop/YAPL/state"
)
func run(source string) {
state.HadError = false // Reset error state
scanner := scanner.Scanner{Source: source}
tokens, err := scanner.ScanTokens()
interpreter := interpreter.Interpreter{
environment.NewEnvironment(),
}
parserInstance := parser.Parser{
Tokens: tokens,
}
if err != nil {
fmt.Println(errors.New("Error Scanning tokens"))
state.HadError = true
return
}
expr := parserInstance.Parse()
interpreter.Interpret(expr)
if state.HadError {
return
}
}
func runFile(path string) {
bytes, err := os.ReadFile(path)
if err != nil {
panic(errors.New("Error loading the file check the file path"))
}
source := string(bytes[:])
run(source)
if state.HadError {
os.Exit(65)
}
if state.HadRuntimeError {
os.Exit(70)
}
}
func runPrompt() {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print(">> ")
line, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error Reading the line")
continue
} else if line == "\n" || line == "" {
continue
} else if line == "clear\n" {
fmt.Print("\033[H\033[2J")
continue
} else if line == "exit\n" {
break
}
run(string(line))
if state.HadError {
state.HadError = false // Reset error state for next input
}
}
}
func main() {
args := os.Args[1:]
if len(args) > 1 {
panic(errors.New("usage Lox [script]"))
} else if len(args) == 1 {
runFile(args[0])
} else {
runPrompt()
}
}