-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagate-run.c
114 lines (90 loc) · 2.37 KB
/
agate-run.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// SPDX-License-Identifier: MIT
// Copyright (c) 2022 Julien Bernard
#include <stdio.h>
#include <stdlib.h>
#include "agate.h"
static void repl(AgateVM *vm) {
char line[1024];
for (;;) {
printf("> ");
if (!fgets(line, sizeof(line), stdin)) {
printf("\n");
break;
}
agateCallString(vm, "script", line);
}
}
static char *dump(const char *path) {
FILE *file = fopen(path, "rb");
if (file == NULL) {
fprintf(stderr, "Could not open file \"%s\".\n", path);
exit(EXIT_FAILURE);
}
fseek(file, 0L, SEEK_END);
long ret = ftell(file);
size_t size = ret > 0 ? ret : 0;
rewind(file);
char *buffer = (char *) malloc(size + 1);
if (buffer == NULL) {
fprintf(stderr, "Not enough memory to read \"%s\".\n", path);
exit(EXIT_FAILURE);
}
size_t count = fread(buffer, sizeof(char), size, file);
if (count < size) {
fprintf(stderr, "Could not read file \"%s\".\n", path);
exit(EXIT_FAILURE);
}
buffer[count] = '\0';
fclose(file);
return buffer;
}
static void run(AgateVM *vm, const char *path) {
char *source = dump(path);
AgateStatus status = agateCallString(vm, "script", source);
free(source);
if (status != AGATE_STATUS_OK) {
exit(EXIT_FAILURE);
}
}
static void print(AgateVM *vm, const char* text) {
fputs(text, stdout);
}
static void write(AgateVM *vm, uint8_t byte) {
fputc(byte, stdout);
}
static void error(AgateVM *vm, AgateErrorKind kind, const char *unit_name, int line, const char *message) {
switch (kind) {
case AGATE_ERROR_COMPILE:
printf("%s:%d: error: %s\n", unit_name, line, message);
break;
case AGATE_ERROR_RUNTIME:
printf("error: %s\n", message);
break;
case AGATE_ERROR_STACKTRACE:
printf("%s:%d: in %s\n", unit_name, line, message);
break;
}
}
static bool input(AgateVM *vm, char *buffer, size_t size) {
return fgets(buffer, size, stdin) != NULL;
}
int main(int argc, const char *argv[]) {
AgateConfig config;
agateConfigInitialize(&config);
config.print = print;
config.write = write;
config.error = error;
config.input = input;
AgateVM *vm = agateNewVM(&config);
if (argc == 1) {
repl(vm);
} else if (argc >= 2) {
agateSetArgs(vm, argc - 1, argv + 1);
run(vm, argv[1]);
} else {
fprintf(stderr, "Usage: agate-run [path]\n");
return EXIT_FAILURE;
}
agateDeleteVM(vm);
return EXIT_SUCCESS;
}