tcompilerapi.nim 1.6 KB

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