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

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
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
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
Phillipp
Hey, I have a NanoPi-M3 and try to install Elixir on their Ubuntu image. I followed the Raspberry Pi installation instructions from the ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
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
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
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement