summary refs log tree commit diff stats
path: root/tests/compilerapi/tcompilerapi.nim
blob: 00c9bc5231d999a8fe0e26dadb249349dfe45d4e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
discard """
  output: '''top level statements are executed!
2.0
'''
"""

## Example program that demonstrates how to use the
## compiler as an API to embed into your own projects.

import "../../compiler" / [ast, vmdef, vm, nimeval]
import std / [os]

proc main() =
  let std = findNimStdLib()
  if std.len == 0:
    quit "cannot find Nim's standard library"

  var intr = createInterpreter("myscript.nim", [std, getAppDir()])
  intr.declareRoutine("*", "exposed", "addFloats", proc (a: VmArgs) =
    setResult(a, getFloat(a, 0) + getFloat(a, 1) + getFloat(a, 2))
  )

  intr.evalScript()

  let foreignProc = selectRoutine(intr, "hostProgramRunsThis")
  if foreignProc == nil:
    quit "script does not export a proc of the name: 'hostProgramRunsThis'"
  let res = intr.callRoutine(foreignProc, [newFloatNode(nkFloatLit, 0.9),
                                           newFloatNode(nkFloatLit, 0.1)])
  if res.kind == nkFloatLit:
    echo res.floatVal
  else:
    echo "bug!"
  destroyInterpreter(intr)

main()