tcompilerapi.nim 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. discard """
  2. output: '''top level statements are executed!
  3. (ival: 10, fval: 2.0)
  4. 2.0
  5. my secret
  6. 11
  7. 12
  8. '''
  9. joinable: "false"
  10. """
  11. ## Example program that demonstrates how to use the
  12. ## compiler as an API to embed into your own projects.
  13. import "../../compiler" / [ast, vmdef, vm, nimeval, llstream]
  14. import std / [os]
  15. proc main() =
  16. let std = findNimStdLibCompileTime()
  17. var intr = createInterpreter("myscript.nim",[std, parentDir(currentSourcePath)])
  18. intr.implementRoutine("*", "exposed", "addFloats", proc (a: VmArgs) =
  19. setResult(a, getFloat(a, 0) + getFloat(a, 1) + getFloat(a, 2))
  20. )
  21. intr.evalScript()
  22. let foreignProc = selectRoutine(intr, "hostProgramRunsThis")
  23. if foreignProc == nil:
  24. quit "script does not export a proc of the name: 'hostProgramRunsThis'"
  25. let res = intr.callRoutine(foreignProc, [newFloatNode(nkFloatLit, 0.9),
  26. newFloatNode(nkFloatLit, 0.1)])
  27. doAssert res.kind == nkFloatLit
  28. echo res.floatVal
  29. let foreignValue = selectUniqueSymbol(intr, "hostProgramWantsThis")
  30. if foreignValue == nil:
  31. quit "script does not export a global of the name: hostProgramWantsThis"
  32. let val = intr.getGlobalValue(foreignValue)
  33. doAssert val.kind in {nkStrLit..nkTripleStrLit}
  34. echo val.strVal
  35. destroyInterpreter(intr)
  36. main()
  37. block issue9180:
  38. proc evalString(code: string, moduleName = "script.nim") =
  39. let stream = llStreamOpen(code)
  40. let std = findNimStdLibCompileTime()
  41. var intr = createInterpreter(moduleName, [std])
  42. intr.evalScript(stream)
  43. destroyInterpreter(intr)
  44. llStreamClose(stream)
  45. evalString("echo 10+1")
  46. evalString("echo 10+2")