]> git.lizzy.rs Git - metalua.git/blob - src/compiler/metalua.mlua
Merge remote branch 'origin/master'
[metalua.git] / src / compiler / metalua.mlua
1 --*-lua-*- Set as a metalua file because it requires some metalua libs
2
3 --require 'verbose_require'
4
5 require 'metalua.compiler'
6 require 'metalua.clopts'
7 require 'metalua.mlc_xcall'
8
9 AST_COMPILE_ERROR_NUMBER        = -1
10 RUNTIME_ERROR_NUMBER            = -3
11 BYTECODE_SYNTHESE_ERROR_NUMBER  = -100
12
13 -{ extension 'match' }
14
15 local chunks  = { }
16 local runargs = { }
17
18 local acc_chunk = |kind| |arg| table.insert (chunks, { tag=kind, arg })
19
20 parser = clopts {
21    -- Chunk loading
22    {  short = 'f', long = 'file', type = 'string', action = acc_chunk 'File',
23       usage = 'load a file to compile and/or run'
24    },
25    {  short = 'l', long = 'library', type = 'string', action = acc_chunk 'Library',
26       usage = 'load a libary from the standard paths'
27    },
28    {  short = 'e', long = 'literal', type = 'string', action = acc_chunk 'Literal',
29       usage = 'load a literal piece of source code'
30    },
31    -- What to do with chunks
32    {  short = 'o', long = 'output', type = 'string',
33       usage = 'set the target name of the next compiled file'
34    },
35    {  short = 'x', long = 'run', type = 'boolean',
36       usage = 'execute the compiled file instead of saving it (unless -o is also used)'
37    },
38    {  short = 'i', long = 'interactive', type = 'boolean',
39       usage = 'run an interactive loop after having run other files'
40    },
41    -- Advanced stuff
42    {  short = 'v', long = 'verbose', type = 'boolean',
43       usage = 'verbose mode'
44    },
45    {  short = 'a', long = 'print-ast',  type = 'boolean',
46       usage = 'print the AST resulting from file compilation'
47    },
48    {  short = 'A', long = 'print-ast-lineinfo',  type = 'boolean',
49       usage = 'print the AST resulting from file compilation, including lineinfo data'
50    },
51    {  short = 'S', long = 'print-src',  type = 'boolean',
52       usage = 'print the AST resulting from file compilation, as re-gerenerated sources'
53    },
54    {  short = 'b', long = 'metabugs', type = 'boolean',
55       usage = 'show syntax errors as compile-time execution errors'
56    },
57    {  short = 's', long = 'sharpbang', type = 'string',
58       usage = 'set a first line to add to compiled file, typically "#!/bin/env mlr"'
59    },
60    {  long  = 'no-runtime', type = 'boolean',
61       usage = "prevent the automatic requirement of metalua runtime"
62    },
63    {  long  = '', short = 'p', type = '*',
64       action= function (newargs) runargs=table.icat(runargs, newargs) end,
65       usage = "pass all remaining arguments to the program"
66    },
67 usage=[[
68
69 Compile and/or execute metalua programs. Parameters passed to the
70 compiler should be prefixed with an option flag, hinting what must be
71 done with them: take tham as file names to compile, as library names
72 to load, as parameters passed to the running program... When option
73 flags are absent, metalua tries to adopt a "Do What I Mean" approach:
74
75 - if no code (no library, no literal expression and no file) is
76   specified, the first flag-less parameter is taken as a file name to
77   load.
78
79 - if no code and no parameter is passed, an interactive loop is
80   started.
81
82 - if a target file is specified with --output, the program is not
83   executed by default, unless a --run flag forces it to. Conversely,
84   if no --output target is specified, the code is run unless ++run
85   forbids it.
86 ]]}
87
88 local function main (...)
89
90    local cfg = parser(...)
91
92    -------------------------------------------------------------------
93    -- Print messages if in verbose mode
94    -------------------------------------------------------------------
95    local function verb_print (fmt, ...)
96       if cfg.verbose then
97          return printf ("[ "..fmt.." ]", ...)
98       end
99    end
100
101    if cfg.verbose then
102       verb_print("raw options: %s", table.tostring(cfg))
103    end
104
105    -------------------------------------------------------------------
106    -- If there's no chunk but there are params, interpret the first
107    -- param as a file name.
108    if #chunks==0 and cfg.params then
109       local the_file = table.remove(cfg.params, 1)
110       verb_print("Param %q considered as a source file", the_file)
111       chunks = { `File{ the_file } }
112    end
113
114    -------------------------------------------------------------------
115    -- If nothing to do, run REPL loop
116    if #chunks==0 and cfg.interactive==nil then
117       verb_print "Nothing to compile nor run, force interactive loop"
118       cfg.interactive=true
119    end
120
121
122    -------------------------------------------------------------------
123    -- Run if asked to, or if no --output has been given
124    -- if cfg.run==false it's been *forced* to false, don't override.
125    if cfg.run==nil and not cfg.output then
126       verb_print("No output file specified; I'll run the program")
127       cfg.run = true
128    end
129
130    local code = { }
131
132    -------------------------------------------------------------------
133    -- Get ASTs from sources
134    mlc.metabugs = cfg.metabugs
135    local last_file
136    for x in values(chunks) do
137       verb_print("Compiling %s", table.tostring(x))
138       local st, ast
139       match x with
140       | `Library{ l } -> st, ast = true, `Call{ `Id 'require', `String{ l } }
141       | `Literal{ e } -> st, ast = mlc_xcall.client_literal (e)
142       | `File{ f } ->
143          st, ast = mlc_xcall.client_file (f)
144           -- Isolate each file in a separate fenv
145          if st then
146             ast = +{ function (...) -{ast} end (...)  }
147             ast.source  = '@'..f -- TODO [EVE]
148             code.source = '@'..f -- TODO [EVE]
149             last_file = ast
150          end
151       end
152       if not st then
153          printf ("Cannot compile %s:\n%s", table.tostring(x), ast or "no msg")
154          os.exit (AST_COMPILE_ERROR_NUMBER)
155       end
156       ast.origin = x
157       table.insert(code, ast)
158    end
159    -- The last file returns the whole chunk's result
160    if last_file then
161       local c = table.shallow_copy(last_file)
162       last_file <- `Return{ source = c.source, c }
163    end
164
165    -------------------------------------------------------------------
166    -- AST printing
167    if cfg['print-ast'] or cfg['print-ast-lineinfo'] then
168       verb_print "Resulting AST:"
169       for x in ivalues(code) do
170          printf("--- AST From %s: ---", table.tostring(x.source, 'nohash'))
171          if x.origin and x.origin.tag=='File' then x=x[1][1][2][1] end
172          if cfg['print-ast-lineinfo'] then table.print(x, 80, "indent1")
173          else table.print(x, 80, 'nohash') end
174       end
175    end
176
177    -------------------------------------------------------------------
178    -- Source printing
179    if cfg['print-src'] then
180       verb_print "Resulting sources:"
181       require 'metalua.ast_to_string'
182       for x in ivalues(code) do
183          printf("--- Source From %s: ---", table.tostring(x.source, 'nohash'))
184          if x.origin and x.origin.tag=='File' then x=x[1][1][2][1] end
185          print (ast_to_string (x))
186       end
187    end
188
189    -- FIXME: canonize/check AST
190
191    -------------------------------------------------------------------
192    -- Insert runtime loader
193    if cfg['no-runtime'] then
194       verb_print "Prevent insertion of command \"require 'metalua.runtime'\""
195    else
196       table.insert(code, 1, +{require'metalua.runtime'})
197    end
198
199    local bytecode = mlc.luacstring_of_ast (code)
200    code = nil
201
202    -------------------------------------------------------------------
203    -- Insert #!... command
204    if cfg.sharpbang then
205       local shbang = cfg.sharpbang
206       verb_print ("Adding sharp-bang directive %q", shbang)
207       if not shbang :strmatch'^#!' then shbang = '#!' .. shbang end
208       if not shbang :strmatch'\n$' then shbang = shbang .. '\n' end
209       bytecode = shbang .. bytecode
210    end
211
212    -------------------------------------------------------------------
213    -- Save to file
214    if cfg.output then
215       -- FIXME: handle '-'
216       verb_print ("Saving to file %q", cfg.output)
217       local file, err_msg = io.open(cfg.output, 'wb')
218       if not file then error("can't open output file: "..err_msg) end
219       file:write(bytecode)
220       file:close()
221       if cfg.sharpbang and os.getenv "OS" ~= "Windows_NT" then
222          pcall(os.execute, 'chmod a+x "'..cfg.output..'"')
223       end
224    end
225
226    -------------------------------------------------------------------
227    -- Run compiled code
228    if cfg.run then
229       verb_print "Running"
230       local f = mlc.function_of_luacstring (bytecode)
231       bytecode = nil
232       -- FIXME: isolate execution in a ring
233       -- FIXME: check for failures
234
235       runargs = table.icat(cfg.params or { }, runargs)
236       local function print_traceback (errmsg)
237          return errmsg .. '\n' .. debug.traceback ('',2) .. '\n'
238       end
239       local st, msg = xpcall(|| f(unpack (runargs)), print_traceback)
240       if not st then
241          io.stderr:write(msg)
242          os.exit(RUNTIME_ERROR_NUMBER)
243       end
244    end
245
246    -------------------------------------------------------------------
247    -- Run REPL loop
248    if cfg.interactive then
249       verb_print "Starting REPL loop"
250       require 'metalua.metaloop'
251       metaloop.run()
252    end
253
254    verb_print "Done"
255
256 end
257
258 main(...)