TL;DR: A macro to generate a Map API for a GenServer’s state or a Module with Agent-held state

The Trouble with State

Modules often need to keep state and share it but, as getting started says

Elixir is an immutable language where nothing is shared by default.

In Elixir there are two basic ways of sharing state: processes and ETS (which I wont consider further).

Arguably the most common way of implementing process-held state is GenServer. But for a module that does little more than hold state, GenServer can be overkill. As an alternative, an Agent provides a simpler, alternative way for a module to hold and manage its state.

But neither GenServer nor Agent provide any built-in API calls to manage the content of the state, not surprisingly as the state’s value can be anything.

More often than not though, I want the state to be a map, and sometimes with keys that are (sub)maps. So I usually want to make Map-like API calls — get, put, take, update etc — both for the state itself and any submaps.

Previously, I’ve written the wrappers manually. This is not hard but is just a bit tedious to do given the possible combinations of state wrappers, submap wrappers, arities, etc (lots and lots of cut’n’paste’edit!). So recently I’ve bitten the bullet and written a first cut of a macro to do the heavy lifting.

The interface I wanted for my applications’ modules was to simply use the module (that I’ve called Amlapio) that makes the API wrapper functions.

As many will already know use calls the __using__ macro in the module being used, and the code generated by __using__ is injected into the caller module.

Here’s an example (from the repo’s tests) of a module using an Agent to hold its state.

The wanted submap wrappers are defined by the agent: [:buttons, :menus, :checkboxes] option.

To generate state wrappers the submaps have been set to nil: agent: nil

Generating wrappers for only a subset of Map functions can be given using the funs options e.g, for the state wrappers, funs: [:get, :put, :pop]

Finally, a namer function has been given to name the state wrappers. It is passed two arguments: the map name (e.g. buttons for a submap, but nil for a state wrapper) and the Map function name (e.g. pop).

These tests from the repo show how the submap wrappers would be used, pretty much how you’d expect. (The repo has tests for the state wrappers as well.)

Creating wrappers for a GenServer’s state is very similar. However, each wrapper has two “parts”: an api function and a handle_call function.

The api wrapper for e.g. buttons_get/3 looks like this:

… while the matching handle_call looks like:

Here’s example of generating wrappers for a GenServer.

Remember: all handle_call functions must be kept together in the source else the compiler will complain.

There are tests got the GenServer example in the repo but they look almost identical to the Agent example.

If you just want to give it a whirl, that pretty much it. Its available on Hex and just needs to be added to the dependencies in mix.exs in the usual way.

But if you are interested in a high-level explanation of how I implemented Amlapio, read on.

Code on Github

You might want to have a look at the code if you are following along.

Wrapper Patterns

Map has three types of functions: accessors (e.g. get), mutators (e.g. put), and the (four) ‘combo’ functions that are both accessors and mutators (e.g. pop) (called hereafter poppers).

Wrapper Pattern for a Mutator

Here’s an example of put for the buttons submap of an agent showing the steps in the wrapper, illustrating that all mutators have a common pattern.

BTW I will be using this wrapper as my example when I show code, etc below unless I say otherwise.

The mutator pattern for both an agent and GenServer wrapper has a maximum of six logical steps:

1. get the state (line 5)

2. (optional) get the submap of the state (line 9)

This step is only needed when creating wrappers for a submap.

3. run the Map API call (line 11)

In this case its Map.put/3.

4. (optional) put the (new) submap into the state (line 14)

Again, this step is only needed for submap wrappers.

5. update the state (line 17)

6. return the result (line 20)

Wrapper Pattern for an Accessor

The steps for an accessor (e.g. buttons_get) are even simpler:

1. get the state

2. (optional) get the submap

3. run the Map API call

4. return the result

Wrapper Pattern for a Popper

The pattern for a popper (e.g. buttons_pop) is very similar to a mutator, the main difference being the wrapper’s result is a tuple e.g.

where the state of the agent no longer has the button_name key in the buttons submap.

Wrapper Generation

The wrapper patterns are implicitly recipes for the generation of each wrapper’s code: each step gives rise to its own fragment of code.

Sometimes the code fragment will be nil e.g state wrappers have no submaps so steps 2 & 4 (of the mutator) will be nil.

Wrapper Generation Spec (map_wrap)

Amlapio’s __using__ macro doesn’t do all that much, it just hands off its arguments to the Amlapio.process_opts/1 function.

process_opts creates a list of maps (called a map_wrap in the code), one for every wrapper name & arity combo e.g.

btw map_name is always nil for a state wrapper

The values of the map_wrap’s keys enable normal pattern matching to be used to determine the wrapper being generated and acts accordingly.

(During generation, the code fragment is usually stored under the :fun_ast key.)

Wrapper Generation DSL

To define a wrapper’s recipe in a programmable way, I’ve invented a very simple DSL (implemented by Amlapio.DSL).

The dsl essentially defines a pipeline of transforms that takes the initial map_wrap and incrementally builds the full code for an specific wrapper.

Here is an example of the “top level” make_fun dsl:

The make_body is itself another dsl:

Each individual dsl is a Keyword where the values may themselves be another dsl, an atom (called a snippet - see make) or a tuple (explained in custom logic).

The keys in the dsl are the verbs and there are three of them: push, pipe and make.

Wrapper Generation DSL verb: make

make normally creates a quoted fragment of code.

The value of the make verb (the snippet e.g. state_get) is the 1st argument in the call to Amlapio.Snippets.map_wrap_make_snippet/2. The 2nd argument is the map_wrap. For example:

The ast returned is stored under the :fun_ast key.

Wrapper Generation DSL verb: push

After running the push’s dsl, the returned map_wrap is pushed onto the tail of list held under the :push_wraps key in the map_wrap

The push verb provides a way of caching a list of map_wraps, each of which usually has one statement of the wrapper stored under its :fun_ast key.

Wrapper Generation DSL verb: pipe

Similar to push, pipe runs its dsl, but then takes all of the fun_asts from the map_wraps returned from running each step in the dsl, and pipes them together.

For example, this “clause” of the dsl above:

generates this code fragment:

Wrapper Generation DSL: custom logic

In the dsl clause above the value of the make was a tuple.

The submap_put is the snippet as usual.

But the first element is a function that’s called with the map_wrap before the snippet is made.

More generally, the make value can be a 3tuple:

where funs_ante and funs_post can be either nil, a function or list of functions.

The tuple elements are used to create a list of functions that take one argument – map_wrap – which are then used with Enum.reduce/3:

(btw I currently use only the 2tuple form)

Just to complete the explanation of this example, AmlUtils.map_wrap_ast_index_set_1/1 sets the index value to be used in the call to Macro.pipe/3 to 1. This makes the code fragment produced by the prior pipe

… the 2nd argument of the submap_put

Final Words

The use of regular pattern matching together with a very simple DSL made it quite straightforward to generate the code for the various wrapper patterns.

The technique is also quite extensible: by adding e.g. more calls to Amlapio.Snippets.map_wrap_make_snippet/2, or maybe even new dsl verbs, one could address other code building needs.

Again though, it highlights that manipulating asts, mostly using the functions you use day in and day out, is really no more difficult than any other challenge in Elixir.

+1 macros