How I got started writing macros for Rust with Gluon

Many languages ​​have a special mechanism for code generation – macros. Sometimes they are implemented in a separate rather primitive language based on simple text substitution (preprocessors PL / I and C, m4), but even in this version it is possible to do interesting and useful things. Another popular option is that macros are implemented in the same language as the program in which they are used. This approach originates from Lisp (convenient in that the format of programs and data is the same there), is actively used in Julia, OCaml (camlp4 / 5), Scala, Haskell, Rust, and received the greatest development in Nemerle, where a macro can be run both before and after type checking and inference, and in the latter case, have access to types.

With these macros, all the features of the language are not needed, for example, the high efficiency and safety of Rust will not bring any benefit here and can only complicate development.

In addition, all these are functional or imperative languages, and I wondered what a logical language could give in terms of writing macros. An idea appeared to implement Prolog on Nemerle, but it suddenly turned out that the latter, despite the care of one large and well-known company, died, and the compiler sighed on the available versions of mono. Then I decided (hopefully temporarily) to lower the bar and try just a functional, but relatively easy to embed. Gluon… Macros in Rust have to be formatted in a separate package, which is not very convenient if you want to develop a macro for a single use. So why not implement a macro that just gets the Gluon code as a parameter and executes it?

Now Gluon should return a string that will be parsed as Rust code. Of course, I would like to be able to return an array of tokens, but I could not stretch the required types into Gluon.

I think this approach may be useful for “one-time” macros. V example an array of prime numbers is created – it is convenient to use a macro here, but the task is not worth creating a separate package for it, and you can write the generating code on the spot.

Similar Posts

Leave a Reply