Community meeting question: metaprogramming in Mojo

Note: this is a question that was submitted for the February 3rd community meeting – we weren’t able to answer this question live so we’re answering it here instead.

What kind of metaprogramming mechanism(s) are planned for Mojo? Specifically, will the metaprogramming be similar to Zig, in that the metaprogramming syntax is the same as the rest of the language?

1 Like

Here are a few metaprogramming features planned for Mojo:

  • Improved error messaging for parameter inference: clear, actionable compiler error messages regarding parameter inference
  • Parameterize traits: ability to write generic traits that can be specialized to provide tighter type guarantees about a conforming type’s associated aliases and methods
  • List and dictionary literals: ability to initialize list and dictionary types with a terse literals syntax

As an addition to what @Caroline has given as the official answer, there’s a few more details that may be helpful.

First, Zig’s comptime is a very, very good reflection API, but Zig has an “if all you have is a hammer” problem. There are a lot of data structures for which the “shorthand” of List[T: CollectionElement] is sufficient, because you don’t need to do very aggressive transforms. It’s also much easier for most developers to use it this way, and combines in a much better way with an algebraic type system. An idea I have seen raised repeatedly is to try to offer both a Rust-style parameter API that integrates more tightly with algebraic traits, and a Zig-like reflection API. Zig’s approach is, in my opinion, overkill and extra stress on the compiler for data structures and generic functions, but it works very, very well for writing struct transforms and things like serialization/deserialization code. There’s also oppertunities to improve on Zig’s approach by letting you use traits to constrain parameters, then generating functions using those types, which removes a lot of those checks that Zig makes you write, like is_memcpy_safe.

The big downside of Zig’s comptime is that it’s really, really hard to write an LSP for, especially one that is responsive. Andrew has decided that the best path forwards for Zig is to make the compiler fast enough to let you run an entire compile without emitting object files as an LSP. While this is a noble goal, as codebases increase in size this becomes harder and harder to sustain, and Mojo has a much more advanced type system than Zig does, which makes the problem even harder. Minimizing the use of comptime will help a lot with this issue.

1 Like