MrDoops

MrDoops

Escaping runtime values in a macro with `^`

I’ve been building a tool that compiles elixir expressions into a “workflow” a directed acyclic graph of steps, conditions, and other nodes. Some examples in a livebook here. The advantage of doing this is it allows for composition of functionality at runtime - with varying levels of potential user defined logic. Should be handy for data pipelines, rule based expert systems or other runtime dependent workflows.

A big part of expert systems is to build rules at runtime, but to do this I need to be able to inject runtime values into a macro (at least as implemented - if there’s a better way to extract atomic conditionals in a function I’m all ears).

So the idea is supporting ^ as an escape value like Ecto and Explorer do, but I barely understand Macros and have been struggling to figure out how to access the runtime values in this situation.

test "escapes runtime values with '^'" do
    some_values = [:potato, :ham, :tomato]

    escaped_rule = Dagger.rule(
      name: "escaped_rule",
      condition: fn val when val in ^some_values -> true end,
      reaction: "food"
    )

    assert match?(%Rule{}, escaped_rule)
    assert Rule.check(escaped_rule, :potato)
end

I want the left hand side of this rule to build a function such as:

fn val when val in [:potato, :ham, :tomato] -> true end

I noticed Jose implemented something similar in Explorer recently: explorer/query.ex at v0.5.5 · elixir-nx/explorer · GitHub but I don’t quite understand how it works yet.

I’ve tried a few variations such as:

check =
  Macro.prewalk(lhs, fn
    {:^, _meta, [{bind, _, _} = expr]} = ast ->
      Macro.Env.has_var?(context, {bind, nil}) |> IO.inspect(label: "has var?") # true
      runtime_value = Macro.Env.vars(context) |> IO.inspect() # [some_values: nil]

      if runtime_value do
        var = Macro.unique_var(bind, __MODULE__)
        quote do: unquote(var)
      else
        ast
      end

    ast ->
      ast
  end)

Can anyone more familiar with macros and/or escaping runtime values help me understand how this works or how you’d approach this problem? Any feedback is appreciated.

Thanks.

First Post!

zachallaun

zachallaun

You can’t access the runtime value at compile time, because, well, it doesn’t have a value yet. :slight_smile: what you can do is strip the ^ and inject the variable into the quoted expression such that the runtime value will be used when things finally execute.

The ^ isn’t special in any way, it’s just a conventional signal to the macro that what follows should be left untouched and not further transformed.

Where Next?

Popular in Questions Top

openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement