-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.odin
More file actions
111 lines (89 loc) · 2.21 KB
/
Copy pathmain.odin
File metadata and controls
111 lines (89 loc) · 2.21 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
package olox
import "core:fmt"
import "core:mem"
import "core:os"
import "core:strings"
DEBUG_TRACE_EXECUTION :: #config(DEBUG_TRACE_EXECUTION, false)
DEBUG_PRINT_CODE :: #config(DEBUG_PRINT_CODE, false)
DEBUG_VERBOSE :: #config(DEBUG_VERBOSE, false)
main :: proc() {
os.exit(run())
}
// hack(mo): we do this to make sure print_memory_issues is called even if we exit abnormally
run :: proc() -> int {
tracking_allocator, a := wrap_into_tracking_allocator(context.allocator)
context.allocator = a
defer print_memory_issues(tracking_allocator)
if len(os.args) == 1 {
return repl()
} else if len(os.args) == 2 {
return run_file(os.args[1])
} else {
fmt.printfln("Usage: olox [path]")
return 64
}
}
wrap_into_tracking_allocator :: proc(
current_allocator: mem.Allocator,
) -> (
^mem.Tracking_Allocator,
mem.Allocator,
) {
tracking_allocator := new(mem.Tracking_Allocator)
mem.tracking_allocator_init(tracking_allocator, current_allocator)
return tracking_allocator, mem.tracking_allocator(tracking_allocator)
}
print_memory_issues :: proc(a: ^mem.Tracking_Allocator) {
for _, value in a.allocation_map {
fmt.printfln("%v: Leaked %v bytes", value.location, value.size)
}
for x in a.bad_free_array {
fmt.printfln("Bad free at: %v", x.location)
}
}
run_file :: proc(path: string) -> int {
source, err := os.read_entire_file_from_filename_or_err(path)
if err != nil {
fmt.printfln("Could not read file '%s': %v", path, err)
return 74
}
vm := vm_init()
defer vm_free(&vm)
result := vm_interpret(&vm, string(source))
if result == InterpretResult.CompileError {
return 65
}
if result == InterpretResult.RuntimeError {
return 70
}
return 0
}
repl :: proc() -> int {
vm := vm_init()
defer vm_free(&vm)
buf: [1024]u8
for {
fmt.print("lox> ")
n, err := os.read(os.stdin, buf[:])
if err != nil {
fmt.printfln("Could not read line: %v", err)
os.exit(74)
}
line, ok := strings.substring_to(string(buf[:]), n - 1)
if !ok {
fmt.printfln("Line too long")
os.exit(74)
}
if line == "exit" {
break
}
result := vm_interpret(&vm, line)
if result == InterpretResult.CompileError {
return 65
}
if result == InterpretResult.RuntimeError {
return 70
}
}
return 0
}