3 For installation matters, cf. INSTALL.TXT
7 Metalua is a static metaprogramming system for Lua: a set of tools
8 that let you alter the compilation process in arbitrary, powerful and
9 maintainable ways. For the potential first-time users of such a
10 system, a descripition of these tools, as implemented by metalua,
16 One of the tools is the dynamic parser, which allows a source file to
17 change the grammar recognized by the parser, while it's being
18 parsed. Taken alone, this feature lets you make superficial syntax
19 tweaks on the language. The parser is based on a parser combinator
20 library called 'gg'; you should know the half dozen functions in gg
21 API to do advanced things:
23 - There are a couple of very simple combinators like gg.list,
24 gg.sequence, qq.multisequence, gg.optkeyword etc. that offer a level
25 of expressiveness comparable to Yacc-like parsers. For instance, if
26 mlp.expr parses Lua expressions, gg.list{ mlp.expr } creates a
27 parser which handles lists of Lua expressions.
29 - Since you can create all the combinators you can think of (they're
30 regular, higher-order functions), there also are combinators
31 specialized for typical language tasks. In Yacc-like systems, the
32 language definition quickly becomes unreadable, because all
33 non-native features have to be encoded in clumsy and brittle ways.
34 So if your parser won't natively let you specify infix operator
35 precedence and associativity easily, tough luck for you and your
36 code maintainers. With combinators OTOH, most of such useful
37 functions already exist, and you can write your owns without
38 rewriting the parser itself. For instance, adding an infix operator
41 > mlp.expr.infix:add{ "xor", prec=40, assoc='left', builder=xor_builder }
43 Moreover, combinators tend to produce usable error messages when fed
44 with syntactically incorrect inputs. It matters, because clearly
45 explaining why an invalid input is invalid is almost as important as
46 compiling a valid one, for a use=able compiler.
48 Yacc-like systems might seem simpler to adopt than combinators, as
49 long as they're used on extremely simple problems. However, if you
50 either try to write something non trivial, or to write a simple macro
51 in a robust way, you'll need to use lots of messy tricks and hacks,
52 and spend much more time getting them (approximatively) right than
53 that 1/2 hour required to master the regular features of gg.
59 If you plan to go beyond trivial keyword-for-keyword syntax tweaks,
60 what will limit you is not syntax definition, but the ability to
61 manipulate source code conveniently: without the proper tools and
62 abstractions, even the simplest tasks will turn into a dirty hacks
63 fest, then either into a maintenance nightmare, or simply into
64 abandonware. Providing an empowering framework so that you don't get
65 stuck in such predicaments is metalua's whole purpose. The central
66 concept is that programs prefer to manipulate code as trees, whereas
67 most developers prefer ASCII sources, so both representations must be
68 freely interchangeable. The make-or-break deal is then:
70 - To easily let users see sources as trees, as sources, or as
71 combination thereof, and switch representations seamlessly.
73 - To offer the proper libraries, that won't force you to reinvent a
74 square wheel, will take care of the most common pitfalls, won't
75 force you to resort to brittle hacks.
77 On the former point, Lisps are at a huge advantage, their user syntax
78 already being trees. But languages with casual syntax can also offer
79 interchangeable tree/source views; metalua has some quoting +{ ... }
80 and anti-quoting -{ ... } operators which let you switch between both
81 representations at will: internally it works on trees, but you always
82 have the option to see them as quoted sources. Metalua also supports a
83 slightly improved syntax for syntax trees, to improve their
86 Library-wise, metalua offers a set of syntax tree manipulation tools:
88 - Structural pattern matching, a feature traditionally found in
89 compiler-writing specialized languages (and which has nothing to do
90 with string regular expressions BTW), which lets you express
91 advanced tree analysis operations in a compact, readable and
92 efficient way. If you have to work with advanced data structures
93 and you try it, you'll never go back.
95 - The walker library allows you to perform transformations on big
96 portions of programs. It lets you easily express things like:
97 "replace all return statements which aren't in a nested function by
98 error statements", "rename all local variables and their instances
99 into unique fresh names", "list the variables which escape this
100 chunk's scope", "insert a type-checking instruction into every
101 assignments to variable X", etc. Most of non-trivial macros will
102 requir some of those global code transformations, if you really want
103 them to behave correctly.
105 - Macro hygiene, although not perfect yet in metalua, is required if
106 you want to make macro writing reasonably usable (and contrary to a
107 popular belief, renaming local variables into fresh names only
108 address the easiest part of the hygiene issue; cf. changelog below
111 - The existing extensions are progressively refactored in more modular
112 ways, so that their features can be effectively reused in other
116 Notworthy changes since 0.3
117 ===========================
119 - A significantly bigger code base, mostly due to more libraries:
120 about 2.5KLoC for libs, 4KLoC for the compiler. However, this remains
121 tiny in today's desktop computers standards. You don't have to know
122 all of the system to do useful stuff with it, and since compiled
123 files are Lua 5.1 compatible, you can keep the "big" system on a
124 development platform, and keep a lightweight runtime for embedded or
125 otherwise underpowered targets.
128 - The compiler/interpreter front-end is completely rewritten. The new
129 frontend program, aptly named 'metalua', supports proper passing of
130 arguments to programs, and is generally speaking much more user
131 friendly than the mlc from the previous version.
134 - Metalua source libraries are looked for in environmemt variable
135 LUA_MPATH, distinct from LUA_PATH. This way, in an application
136 that's part Lua part Metalua, you keep a natural access to the
139 By convention, metalua source files should have extension .mlua. By
140 default, bytecode and plain lua files have higher precedence than
141 metalua sources, which lets you easily precompile your libraries.
144 - Compilation of files are separated in different Lua Rings: this
145 prevents unwanted side-effects when several files are compiled
146 (This can be turned off, but shouldn't be IMO).
149 - Metalua features are accessible programmatically. Library
150 'metalua.runtime' loads only the libraries necessary to run an
151 already compiled file; 'metalua.compile' loads everything useful at
154 Transformation functions are available in a library 'mlc' that
155 contains all meaningful transformation functions in the form
156 'mlc.destformat_of_sourceformat()', such as 'mlc.luacfile_of_ast()',
157 'mlc.function_of_luastring()' etc. This library has been
158 significantly completed and rewritten (in metalua) since v0.3.
161 - Helper libraries have been added. For now they're in the
162 distribution, at some point they should be luarocked in. These
164 - Lua Rings and Pluto, duct-taped together into Springs, an improved
165 Rings that lets states exchange arbitrary data instead of just
166 scalars and strings. Since Pluto requires a (minor) patch to the
167 VM, it can be disabled.
168 - Lua bits for bytecode dumping.
169 - As always, very large amounts of code borrowed from Yueliang.
170 - As a commodity, I've also packaged Lua sources in.
173 - Extensions to Lua standard libraries: many more features in table
174 and the baselib, a couple of string features, and a package system
175 which correctly handles metalua source files.
178 - Builds on Linux, OSX, Microsoft Visual Studio. Might build on mingw
179 (not tested recently, patches welcome). It's easily ported to all
180 systems with a full support for lua, and if possible dynamic
183 The MS-windows building is based on a dirty .bat script, because
184 that's pretty much the only thing you're sure to find on a win32
185 computer. It uses Microsoft Visual Studio as a compiler (tested with
188 Notice that parts of the compiler itself are now written in metalua,
189 which means that its building now goes through a bootstrapping
193 - Structural pattern matching improvements:
194 - now also handles string regular expressions: 'someregexp'/pattern
195 will match if the tested term is a string accepted by the regexp,
196 and on success, the list of captures done by the regexp is matched
198 - Matching of multiple values has been optimized
199 - the default behavior when no case match is no to raise an error,
200 it's the most commonly expected case in practice. Trivial to
201 cancel with a final catch-all pattern.
202 - generated calls to type() are now hygienic (it's been the cause of
203 a puzzling bug report; again, hygiene is hard).
206 - AST grammar overhaul:
207 The whole point of being alpha is to fix APIs with a more relaxed
208 attitude towards backward compatibility. I think and hope it's the
209 last AST revision, so here is it:
210 - `Let{...} is now called `Set{...}
211 (Functional programmers would expect 'Let' to introduce an
212 immutable binding, and assignment isn't immutable in Lua)
213 - `Key{ key, value } in table literals is now written `Pair{ key, value }
214 (it contained a key *and* its associated value; besides, 'Pair' is
215 consistent with the name of the for-loop iterator)
216 - `Method{...} is now `Invoke{...}
217 (because it's a method invocation, not a method declaration)
218 - `One{...} is now `Paren{...} and is properly documented
219 (it's the node representing parentheses: it's necessary, since
220 parentheses are sometimes meaningful in Lua)
221 - Operator are simplified: `Op{ 'add', +{2}, +{2} } instead of
222 `Op{ `Add, +{2}, +{2} }. Operator names match the corresponding
223 metatable entries, without the leading double-underscore.
224 - The operators which haven't a metatable counterpart are
225 deprecated: 'ne', 'ge', 'gt'.
228 - Overhaul of the code walking library:
229 - the API has been simplified: the fancy predicates proved more
230 cumbersome to use than a bit of pattern matching in the visitors.
231 - binding identifiers are handled as a distinct AST class
232 - walk.id is scope-aware, handles free and bound variables in a
234 - the currified API proved useless and sometimes cumbersome, it's
238 - Hygiene: I originally planned to release a full-featured hygienic
239 macro system with v0.4, but what exists remains a work in
240 progress. Lua is a Lisp-1, which means unhygienic macros are very
241 dangerous, and hygiene a la Scheme pretty much limits macro writing
242 to a term rewriting subset of the language, which would be crippling
245 Note: inside hygiene, i.e. preventing macro code from capturing
246 variables in user code, is trivial to address through alpha
247 conversion, it's not the issue. The trickier part is outside
248 hygiene, when user's binders capture globals required by the
249 macro-generated code. That's the cause of pretty puzzling and hard
250 to find bugs. And the *really* tricky part, which is still an open
251 problem in metalua, is when you have several levels of nesting
252 between user code and macro code. For now this case has to be
255 Note 2: Converge has a pretty powerful approach to hygienic macros
256 in a Lisp-1 language; for reasons that would be too long to expose
257 here, I don't think its approch would be the best suited to metalua.
258 But I might well be proved wrong eventually.
260 Note 3: Redittors must have read that Paul Graham has released Arc,
261 which is also a Lisp-1 with Common Lisp style macros; I expect this
262 to create a bit of buzz, out of which might emerge proper solutions
263 the macro hygiene problem.
266 - No more need to create custom syntax for macros when you don't want
267 to. Extension 'dollar' will let you declare macros in the dollar
268 table, as in +{block: function dollar.MYMACRO(a, b, c) ... end},
269 and use it as $MYMACRO(1, 2, 3) in your code.
271 With this extension, you can write macros without knowing anything
272 about the metalua parser. Together with quasi-quotes and automatic
273 hygiene, this will probably be the closest we can go to "macros for
274 dummies" without creating an unmaintainable mess generator.
276 Besides, it's consistent with my official position that focusing on
277 superficial syntax issues is counter-productive most of the time :)
280 - Lexers can be switched on the fly. This lets you change the set of
281 keywords temporarily, with the new gg.with_lexer() combinator. You
282 can also handle radically different syntaxes in a single file (think
283 multiple-languages systems such as LuaTeX, or programs+goo as PHP).
286 - Incorporation of the bug fixes reported to the mailing list and on
290 - New samples and extensions, in various states of completion:
292 * lists by comprehension, a la python/haskell. It includes lists
293 chunking, e.g. mylist[1 ... 3, 5 ... 7]
295 * anaphoric macros for 'if' and 'while' statements: with this
296 extension, the condition of the 'if'/'while' is bound to variable
297 'it' in the body; it lets you write things like:
299 > while file:read '*l' do print(it) end.
301 No runtime overhead when 'it' isn't used in the body. An anaphoric
302 variable should also be made accessible for functions, to let
303 easily write anonymous recursive functions.
305 * Try ... catch ... finally extension. Syntax is less than ideal,
306 but the proper way to fix that is to refactor the match extension
307 to improve code reuse. There would be many other greate ways to
308 leverage a refactored match extension, e.g. destructuring binds or
309 multiple dispatch methods. To be done in the next version.
311 * with ... do extension: it uses try/finally to make sure that
312 resources will be properly closed. The only constraint on
313 resources is that they have to support a :close() releasing method.
314 For instance, he following code guarantees that file1 and file2
315 will be closed, even if a return or an error occurs in the body.
317 > with file1, file2 = io.open "f1.txt", io.open "f2.txt" do
318 > contents = file1:read'*a' .. file2:read ;*a'
321 * continue statement, logging facilities, ternary "?:" choice
322 operator, assignments as expressions, and a couple of similarly
323 tiny syntax sugar extensions.
326 You might expect in next versions
327 =================================
328 The next versions of metalua will provide some of the following
329 improvements, in no particular order: better error reporting,
330 especially at runtime (there's a patch I've been too lazy to test
331 yet), support for 64 bits CPUs, better support for macro hygiene, more
332 samples and extensions, an adequate test suite, refactored libraries.
337 I'd like to thank the people who wrote the open source code which
338 makes metalua run: the Lua team, the authors of Yueliang, Pluto, Lua
339 Rings, Bitlib; and the people whose bug reports, patches and
340 insightful discussions dramatically improved the global design,
341 including John Belmonte, Viacheslav Egorov, David Manura, Olivier
342 Gournet, Eric Raible, Laurence Tratt...