r/ProgrammingLanguages • u/Mr-Tau • Aug 03 '26
Discussion Between more constrained, local metaprogramming approaches and full-blown DSL interpreters, where's the practical use case for LISP-style metaprogramming?
Of the various contemporary metaprogramming approaches, I'm mostly very happy with systems that let you operate on static data and types. In this category I would count, for example, C++'s template metaprogramming--a declarative sub-language that somewhat wonkily and arduously allows you to operate on types and constants--as well as the C++26 metaprogramming features, which are turning out somewhat Zig-like--you get to run regular code in a slightly constrained environment at compile time, where it can read constants as well as special data structures describing types, and generate new constants or types to be injected into a well-defined place in the code.
Now many LISPs (AFAICT, similarly Jai and, with a stricter separation of stages, Rust's procedural macros) tout as a feature the ability to inspect and rewrite the entirety of the AST, notably including function bodies. This is obviously strictly more powerful than the the first category, but where would you practically use that extra power? Specifically, it seems to me like you would either
a) Try to preserve the semantics of the input code--which, for procedural languages at least, is actually pretty difficult. The only transformations you could make confidently are so localized that you don't really gain anything over the more constrained metaprogramming approaches; anything more advanced would require the full analysis passes of the actual compiler to have any chance at soundness, and at that point you're really trying to write a compiler plugin instead. Nothing wrong with that, I'd love more easily extensible compilers, but I wouldn't call that a language feature. Or am I missing a point between those two extremes?
b) Attribute different semantics to the code. I think the history of LISP has already somewhat shown how proliferation of DSLs harms maintainability and shareability of code, but even in the cases where a DSL is genuinely useful, what benefits do you really gain from implementing it through metaprogramming? You can't expect any IDE features, LSPs, smart syntax highlighters, debuggers, or other tooling for the base language to automatically work for your DSL. So you just get to use the parser? Come on, an S-expr parser is less than a hundered LOC.
14
u/initial-algebra Aug 03 '26
The only essential difference between a macro and a normal function, especially in a higher-order functional language, is staged computation/partial evaluation/compile-time evaluation, or whatever you want to call it. A macro does not necessarily express a code-to-code transformation, but code generation based on any kind of input.
6
u/kwan_e tonal-lang Aug 03 '26
By virtue of being so powerful, I don't think there is an identifiable "use case". It can literally do anything and the onus is on the programmers to limit themselves, otherwise it comes out with the problems like your point b.
With regards to point b, I think the issue there actually is laziness. The LISP stuff is powerful, they probably should have used that increase in power to also create the tools for their mini-language. On the flip side, because the mini-languages would be evolving quite fast, it would be hard to also write the standardized tools that could keep up with the progress. They'd have to write more metaprogramming to keep up with it, which won't have the tooling support they need to be maintainable either.
Long story short, mini-languages would need to be standardizable before anyone would want to work on the tooling for them. And not purely just the grammar, but also the community idioms. eg, only recently is C++ metaprogramming support usable in IDEs because now it is more accessible and the idioms are more established now.
11
u/digikar Aug 03 '26
What are your thoughts on DSLs like loop or, even better, the finding clauses of iterate?
Also, coalton is an entire ML-typed language that is essentially a DSL in Common Lisp!
But we don't even need them! Not most of them anyways! Or not in the ways one'd think. Common Lisp development usually takes place via SLIME/Swank (or Sly). This is essentially a communication with a running lisp compiler; which means you can evaluate arbitrary code. In principle, it can be extended in arbitrary ways. In practice, developers and communities try to make some opinionated choices, but you can always override them. The development is centered around symbols, which don't change [much] with the introduction of a DSL. Syntax highlighting is not used much since the syntax for lisps is quite minimal; but emacs is trivially extensible. The main aspect of syntax are parentheses (which the editor handles half-way). And the indentation (which, again, the editor handles once it has handled the parentheses).
So, what one does not have to write while writing a DSL:
What you need to define:
I agree, this can be trivial, or very complex. But it is still wayyy less complex than writing a full compiler that works across multiple platforms!
5
u/EggplantExtra4946 Aug 04 '26 edited Aug 04 '26
This is non sense. What languages like LISP allows you to do is generating ASTs, often from existing ASTs but it could be from pure data, or both.
Rewriting an AST is possible but this isn't going to be of much use for metaprogramming per se, it would be rather for implementing additional semantic checks, doing optimizations or inserting instrumentation.
Also, any kind of metaprogramming generation of type definitions is going to be severely limited if you don't/can't generate the functions that use that type as well.
As opposed to not implementing it at all? How many DSLs project do you know of where someeone wrote a parser, compiler+VM or transpiler or compiler to LLVM IR? Very very few, even fewer where the implementation is practical to be integrated with an existing language. And how many of those actually have a debugger?
3
u/_A_Nun_Mouse_ Aug 04 '26 edited Aug 04 '26
I use macros to greatly simplify writing queries in my ECS based game.
Before:
After:
4
u/arthurno1 Aug 04 '26
What qualification do you have for this opinion?
Anyhow, when it comes to DSLs, we can look at "DSLs" at different levels. Consider for example a langauge like C or C++: what you normaly see as a "syntax" of the language, could be of course broken into smaller pieces, where each part of "syntax" is a "small DSL" for implementing an abstraction or idiom. For example, if-else is an asbtraction or a "small DSL" for conditional jumps or branching, which abstract the low-level hardware compare and jump instructions.
If we go back to Lisp "metaprogramming", Lisp has since very beginning, separated evaluator and parser from each other. The evaluator understands only one "form":
I think it is possible to mathematically prove that all other syntactic forms could be reduced to one by "meta" operations on that internal form. I think it is somewhat analogous to DFAs and NDFAs. Now why I take up that one: well, since the internal form in which source code is parsed, the list, is exposed to the user programmer, or to the runtime, it means we can actually do those transformations ourselves. In other words we can do that metaprogramming ourselves.
The benefit of separating the evaluator syntax in this way from the parser, is that you introduce new syntactic forms, without having to rewrite the entire compiler. Since we are reducing all syntactic forms to one(!) that evaluator understands, it means we can introduce new syntactic forms as we need them via metaprogrammign facilities, in Lisps most notably macros. Compare that to "conventional" programming languages, which do not separate evaluator from syntactic forms. Each syntactic forms, or "small DSL" like if-else or while, or for loop etc, requires the evaluator to understand the synctactic form of each one. Whenever we add a new construct, we have to update both the parser and the evaluator. This is typically done via some AST and specialized APIs like for Python AST or llvm AST for example. In Lisp we don't need those, due to that fundamental sepration between syntax. The list that parsed symbolic expression is represented with, serves itself as its AST (or rather CST but that is out of scope here). I suggest reading about Lisp Trees (l-trees) vs boxed representation for symbolic expressions in Anatomy of Lisp which nowdays is free to read online. I suggest that book to anyone who is interested in writing interpreters for any language.
To make that possible, Lisp introduced symbolic expressions, so the source code can be expressed as linked list of nodes, and quoting which turns off the evaluator. By "quoting" we are getting the list of parsed source code in form of linked list nodes.
Admittedly, working with linked list nodes more low-level, compared to working with specilized AST nodes, but nothing prevents from introducing higher-level functions for working with the code, and it is not uncommon to see functions that work on lambda-lists (argument lists), code-walkers, etc.
To round this up, I am not a good writer, so I don't know if it is self-apparent or not, but metaprogramming facility in Lisp is not something inve nted to enable customized DSLs, but a fundamental property of Lisp, that make Lisp(s) more or less programmable languages. By separating parsing from evaluation, and making the iternal form of parsed code (list) available at compile-time or run-time, metaprogramming follows naturally from that distinction.
Whether you should use it for DSLs or not is of course debatable, just as writing dialects of C in C preprocessor is debatable. However, the metaprogramming is much more fundamental than using it for DSLs. It enables metacircularity in Lisps and the most importantly, it enables Lisp to be grown by user programmers rather than waiting for the compiler writers to extend it (at least to a degree). I think Guy Steele has put it wonderfully in his OOPSLA talk about growing a language. I think it should definitely be seen by any aspiring language designer and compiler writer.
PS: I am not an expert in this, so if you find something incorrect, I am happy to hear it!
2
u/Veqq Aug 04 '26
https://codeberg.org/veqq/declarative-dsls uses a single macro (
select) to build a common query language, a common idiom, for many data structures (strings, arrays, hashmaps, dataframes) is liberating, permitting you to e.g. solve sudoku, make mandelbrot sets or calculate primes directly:Or e.g.
The tests file has many such things (like the sudoku solver) and even datalog and minikanren implemented on top of this!
2
u/Hakawatha Aug 04 '26
I find macros are best when they act to simplify more granular interfaces.
Good examples of macros here include Julia's
Threads.@threadsmacro, and the@kernelmacro inKernelAbstractions.jl. The former decorates a for-loop to multithread it (in a similar way to e.g. OpenMP). The latter intercepts the LLVM IR of a function and recompiles it for GPU targets - allowing you to write GPU kernels natively in Julia.Both of these rely on some underlying machinery (the threading system, or GPU compilation and dispatch) - the macros serve to provide a simple interface into this machinery.
In my work, I am reprocessing large (>700 GB) quantities of lunar multispectral data. I have lots of machinery in place to do the low-level work. I can then decorate a function with
@defparamto write spectral parameters which are then lifted into anObservationmonad, so that pipelines can be written. This allows for a degree of flexibility and extensibility that most other multispectral tool-kits simply do not have.The end users (geologists) don't have to care about how this works; they write one-liners, and the code is fast. They don't need to worry about cache-locality or false sharing or I/O to underlying HDF5 files.
Like all powerful abstractions, there is a matter of good taste. Overuse of macros, leading to DSLs everywhere, yields write-only code. Well-placed macros that abstract over complicated machinery, however, are gold dust.
2
u/Blind_nabler Aug 03 '26
These questions aren't really useful in the broad case. What benefit is feature X if I only use feature Y? Probably not a ton for you if you aren't using X!
The main benefit of having a rich meta-programming system is that it enables users to implement features that otherwise would require modifying the compiler to implement, or require the use of some rube goldberg code generation nonsense. This kinda thing isn't important to you until it is.
For example in a procedural language it can be rather gnarly to convert normal single threaded code to work in an async setting. Since it requires setting up trampolines or rewriting everything into CPS flavored versions etc etc. But if I have the ability to use rich macros, I can just invoke a macro over my normal function and now it can work with whatever async backend I want, utilizing whatever custom semantic checking is required because I have (most of / all) the language available to us.
And IDE tooling works totally fine if the meta-programming system is well designed. Nim does a pretty good job of this. The most extremely example I have experience with is smalltalk, which has the best IDE support of any language IMO but obviously it's not the same kind of language as you are describing.
Now do I reach for it every project? No. But I definitely find myself missing it in languages that don't trust users with that kind of thing.
1
u/aaaaargZombies Aug 03 '26
Might be worth looking at elixir which uses macros a lot and you can parse the code as a data structure if you want. I think many things that would normally be language constructs are actually implemented as macros, like
if/else.1
u/vanderZwan Aug 04 '26
I'm not a computer scientist, but years of programming and reading up on these things has given me the impression that this gets at the core trade-off you're thinking of: "strictly more powerful" here seems to be talking about expressive power in the context of a real formal basis like the Chomsky hierarchies. However, what we often want seems to be the language that gives you the most "ergonomic" expressive power while using as little formal expressive power as possible. Because the latter usually means the computer can do more work for you automatically without running into pitfalls.
(this also makes "expressive power" such an easy way to have discussions where people don't realize they're not talking about the same thing, even the wiki page acknowledges the ambiguities in how the term is used
Well, then I guess that situations where you only can afford a few hundred LOC for whatever reason, LISP-style macros might be a good choice.
0
u/iEliteTester Aug 04 '26
Admittedly I haven't search THAT much but I have yet to see a single example of practical metaprogramming use in lisp. Best I could find was a guy trying to make a case for it by showing "hey look I can write tnirp and the macro will actually execute print!"