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 (approximately) 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 require 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 from 0.4 to 0.4.1
117 ===================================
119 - Proper reporting of runtime errors
120 - Interactive REPL loop
121 - Support for 64 bits architectures
122 - Update to Pluto 2.2 and Lua 5.1.3
123 - Build for Visual Studio .NET
125 Notworthy changes from 0.3 to 0.4
126 =================================
128 - A significantly bigger code base, mostly due to more libraries:
129 about 2.5KLoC for libs, 4KLoC for the compiler. However, this remains
130 tiny in today's desktop computers standards. You don't have to know
131 all of the system to do useful stuff with it, and since compiled
132 files are Lua 5.1 compatible, you can keep the "big" system on a
133 development platform, and keep a lightweight runtime for embedded or
134 otherwise underpowered targets.
137 - The compiler/interpreter front-end is completely rewritten. The new
138 frontend program, aptly named 'Metalua', supports proper passing of
139 arguments to programs, and is generally speaking much more user
140 friendly than the mlc from the previous version.
143 - Metalua source libraries are looked for in environmemt variable
144 LUA_MPATH, distinct from LUA_PATH. This way, in an application
145 that's part Lua part Metalua, you keep a natural access to the
148 By convention, Metalua source files should have extension .mlua. By
149 default, bytecode and plain lua files have higher precedence than
150 Metalua sources, which lets you easily precompile your libraries.
153 - Compilation of files are separated in different Lua Rings: this
154 prevents unwanted side-effects when several files are compiled
155 (This can be turned off, but shouldn't be IMO).
158 - Metalua features are accessible programmatically. Library
159 'Metalua.runtime' loads only the libraries necessary to run an
160 already compiled file; 'Metalua.compile' loads everything useful at
163 Transformation functions are available in a library 'mlc' that
164 contains all meaningful transformation functions in the form
165 'mlc.destformat_of_sourceformat()', such as 'mlc.luacfile_of_ast()',
166 'mlc.function_of_luastring()' etc. This library has been
167 significantly completed and rewritten (in Metalua) since v0.3.
170 - Helper libraries have been added. For now they're in the
171 distribution, at some point they should be luarocked in. These
173 - Lua Rings and Pluto, duct-taped together into Springs, an improved
174 Rings that lets states exchange arbitrary data instead of just
175 scalars and strings. Since Pluto requires a (minor) patch to the
176 VM, it can be disabled.
177 - Lua bits for bytecode dumping.
178 - As always, very large amounts of code borrowed from Yueliang.
179 - As a commodity, I've also packaged Lua sources in.
182 - Extensions to Lua standard libraries: many more features in table
183 and the baselib, a couple of string features, and a package system
184 which correctly handles Metalua source files.
187 - Builds on Linux, OSX, Microsoft Visual Studio. Might build on mingw
188 (not tested recently, patches welcome). It's easily ported to all
189 systems with a full support for lua, and if possible dynamic
192 The MS-windows building is based on a dirty .bat script, because
193 that's pretty much the only thing you're sure to find on a win32
194 computer. It uses Microsoft Visual Studio as a compiler (tested with
197 Notice that parts of the compiler itself are now written in Metalua,
198 which means that its building now goes through a bootstrapping
202 - Structural pattern matching improvements:
203 - now also handles string regular expressions: 'someregexp'/pattern
204 will match if the tested term is a string accepted by the regexp,
205 and on success, the list of captures done by the regexp is matched
207 - Matching of multiple values has been optimized
208 - the default behavior when no case match is no to raise an error,
209 it's the most commonly expected case in practice. Trivial to
210 cancel with a final catch-all pattern.
211 - generated calls to type() are now hygienic (it's been the cause of
212 a puzzling bug report; again, hygiene is hard).
215 - AST grammar overhaul:
216 The whole point of being alpha is to fix APIs with a more relaxed
217 attitude towards backward compatibility. I think and hope it's the
218 last AST revision, so here is it:
219 - `Let{...} is now called `Set{...}
220 (Functional programmers would expect 'Let' to introduce an
221 immutable binding, and assignment isn't immutable in Lua)
222 - `Key{ key, value } in table literals is now written `Pair{ key, value }
223 (it contained a key *and* its associated value; besides, 'Pair' is
224 consistent with the name of the for-loop iterator)
225 - `Method{...} is now `Invoke{...}
226 (because it's a method invocation, not a method declaration)
227 - `One{...} is now `Paren{...} and is properly documented
228 (it's the node representing parentheses: it's necessary, since
229 parentheses are sometimes meaningful in Lua)
230 - Operator are simplified: `Op{ 'add', +{2}, +{2} } instead of
231 `Op{ `Add, +{2}, +{2} }. Operator names match the corresponding
232 metatable entries, without the leading double-underscore.
233 - The operators which haven't a metatable counterpart are
234 deprecated: 'ne', 'ge', 'gt'.
237 - Overhaul of the code walking library:
238 - the API has been simplified: the fancy predicates proved more
239 cumbersome to use than a bit of pattern matching in the visitors.
240 - binding identifiers are handled as a distinct AST class
241 - walk.id is scope-aware, handles free and bound variables in a
243 - the currified API proved useless and sometimes cumbersome, it's
247 - Hygiene: I originally planned to release a full-featured hygienic
248 macro system with v0.4, but what exists remains a work in
249 progress. Lua is a Lisp-1, which means unhygienic macros are very
250 dangerous, and hygiene a la Scheme pretty much limits macro writing
251 to a term rewriting subset of the language, which would be crippling
254 Note: inside hygiene, i.e. preventing macro code from capturing
255 variables in user code, is trivial to address through alpha
256 conversion, it's not the issue. The trickier part is outside
257 hygiene, when user's binders capture globals required by the
258 macro-generated code. That's the cause of pretty puzzling and hard
259 to find bugs. And the *really* tricky part, which is still an open
260 problem in Metalua, is when you have several levels of nesting
261 between user code and macro code. For now this case has to be
264 Note 2: Converge has a pretty powerful approach to hygienic macros
265 in a Lisp-1 language; for reasons that would be too long to expose
266 here, I don't think its approach would be the best suited to Metalua.
267 But I might well be proved wrong eventually.
269 Note 3: Redittors must have read that Paul Graham has released Arc,
270 which is also a Lisp-1 with Common Lisp style macros; I expect this
271 to create a bit of buzz, out of which might emerge proper solutions
272 the macro hygiene problem.
275 - No more need to create custom syntax for macros when you don't want
276 to. Extension 'dollar' will let you declare macros in the dollar
277 table, as in +{block: function dollar.MYMACRO(a, b, c) ... end},
278 and use it as $MYMACRO(1, 2, 3) in your code.
280 With this extension, you can write macros without knowing anything
281 about the Metalua parser. Together with quasi-quotes and automatic
282 hygiene, this will probably be the closest we can go to "macros for
283 dummies" without creating an unmaintainable mess generator.
285 Besides, it's consistent with my official position that focusing on
286 superficial syntax issues is counter-productive most of the time :)
289 - Lexers can be switched on the fly. This lets you change the set of
290 keywords temporarily, with the new gg.with_lexer() combinator. You
291 can also handle radically different syntaxes in a single file (think
292 multiple-languages systems such as LuaTeX, or programs+goo as PHP).
295 - Incorporation of the bug fixes reported to the mailing list and on
299 - New samples and extensions, in various states of completion:
301 * lists by comprehension, a la python/haskell. It includes lists
302 chunking, e.g. mylist[1 ... 3, 5 ... 7]
304 * anaphoric macros for 'if' and 'while' statements: with this
305 extension, the condition of the 'if'/'while' is bound to variable
306 'it' in the body; it lets you write things like:
308 > while file:read '*l' do print(it) end.
310 No runtime overhead when 'it' isn't used in the body. An anaphoric
311 variable should also be made accessible for functions, to let
312 easily write anonymous recursive functions.
314 * Try ... catch ... finally extension. Syntax is less than ideal,
315 but the proper way to fix that is to refactor the match extension
316 to improve code reuse. There would be many other great ways to
317 leverage a refactored match extension, e.g. destructuring binds or
318 multiple dispatch methods. To be done in the next version.
320 * with ... do extension: it uses try/finally to make sure that
321 resources will be properly closed. The only constraint on
322 resources is that they have to support a :close() releasing method.
323 For instance, he following code guarantees that file1 and file2
324 will be closed, even if a return or an error occurs in the body.
326 > with file1, file2 = io.open "f1.txt", io.open "f2.txt" do
327 > contents = file1:read'*a' .. file2:read ;*a'
330 * continue statement, logging facilities, ternary "?:" choice
331 operator, assignments as expressions, and a couple of similarly
332 tiny syntax sugar extensions.
335 You might expect in next versions
336 =================================
337 The next versions of Metalua will provide some of the following
338 improvements, in no particular order: better error reporting,
339 especially at runtime (there's a patch I've been too lazy to test
340 yet), support for 64 bits CPUs, better support for macro hygiene, more
341 samples and extensions, an adequate test suite, refactored libraries.
346 I'd like to thank the people who wrote the open source code which
347 makes Metalua run: the Lua team, the authors of Yueliang, Pluto, Lua
348 Rings, Bitlib; and the people whose bug reports, patches and
349 insightful discussions dramatically improved the global design,
350 including John Belmonte, Olivier Gournet, Vyacheslav Egorov, David
351 Manura, Olivier Gournet, Eric Raible, Laurence Tratt...