And second version, with run_hook as pragma
    
    
    import tables, macros
    
    var hooks {.compileTime.}: Table[string, NimNode]
    
    macro registerHook(name: untyped{ident}, body: untyped): untyped =
      result = newStmtList()
      result.add newProc(
        name = name,
        body = body,
        # need a dirty template to capture x
        procType = nnkTemplateDef,
        pragmas = nnkPragma.newTree(ident"dirty")
        )
      
      # We could use a hashing scheme for idents instead of a string
      # but let's keep it simple for now
      # See 
https://github.com/mratsim/compute-graph-optim/blob/master/e07_part1_var_ADTs_tables.nim#L5-L7
      hooks[$name] = name
    
    macro runHook(pragma: untyped, moddedProc: untyped): untyped =
      result = moddedProc
      
      result[6].expectKind(nnkStmtList)
      result[6].add newCall(pragma)
    
    registerHook post_foo:
      # need a dirty template to capture x
      echo "foo done. x=", x
    
    proc foo {.runHook: post_foo.}=
      let x = 10
    
    proc main() =
      foo()
      echo "The end."
    
    main()
    
    
    Run

Reply via email to