/
bootstrap.ngs
306 lines (259 loc) · 7.96 KB
/
bootstrap.ngs
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# === Exception ==================================
doc Initialize an Exception.
doc %RET - Exception with .backtrace and .message
doc message - Goes into .message
F init(e:Exception, message:Str) {
e.message = message
}
doc Initialize an Exception.
doc %RET - Exception with .backtrace and .cause
F init(e:Exception, cause:Exception) {
e.cause = cause
}
doc Initialize an Exception.
doc %RET - Exception with .backtrace, .message, and .cause
F init(e:Exception, message:Str, cause:Exception) {
e.message = message
e.cause = cause
}
{
type NotImplemented; NotImplemented.inherit(Exception)
type ReadFail; ReadFail.inherit(Exception)
type RequireFail; RequireFail.inherit(Exception)
type MainFail; MainFail.inherit(Exception)
doc Represents error when converting program execution result to exit code
type ExitCodeFail; ExitCodeFail.inherit(Exception)
doc Information about exiting, used by bootstrap and as argument to exit_hook.
doc exit_code - the code to exit with
doc exceptions - exceptions that occurred during exit procedure
type Exit
}
# === bootstrap ==================================
# *** Convert values returned by the program (or -e/-E expression) to exit codes ***
doc %RET - always 0
F ExitCode(x) 0
doc %RET - 0 for true, 1 for false
F ExitCode(b:Bool) if b 0 1
doc %RET - n
F ExitCode(n:Int) n
doc %RET - Always 240
F ExitCode(e:Exception) 240
doc Create MultiMethod with no methods
F MultiMethod() super([])
doc Number of methods in MultiMethod
F len(mm:MultiMethod) mm.Arr().len()
doc Whether MultiMethod has any methods
F Bool(mm:MultiMethod) mm.Arr().Bool()
main = MultiMethod()
# *** Define bootstrap_debug function ***
bootstrap_debug =
if 'NGS_BOOTSTRAP_DEBUG' in ENV
F(s) echo(2, "+ [BOOSTRAP DEBUG] $s")
else
F(s) {}
bootstrap_ngs_dir_candidates = [
'/usr/local/etc/ngs'
'/usr/local/lib/ngs'
'/etc/ngs'
'/usr/lib/ngs'
]
doc Internal method. Please do not use.
doc Find which of bootstrap_ngs_dir_candidates directories contains stdlib.ngs . That directory would be the "NGS_DIR".
doc %RET - Str or null
doc %STATUS - internal
F bootstrap_find_ngs_dir() {
'NGS_DIR' in ENV returns ENV['NGS_DIR']
l = bootstrap_ngs_dir_candidates.len()
for(i;l) {
c_access("${bootstrap_ngs_dir_candidates[i]}/stdlib.ngs", ACCESS['F_OK']) == 0 returns bootstrap_ngs_dir_candidates[i]
}
null
}
# *** read - abstraction above low level c io primitives ***
# TODO: Better exceptions
doc Fetches the whole file
doc fname - File name to read
doc %RET - Whole file as a string
F read(fname:Str) {
try {
fd = c_open(fname, 'r')
fd <= 0 throws Exception("read(): failed to open file ${fname}")
bootstrap_debug("read(): opened file ${fname} as fd ${fd}")
file_len = c_lseek(fd, 0, "end")
file_len < 0 throws Exception("read(): failed to get the size of file ${fname}")
c_lseek(fd, 0, "set")
bootstrap_debug("read(): file size of ${fname} is ${file_len}")
data = c_read(fd, file_len)
c_close(fd)
data[1]
} catch(e) {
throw ReadFail(e)
}
}
F bootstrap_print_compilation_warnings(program_bytecode, fname) {
warnings = program_bytecode.attrs()['warnings']
l = warnings.len()
for(i;l) {
w = warnings[i]
wl = w['location']
echo(2, "${fname}:${wl['first_line']}:${wl['first_column']} warning: ${w['message']}")
}
}
doc Runs the given file
doc %RET - Typically whatever the last expression in the file evaluates to
F require(fname:Str) {
try {
program_text = read(fname)
program_bytecode = compile(program_text, fname)
bootstrap_debug("require(): bytecode for ${fname} has length of ${program_bytecode.len()} bytes")
bootstrap_print_compilation_warnings(program_bytecode, fname)
program_func = load(program_bytecode, "require()d file: $fname")
ret = program_func()
bootstrap_debug("require(): done requiring ${fname}")
ret
} catch(e) {
throw RequireFail(e)
}
}
doc Internal method. Please do not use.
doc Main entry point. Executed on NGS boot.
doc %STATUS - internal
F bootstrap() {
global ARGV0
global ORIG_ARGV = copy(ARGV)
do_load_stdlib = true
code_to_run = null
bootstrap_debug('bootstrap.ngs begin')
bootstrap_debug("BOOTSTRAP_FILE=$BOOTSTRAP_FILE")
# *** Prepare ARGV ***
# first_item = shift(array, default_value_if_array_is_empty)
ARGV0 = ARGV.shift(null)
# *** Parse switches ***
sw = null
if ARGV {
a = ARGV[0]
if (a == '--version') {
echo(VERSION)
return 0
}
if (a == '-e' or a == '-E' or a == '-p' or a == '-pj' or a == '-pi' or a == '-pl' or a == '-pil' or a == '-pjl' or a == '-pc' or a == '-pt') {
sw = ARGV.shift()
# Newline at the end is for avoiding # commenting out the closing }
# Newline at the beginning is for symmetry
default_code = 'F default_argv_code() { fetch() }()'
code_to_run = "{\n${ARGV.shift(default_code)}\n}"
bootstrap_debug("Got $sw switch, using command line provided code")
if sw == '-E' {
bootstrap_debug('Will skip loading stdlib because of -E flag')
do_load_stdlib = false
}
fname = "<command line ${sw} switch>"
}
}
if 'NGS_SKIP_STDLIB' in ENV {
bootstrap_debug('Will skip loading stdlib because of set NGS_SKIP_STDLIB environment variable')
do_load_stdlib = false
}
global NGS_DIR = bootstrap_find_ngs_dir()
NGS_DIR is Null throws Exception("Could not find NGS_DIR")
if do_load_stdlib {
bootstrap_debug('Will load stdlib')
stdlib_file = "${NGS_DIR}/stdlib.ngs"
bootstrap_debug("Stdlib is at $stdlib_file")
require(stdlib_file)
}
# Note: not() is not defined yet
if code_to_run is Null {
bootstrap_debug('No -e or -E switch was passed, will load the program from a file')
fname = ARGV.shift(null)
if fname is Null {
fname = ENV.get('NGS_CLI', "${NGS_DIR}/cli.ngs")
} else {
ARGV0 = fname
}
code_to_run = read(fname)
}
program_bytecode = compile(code_to_run, fname)
bootstrap_debug("bootstrap(): bytecode for ${fname} has length of ${program_bytecode.len()} bytes")
bootstrap_print_compilation_warnings(program_bytecode, fname)
program_func = load(program_bytecode, "bootstrap()ped file: $fname")
result = program_func()
# Handle main() - start
if main.len() > 0 {
bootstrap_debug("main() defined, using bootstrap_invoke_main()")
if global_not_found_handler.len() == 0 {
throw MainFail("Autoloading (usually defined in stdlib) is not present but the main() invoking mechanism requires it")
}
result = bootstrap_invoke_main(fname, result)
}
# Handle main() - end
if sw == '-E' {
} else {
transformation = {
'-pl': identity
'-pil': inspect
'-pjl': encode_json
}
if sw in transformation {
for r in result {
transformation[sw](r).echo()
}
return 0
}
transformation = {
'-p': identity
'-pi': inspect
'-pj': encode_json
'-pc': code
'-pt': { Table2::Table(A) }
}
if sw in transformation {
echo(transformation[sw](result))
return 0
}
}
result.ExitCode()
}
doc Uses built-in dump() to show an exception. Only used if stdlib is not loaded (stdlib defines better method).
F print_exception(e:Exception) {
dump(exception)
}
doc Prints exceptions. Only used if stdlib is not loaded (stdlib changes exit_hook to a Hook object).
F exit_hook(exit:Exit) {
for(i; exit.exceptions.len()) {
echo(2, "[exit_hook] --- Uncaught exception ---")
print_exception(exit.exceptions[i])
}
}
doc Internal method. Please do not use.
doc Runs bootstrap() and handles exceptions.
doc %STATUS - internal
F bootstrap_exception_catch_wrapper() {
exit = Exit()
exit.exit_code = 0
exit.exceptions = []
try {
exit.exit_code = bootstrap()
} catch(e:Exception) {
exit.exceptions.push(e)
exit.exit_code = 240
try {
exit.exit_code = e.ExitCode()
} catch(e:Exception) {
exit.exceptions.push(ExitCodeFail("Failed to convert exception to exit code", e))
exit.exit_code = exit.exit_code + 1
}
}
try {
exit_hook(exit)
} catch(e:Exception) {
exit.exceptions.push(e)
exit.exit_code = exit.exit_code + 2
for(i; exit.exceptions.len()) {
echo(2, "[bootstrap_exception_catch_wrapper] --- Uncaught exception ---")
dump(exit.exceptions[i])
}
}
c_exit(exit.exit_code)
}
bootstrap_exception_catch_wrapper()