1 /* 2 * Copyright (C) 2021 Jo-Philipp Wich <jo@mein.io> 3 * 4 * Permission to use, copy, modify, and/or distribute this software for any 5 * purpose with or without fee is hereby granted, provided that the above 6 * copyright notice and this permission notice appear in all copies. 7 * 8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 */ 16 17 #include <stdio.h> 18 19 #include <ucode/compiler.h> 20 #include <ucode/lib.h> 21 #include <ucode/vm.h> 22 23 24 #define MULTILINE_STRING(...) #__VA_ARGS__ 25 26 static const char *program_code = MULTILINE_STRING( 27 {% 28 let n = global.value || 1; 29 30 print("Current value is " + n + "\n"); 31 32 global.value = n * 2; 33 %} 34 ); 35 36 static uc_parse_config_t config = { 37 .strict_declarations = false, 38 .lstrip_blocks = true, 39 .trim_blocks = true 40 }; 41 42 int main(int argc, char **argv) 43 { 44 int exit_code = 0; 45 46 /* create a source buffer containing the program code */ 47 uc_source_t *src = uc_source_new_buffer("my program", strdup(program_code), strlen(program_code)); 48 49 /* compile source buffer into function */ 50 char *syntax_error = NULL; 51 uc_program_t *program = uc_compile(&config, src, &syntax_error); 52 53 /* release source buffer */ 54 uc_source_put(src); 55 56 /* check if compilation failed */ 57 if (!program) { 58 fprintf(stderr, "Failed to compile program: %s\n", syntax_error); 59 60 return 1; 61 } 62 63 /* initialize default module search path */ 64 uc_search_path_init(&config.module_search_path); 65 66 /* initialize VM context */ 67 uc_vm_t vm = { 0 }; 68 uc_vm_init(&vm, &config); 69 70 /* load standard library into global VM scope */ 71 uc_stdlib_load(uc_vm_scope_get(&vm)); 72 73 /* execute compiled program function five times */ 74 for (int i = 0; i < 5; i++) { 75 printf("Iteration %d: ", i + 1); 76 77 /* execute program function */ 78 int return_code = uc_vm_execute(&vm, program, NULL); 79 80 /* handle return status */ 81 if (return_code == ERROR_COMPILE || return_code == ERROR_RUNTIME) { 82 printf("An error occurred while running the program\n"); 83 exit_code = 1; 84 break; 85 } 86 87 /* perform GC step */ 88 ucv_gc(&vm); 89 } 90 91 /* release program function */ 92 uc_program_put(program); 93 94 /* free VM context */ 95 uc_vm_free(&vm); 96 97 /* free search module path vector */ 98 uc_search_path_free(&config.module_search_path); 99 100 return exit_code; 101 } 102
This page was automatically generated by LXR 0.3.1. • OpenWrt