-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.lua
More file actions
81 lines (58 loc) · 1.61 KB
/
compiler.lua
File metadata and controls
81 lines (58 loc) · 1.61 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
Instruction = require("Compiler/Instruction")
Error = require("Error")
dump = require("dump")
function init(arg)
if table.getn(arg) ~= 2 then
print("Usage: compiler <input_file> <output_file>")
return nil
end
input = fs.open(arg[1], "r")
if input == nil then
Error.print("Error opening file "..arg[1].." for reading")
return nil
end
output = fs.open(arg[2], "wb")
if output == nil then
Error.print("Error opening file "..arg[2].." for writing")
return nil
end
return input,output
end
function parse(input)
result = {}
line = ""
n = 1
while line ~= nil do
parsed = {}
for token in string.gmatch(line, "([$#%-%a%d]+)") do
table.insert(parsed, token)
end
parsingResult = Instruction.parse(parsed)
if parsingResult ~= nil then
if parsingResult.error then
Error.print(n, parsingResult, parsed)
return nil
end
table.insert(result, parsingResult)
end
line = input.readLine()
n = n + 1
end
return result
end
function writeOut(output, result)
for _,inst in ipairs(result) do
for _,byteCode in ipairs(inst) do
write(tostring(byteCode).." ")
output.write(byteCode)
end
print("")
end
end
input,output = init{...}
result = parse(input)
input.close()
if result ~= nil then
writeOut(output, result)
end
output.close()