ashton314

ashton314

How to write a macro that replaces one identifier with another, but it needs to respect lexical scope?

I would like to write a macro that replaces one identifier with another, but it needs to respect lexical scope.

Here is an example illustrating what I mean:

defmodule Foo do
  defmacro rename({i1, _, c1}, {_i2, _, _} = i2c, do: body) do
    Macro.postwalk(body, fn x ->
      case x do
        {^i1, _, ^c1} -> i2c
        w -> w
      end
    end)
  end

  def foo() do
    quote do
      rename x, y do
        x = 42
        z = fn x -> x + 2 end
        x + 1
      end
    end
    |> Macro.expand_once(__ENV__)
    |> Macro.to_string()
    |> IO.puts()
  end
end

Foo.foo()

When I run this code it prints the following: (meaning: the reanme do ... end block expands to the following)

y = 42
z = fn y -> y + 2 end
y + 1

The problem here is that the x variable introduced on line 3 by the fn form gets rewritten, even though that x refers to a different variable than the x on line 1. What I want is a definition for rename that, when run on the same code, prints something like this:

y = 42
z = fn x -> x + 2 end
y + 1

Context

Above is just a toy problem meant to illustrate what I would like to try to do. I’m working on a bigger and much more complicated macro that might need to rewrite variables in arbitrary expressions, but I want to make sure that my macro respects lexical scoping.

Racket can do something like this with make-rename-transformer, which creates an identifier macro that expands to another identifier. When you run this code:

#lang racket

(require syntax/parse syntax/parse/define
         (for-syntax racket/match))

(define-syntax (replace stx)
  (syntax-parse stx
    [(_ (i1:id i2:id) body:expr)
     #'(let-syntax ([i1 (make-rename-transformer (syntax i2))]) body)]))

(expand-once #'(let ([x 1] [y 2]) (replace (x y) (+ x (let ([x 1]) x)))))

you get this output:

#<syntax:ident_test.rkt:11:10
  (let-values (((x) (quote 1)) ((y) (quote 2)))
    (let-values ()
      (let-values () (#%app + y
                            (let-values (((x) (quote 1)))
                              x)))))>

if it’s not immediately obvious, the variable x has been swapped out for y except inside of the inner let block, which introduces a new variable x.

I would like to see if I can do the same in Elixir. I know that this is a little unusual; I’m a researcher, so I do unusual stuff by definition. :slight_smile:

Thanks in advance for any help.

Marked As Solved

josevalim

josevalim

Creator of Elixir

We don’t have built in affordances in the language for this. You would need to traverse the constructs yourself, expanding nodes, and tracking when variables are introduced.

Perhaps some of the tooling being used by folks for refactoring, such as sourceror and styler, have higher level conveniences for that, but they are more on the static analysis / source code rewriting side of things.

Also Liked

ashton314

ashton314

Thank you very much for the answer José!

Where Next?

Popular in Questions Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
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
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
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
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

We're in Beta

About us Mission Statement