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