I reopen this thread as I'm facing a similar problem, but now when calling an
API.
Is it possible to write a proc whose behaviour is based on existence or not of
macro injected variables? I've tried to reproduce a sample case below:
import macros
template foo(body: untyped) =
block:
let inFoo {. inject, used .} = true
body
template bar(body: untyped) =
block:
let inBar {. inject, used .} = true
body
proc callApi =
if declaredInScope(inFoo):
echo "Calling API with foo scope"
elif declaredInScope(inBar):
echo "Calling API with bar scope"
else:
echo "You can call API only in foo or bar scopes!"
proc foobar =
foo:
callApi()
bar:
callApi()
foobar()
Run
This code **does not give the expected result!**
What I'm trying to do and that does not work: the `callApi` proc takes no
parameters and depend on the scope it is used to call different API entry
points. Its behaviour is really given in the scope it is used. In order to
determine in which scope it is used, I've tried to inject 2 different variables
`inFoo` and `inBar` and base `callApi` behaviour on the presence or absence of
these variables in the scope.
Having changed the way my DSL works, I'm now able to know in which
scope/context the AST is parsed. But in that case, `callApi` is a Nim function
that can be called by the user and I don't want for these types of functions to
have a complex syntax: the user knows if she is using it in the `for` or `bar`
contexts and that's the reason it doesn't have arguments in my example.
Behind the scene, I have two functions `callApiFromFoo` and `calApiFromBar`
with all the parameters required. I want to be able to find which function to
call...
Is the only way to get the expected result to parse the whole AST tree and when
finding a `callApi` call NimNode, replace it with `callApiFromFoo` (resp.
`callApiFromBar`) when in the `foo` (resp. `bar`) scope?
Or is there another way to solve this problem?