Elixir macros and parsers: code generation magic

Lately I have been macro-generating code from ASN1 definitions files.

I basically:

  • Read the file
  • Extract the interesting data with…
    • regular expressions or string processing into a map or
    • other simplified form
  • Use elixir macros to pull in this information and generate functions from it

Now so far that is only a rehash of the “Metaprogramming Elixir” book but bear with me.

Even though the ASN.1 is rather regular I do realize that using regular expressions is rather brittle.

So, what if you were instead using a proper parser (any which is accessible from elixir) to more reliably parse your input files and then post-process the abstract syntax trees? You get compile-time code generation magic!
Or so I hope…

Sometimes the things you can do with 10-20 lines of elixir are purely amazing. Even now my code for generating ASN.1 convenience functions is roughly that size for each function - half of it is the extraction of the information, half of it is the macro to generate the function(s). elixir always provides new ways to make my hacking happy. :smile:

3 Likes

Erlang docs on ASN.1:

Unless I misunderstand you.

BTW I worked with legacy ASN.1-dependent apps and I am very interested in any Elixir ASN.1 encoders and decoders. If you can open-source yours, I’ll be a fan!

1 Like

I’ve been using asn1ct for the actual encoding and decoding stuff for a few years now, but there are things it doesn’t provide. Much of that “missing” code I used to write “by hand.” Now I’m just directly pre-processing the .asn files I have and define new functions through macros.

Mostly convenience stuff, really. But it really speaks for elixir that I can write this code not only in elixir, but have it executed at compile time and it is rather short and concise, and the code I generate is immediately available to the rest of my application.

Considered open-sourcing it?

2 Likes