Modifying Julia code using macros to substitute variables

137 views Asked by At

I'm trying to create a Julia macro to substitute specific variables in a Julia program with new ones. I have a working example, but I'm facing a challenge when I need to reassign variables within nested functions.

Here's a simplified version of my Input code:

module m1

using sub_vars

function f1()
  @declare_newvar v1 v_1 1
  v2 = 2

  function f2()
    v3 = v1 + v2
    @declare_newvar v1 v^1 4
    v4 = v1 + v3
    v1 = v1 + v4
  end

  f2()
end

f1()
end

where,

module sub_vars

?

macro declare_newvar(orig_var :: Symbol, new_var :: Symbol, val :: Any)
  ?
end 

end 

The @declare_newvar macro should replace v1 with v_1 and v^1 in the code as specified.

I would like to get the desired output:

module m1

using sub_vars

function f1()
  v_1 = 1
  v2 = 2

  function f2()
    v3 = v_1 + v2
    v^1 = 4
    v4 = v^1 + v3
    v^1 = v^1 + v4
  end

  f2()
end

f1()
end

This is a MWE, the variables should be substituted correctly with respect to scoping of the blocks.

Approaches to tackle this issue:

  1. Transform the code into an Expr variable and employ a relevant package to identify variable scopes. Subsequently, navigate through the Abstract Syntax Tree (AST) and modify the Expr variable accordingly.

  2. Create and maintain a Symbol Table within the sub_vars module. Utilize macros to capture essential information during passes and employ this data to facilitate variable substitution.

Are there any alternative methods to address this problem?

0

There are 0 answers