forked from compy-toys/metalua
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetalua.lua
More file actions
Latest commit
executable file
·276 lines (239 loc) · 8.99 KB
/
Copy pathmetalua.lua
File metadata and controls
executable file
·276 lines (239 loc) · 8.99 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
-------------------------------------------------------------------------------
-- Copyright (c) 2006-2013 Fabien Fleutot and others.
--
-- All rights reserved.
--
-- This program and the accompanying materials are made available
-- under the terms of the Eclipse Public License v1.0 which
-- accompanies this distribution, and is available at
-- http://www.eclipse.org/legal/epl-v10.html
--
-- This program and the accompanying materials are also made available
-- under the terms of the MIT public license which accompanies this
-- distribution, and is available at http://www.lua.org/license.html
--
-- Contributors:
-- Fabien Fleutot - API and implementation
--
-------------------------------------------------------------------------------
-- Survive lack of checks
ifnotpcall(require, 'checks') thenfunctionpackage.preload.checks() functionchecks() endendend
-- Main file for the metalua executable
require'metalua.loader' -- load *.mlue files
require'metalua.compiler.globals' -- metalua-aware loadstring, dofile etc.
localalt_getopt=require'alt_getopt'
localpp=require'metalua.pprint'
localmlc=require'metalua.compiler'
localM= { }
localAST_COMPILE_ERROR_NUMBER=-1
localRUNTIME_ERROR_NUMBER=-3
localalt_getopt_options="f:l:e:o:xivaASbs"
locallong_opts= {
file='f',
library='l',
literal='e',
output='o',
run='x',
interactive='i',
verbose='v',
['print-ast']='a',
['print-ast-lineinfo']='A',
['print-src']='S',
['meta-bugs']='b',
['sharp-bang']='s',
}
localchunk_options= {
library=1,
file=1,
literal=1
}
localusage=[[
Compile and/or execute metalua programs. Parameters passed to the
compiler should be prefixed with an option flag, hinting what must be
done with them: take tham as file names to compile, as library names
to load, as parameters passed to the running program... When option
flags are absent, metalua tries to adopt a "Do What I Mean" approach:
- if no code (no library, no literal expression and no file) is
specified, the first flag-less parameter is taken as a file name to
load.
- if no code and no parameter is passed, an interactive loop is
started.
- if a target file is specified with --output, the program is not
executed by default, unless a --run flag forces it to. Conversely,
if no --output target is specified, the code is run unless ++run
forbids it.
]]
functionM.cmdline_parser(...)
localargv= {...}
localopts, optind, optarg=
alt_getopt.get_ordered_opts({...}, alt_getopt_options, long_opts)
--pp.printf("argv=%s; opts=%s, ending at %i, with optarg=%s",
-- argv, opts, optind, optarg)
locals2l= { } -- short to long option names conversion table
forlong, shortinpairs(long_opts) dos2l[short]=longend
localcfg= { chunks= { } }
fori, shortinpairs(opts) do
locallong=s2l[short]
ifchunk_options[long] thentable.insert(cfg.chunks, { tag=long, optarg[i] })
elsecfg[long] =optarg[i] ortrueend
end
cfg.params= { select(optind, ...) }
returncfg
end
functionM.main (...)
localcfg=M.cmdline_parser(...)
-------------------------------------------------------------------
-- Print messages if in verbose mode
-------------------------------------------------------------------
localfunctionverb_print (fmt, ...)
ifcfg.verbosethen
returnpp.printf ("[ "..fmt.." ]", ...)
end
end
ifcfg.verbosethen
verb_print("raw options: %s", cfg)
end
-------------------------------------------------------------------
-- If there's no chunk but there are params, interpret the first
-- param as a file name.
ifnotnext(cfg.chunks) andnext(cfg.params) then
localthe_file=table.remove(cfg.params, 1)
verb_print("Param %q considered as a source file", the_file)
cfg.file={ the_file }
end
-------------------------------------------------------------------
-- If nothing to do, run REPL loop
ifnotnext(cfg.chunks) andnotcfg.interactivethen
verb_print"Nothing to compile nor run, force interactive loop"
cfg.interactive=true
end
-------------------------------------------------------------------
-- Run if asked to, or if no --output has been given
-- if cfg.run==false it's been *forced* to false, don't override.
ifnotcfg.runandnotcfg.outputthen
verb_print("No output file specified; I'll run the program")
cfg.run=true
end
localcode= { }
-------------------------------------------------------------------
-- Get ASTs from sources
locallast_file_idx
fori, xinipairs(cfg.chunks) do
localcompiler=mlc.new()
localtag, val=x.tag, x[1]
verb_print("Compiling %s", x)
localst, ast
iftag=='library' then
ast= { tag='Call',
{tag='Id', "require" },
{tag='String', val } }
elseiftag=='literal' thenast=compiler :src_to_ast(val)
elseiftag=='file' then
ast=compiler :srcfile_to_ast(val)
-- Isolate each file in a separate fenv
ast= { tag='Call',
{ tag='Function', { { tag='Dots'} }, ast },
{ tag='Dots' } }
ast.source='@'..val
code.source='@'..val
last_file_idx=i
else
error ("Bad option "..tag)
end
localvalid=true-- TODO: check AST's correctness
ifnotvalidthen
pp.printf ("Cannot compile %s:\n%s", x, astor"no msg")
os.exit (AST_COMPILE_ERROR_NUMBER)
end
ast.origin=x
table.insert(code, ast)
end
-- The last file returns the whole chunk's result
iflast_file_idxthen
-- transform +{ (function(...) -{ast} end)(...) }
-- into +{ return (function(...) -{ast} end)(...) }
localprv_ast=code[last_file_idx]
localnew_ast= { tag='Return', prv_ast }
new_ast.source, new_ast.origin, prv_ast.source, prv_ast.origin=
prv_ast.source, prv_ast.origin, nil, nil
code[last_file_idx] =new_ast
end
-- Further uses of compiler won't involve AST transformations:
-- they can share the same instance.
-- TODO: reuse last instance if possible.
localcompiler=mlc.new()
-------------------------------------------------------------------
-- AST printing
ifcfg['print-ast'] orcfg['print-ast-lineinfo'] then
verb_print"Resulting AST:"
for_, xinipairs(code) do
pp.printf("--- AST From %s: ---", x.source)
ifx.originandx.origin.tag=='File' thenx=x[1][1][2][1] end
localpp_cfg=cfg['print-ast-lineinfo']
and { line_max=1, fix_indent=1, metalua_tag=1 }
or { line_max=1, metalua_tag=1, hide_hash=1 }
pp.print(x, pp_cfg)
end
end
-------------------------------------------------------------------
-- Source printing
ifcfg['print-src'] then
verb_print"Resulting sources:"
for_, xinipairs(code) do
printf("--- Source From %s: ---", table.tostring(x.source, 'nohash'))
ifx.originandx.origin.tag=='File' thenx=x[1][1][2] end
print (compiler :ast2string (x))
end
end
-- TODO: canonize/check AST
localbytecode=compiler :ast_to_bytecode (code)
code=nil
-------------------------------------------------------------------
-- Insert #!... command
ifcfg.sharpbangthen
localshbang=cfg.sharpbang
verb_print ("Adding sharp-bang directive %q", shbang)
ifnotshbang :match'^#!' thenshbang='#!' ..shbangend
ifnotshbang :match'\n$' thenshbang=shbang..'\n' end
bytecode=shbang..bytecode
end
-------------------------------------------------------------------
-- Save to file
ifcfg.outputthen
-- FIXME: handle '-'
verb_print ("Saving to file %q", cfg.output)
localfile, err_msg=io.open(cfg.output, 'wb')
ifnotfilethenerror("can't open output file: "..err_msg) end
file:write(bytecode)
file:close()
ifcfg.sharpbangandos.getenv"OS" ~="Windows_NT" then
pcall(os.execute, 'chmod a+x "'..cfg.output..'"')
end
end
-------------------------------------------------------------------
-- Run compiled code
ifcfg.runthen
verb_print"Running"
localf=compiler :bytecode_to_function (bytecode)
bytecode=nil
-- FIXME: isolate execution in a ring
-- FIXME: check for failures
localfunctionprint_traceback (errmsg)
returnerrmsg..'\n' ..debug.traceback ('',2) ..'\n'
end
localfunctiong() returnf(unpack (cfg.params)) end
localst, msg=xpcall(g, print_traceback)
ifnotstthen
io.stderr:write(msg)
os.exit(RUNTIME_ERROR_NUMBER)
end
end
-------------------------------------------------------------------
-- Run REPL loop
ifcfg.interactivethen
verb_print"Starting REPL loop"
require'metalua.repl' .run()
end
verb_print"Done"
end
returnM.main(...)