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