-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.lua
More file actions
98 lines (81 loc) · 1.84 KB
/
Copy pathmain.lua
File metadata and controls
98 lines (81 loc) · 1.84 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
setmetatable(_G, {
__index = function (t, k)
error('get global varaible: ' .. k, 2)
end;
__newindex = function (t, k, v)
error('set global varaible: ' .. k, 2)
end;
})
local parse = require 'parser'
local read_types = require 'read_types'
local check_types = require 'check_types'
local expr_to_stat = require 'expr_to_stat'
local codegen = require 'lua_codegen'
local function compile(istream, ostream)
if type(istream) == 'string' then
istream = istream:gmatch('.')
end
local s = {
raw_line = 1,
raw_col = 0,
}
function s.getch()
s.ch = istream()
if s.ch == '\n' then
s.raw_line, s.raw_col = s.raw_line + 1, 0
else
s.raw_col = s.raw_col + 1
end
end
local error_tbl = {}
function s.error(msg, cont, line, col)
error_tbl.msg = msg
error_tbl.cont = cont and true or false
error_tbl.line = line or s.line
error_tbl.col = col or s.col
error(error_tbl)
end
local next_tmp_id = 0
function s.tmp_name()
local n = '____tmp_' .. next_tmp_id
next_tmp_id = next_tmp_id + 1
return n
end
function s.throwaway_name()
return '____tmp_discarded'
end
local success, result = xpcall(function ()
s.getch()
local ast = parse(s)
ast = read_types(s, ast)
ast = check_types(s, ast)
ast = expr_to_stat(s, ast)
return ast
end, function (e)
return {e, debug.traceback('', 2)}
end)
if success then
codegen(result, ostream)
return true
else
if result[1] == error_tbl then
return nil, error_tbl
else
error(result[1] .. '\n' .. result[2])
end
end
end
local ifile = arg[1] and assert(io.open(arg[1])) or io.stdin
local function istream()
return ifile:read(1)
end
local out = {}
local function ostream(s)
out[#out +1] = s
end
local success, err = compile(istream, ostream)
if success then
print(table.concat(out))
else
print(('compilation error: %d:%d: %s'):format(err.line, err.col, err.msg))
end