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 /* the global test variable should've been reset since the previous run */ 29 print("Global variable is null? " + (global.test == null) + "\n"); 30 31 global.test = true; 32 %} 33 ); 34 35 static uc_parse_config_t config = { 36 .strict_declarations = false, 37 .lstrip_blocks = true, 38 .trim_blocks = true 39 }; 40 41 int main(int argc, char **argv) 42 { 43 int exit_code = 0; 44 45 /* create a source buffer containing the program code */ 46 uc_source_t *src = uc_source_new_buffer("my program", strdup(program_code), strlen(program_code)); 47 48 /* compile source buffer into function */ 49 char *syntax_error = NULL; 50 uc_program_t *program = uc_compile(&config, src, &syntax_error); 51 52 /* release source buffer */ 53 uc_source_put(src); 54 55 /* check if compilation failed */ 56 if (!program) { 57 fprintf(stderr, "Failed to compile program: %s\n", syntax_error); 58 59 return 1; 60 } 61 62 /* initialize default module search path */ 63 uc_search_path_init(&config.module_search_path); 64 65 /* execute compiled program function five times */ 66 for (int i = 0; i < 5; i++) { 67 /* initialize VM context */ 68 uc_vm_t vm = { 0 }; 69 uc_vm_init(&vm, &config); 70 71 /* load standard library into global VM scope */ 72 uc_stdlib_load(uc_vm_scope_get(&vm)); 73 74 printf("Iteration %d: ", i + 1); 75 76 /* execute program function */ 77 int return_code = uc_vm_execute(&vm, program, NULL); 78 79 /* handle return status */ 80 if (return_code == ERROR_COMPILE || return_code == ERROR_RUNTIME) { 81 printf("An error occurred while running the program\n"); 82 exit_code = 1; 83 break; 84 } 85 86 /* free VM context */ 87 uc_vm_free(&vm); 88 } 89 90 /* release program function */ 91 uc_program_put(program); 92 93 /* free search module path vector */ 94 uc_search_path_free(&config.module_search_path); 95 96 return exit_code; 97 } 98
This page was automatically generated by LXR 0.3.1. • OpenWrt