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