2
votes

Hello I'd like to build a library that replaces certain function calls with other function calls.

module A do
  def wrapper
    B.foo
  end
end

In the compiled program A.wrapper will actually call B.baz. I already stumbled upon the @before_compile callback but don't seem to get how I can change the AST of the calling module.

So all I got is this

module A do
  use Modifier
  @before_compile Modifier

  def wrapper
    B.foo
  end
end

defmodule Modifier do
  defmacro __before_compile__(env) do
    # Now what?
  end
end
2

2 Answers

0
votes

I think your looking for defdelegate/2.

You could also just create a macro:

defmodule Mofifier do
  defmacro __using__(_) do
    quote do
      import unquote(__MODULE__)
    end
  end

  defmacro wrapper do
    quote do
      B.foo
    end
  end
end

defmodule A do
  use Modifier

  def something, do: wrapper()
end
0
votes

Verify if the @on_definition attribute serves your purposes here. Most probably it will.