example.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include "gravity_compiler.h"
  2. #include "gravity_macros.h"
  3. #include "gravity_core.h"
  4. #include "gravity_vm.h"
  5. #define SOURCE "func main() {var a = 10; var b=20; return a + b}"
  6. // error reporting callback called by both compiler or VM
  7. static void report_error (gravity_vm *vm, error_type_t error_type,
  8. const char *description, error_desc_t error_desc, void *xdata) {
  9. printf("%s\n", description);
  10. exit(0);
  11. }
  12. int main (void) {
  13. // configure a VM delegate
  14. gravity_delegate_t delegate = {.error_callback = report_error};
  15. // compile Gravity source code into bytecode
  16. gravity_compiler_t *compiler = gravity_compiler_create(&delegate);
  17. gravity_closure_t *closure = gravity_compiler_run(compiler, SOURCE, strlen(SOURCE), 0, true, true);
  18. // sanity check on compiled source
  19. if (!closure) {
  20. // an error occurred while compiling source code and it has already been reported by the report_error callback
  21. gravity_compiler_free(compiler);
  22. return 1;
  23. }
  24. // create a new VM
  25. gravity_vm *vm = gravity_vm_new(&delegate);
  26. // transfer objects owned by the compiler to the VM (so they can be part of the GC)
  27. gravity_compiler_transfer(compiler, vm);
  28. // compiler can now be freed
  29. gravity_compiler_free(compiler);
  30. // run main closure inside Gravity bytecode
  31. if (gravity_vm_runmain(vm, closure)) {
  32. // print result (INT) 30 in this simple example
  33. gravity_value_t result = gravity_vm_result(vm);
  34. gravity_value_dump(vm, result, NULL, 0);
  35. }
  36. // free VM memory and core libraries
  37. gravity_vm_free(vm);
  38. gravity_core_free();
  39. return 0;
  40. }