Version 1, exactly what you asked.
    
    
    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 runHooks(hook: untyped): untyped =
      result = newCall(hooks[$hook])
    
    registerHook post_foo:
      # need a dirty template to capture x
      echo "foo done. x=", x
    
    proc foo =
      let x = 10
      runHooks post_foo
    
    proc main() =
      foo()
      echo "The end."
    
    main()
    
    
    Run

Reply via email to