[nim-dev] Re: Code generation from AST with annotations in Nim like in C

  • From: komerdoor <komerdoor@xxxxxxxxx>
  • To: nim-dev@xxxxxxxxxxxxx
  • Date: Sun, 4 Dec 2016 03:02:31 +0000

I managed to create a macro that creates a wrapper for functions that have the 
"scriptExport" attribute. It was easier than I expected.

```nim
import macros

proc expandFormalParamsForCall(formalParamsNode: NimNode): seq[NimNode] 
{.compileTime.} =
  result = @[]
  for i in 1 ..< formalParamsNode.len:
    if formalParamsNode[i].kind == nnkIdentDefs:
      for j in 0 ..< formalParamsNode[i].len - 2:
        result.add(formalParamsNode[i][j])

proc expandFormalParamsForProc(formalParamsNode: NimNode): seq[NimNode] 
{.compileTime.} =
  result = @[]
  for i in 0 ..< formalParamsNode.len:
    if formalParamsNode[i].kind == nnkIdent:
      result.add(formalParamsNode[i])
    if formalParamsNode[i].kind == nnkIdentDefs:
      for j in 0 ..< formalParamsNode[i].len - 2:
        result.add(newNimNode(nnkIdentDefs).add(formalParamsNode[i][j], 
formalParamsNode[i][^2], newEmptyNode()))

macro scriptExport(definition: untyped): typed =
  case definition.kind
  of nnkProcDef:
    var scriptDefinition = newProc(newIdentNode($definition.name & "_script"), 
expandFormalParamsForProc(definition.pa
      newCall(!"echo", newStrLitNode($definition.name & "_script called.")),
      newCall(definition.name, expandFormalParamsForCall(definition.params))
    ))
    return newStmtList(definition, scriptDefinition)
  else:
    error("Only works with procedures for now")

proc sum(x, y: int): int {.noSideEffect,scriptExport.} =
  x + y

echo(sum(1, 2))
echo(sum_script(1, 2))
```

Still have to do the same for other types etc. as well. From this I can write 
code that will create bindings etc.

Other related posts: