]> git.lizzy.rs Git - uwu-lang.git/blob - src/run.c
Update capitalization of Turing in the README (#1)
[uwu-lang.git] / src / run.c
1 #include <dlfcn.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include "common/err.h"
5 #include "common/dl.h"
6 #include "load.h"
7 #include "run.h"
8
9 static void free_expression(UwUVMExpression *expr)
10 {
11         if (expr->type == EX_FNCALL) {
12                 for (size_t i = 0; i < expr->value.cll_value.num_args; i++)
13                         free_expression(&expr->value.cll_value.args[i]);
14
15                 free(expr->value.cll_value.args);
16         }
17
18         if (expr->type == EX_STRLIT)
19                 free(expr->value.str_value);
20 }
21
22 void run_module(const char *progname, const char *modname, size_t num_args, char *args[])
23 {
24         (void) num_args;
25         (void) args;
26
27         Program program = load_program(progname, modname);
28
29         UwUVMValue (*uwuvm_call_function)(UwUVMFunction *, size_t, UwUVMExpression *, UwUVMArgs *) = dlsym(program.api_library, "uwuvm_call_function");
30         char      *(*uwuvm_print_value  )(UwUVMValue                                             ) = dlsym(program.api_library, "uwuvm_print_value"  );
31         void       (*uwuvm_delet_value  )(UwUVMValue                                             ) = dlsym(program.api_library, "uwuvm_delet_value"  );
32
33         check_dlerror();
34
35         UwUVMExpression arg_expressions[num_args];
36
37         for (size_t i = 0; i < num_args; i++)
38                 arg_expressions[i] = (UwUVMExpression) {
39                         .type = EX_STRLIT,
40                         .value = {
41                                 .str_value = args[i],
42                         },
43                 };
44
45         UwUVMValue result = uwuvm_call_function(program.main_function, num_args, arg_expressions, NULL);
46
47         char *str = uwuvm_print_value(result);
48         printf("%s\n", str);
49         free(str);
50
51         uwuvm_delet_value(result);
52
53         for (size_t i = 0; i < program.num_functions; i++) {
54                 UwUVMFunction *function = program.functions[i];
55
56                 if (function->type == MODULE_PLAIN) {
57                         free_expression(function->value.plain);
58                         free(function->value.plain);
59                 }
60
61                 free(function);
62         }
63
64         free(program.functions);
65
66         for (size_t i = 0; i < program.num_libraries; i++)
67                 dlclose(program.libraries[i]);
68
69         if (program.libraries)
70                 free(program.libraries);
71
72         dlclose(program.api_library);
73 }