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