-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathevaluate.jou
More file actions
426 lines (354 loc) · 17.2 KB
/
Copy pathevaluate.jou
File metadata and controls
426 lines (354 loc) · 17.2 KB
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import "stdlib/assert.jou"
import "stdlib/limits.jou"
import "stdlib/io.jou"
import "stdlib/errno.jou"
import "stdlib/str.jou"
import "stdlib/list.jou"
import "stdlib/mem.jou"
import "./ast.jou"
import "./paths.jou"
import "./typecheck/common.jou"
import "./typecheck/step1_global_symbols.jou"
import "./state.jou"
import "./errors_and_warnings.jou"
import "./constants.jou"
import "./types.jou"
@public
def get_special_constant(name: byte*) -> Constant*:
if global_compiler_state.special_constants[0].name == NULL:
# called for the first time, initialize special constants
global_compiler_state.special_constants = [
SpecialConstant{name = "WINDOWS", constant = Constant{kind = ConstantKind.Bool, boolean = WINDOWS}},
# TODO: Set the value of LINUX constant properly
SpecialConstant{name = "LINUX", constant = Constant{kind = ConstantKind.Bool, boolean = (not WINDOWS and not MACOS and not NETBSD)}},
SpecialConstant{name = "MACOS", constant = Constant{kind = ConstantKind.Bool, boolean = MACOS}},
SpecialConstant{name = "NETBSD", constant = Constant{kind = ConstantKind.Bool, boolean = NETBSD}},
SpecialConstant{name = "IS_32BIT", constant = Constant{kind = ConstantKind.Bool, boolean = IS_32BIT}},
]
for i = 0; i < array_count(global_compiler_state.special_constants); i++:
if strcmp(global_compiler_state.special_constants[i].name, name) == 0:
return &global_compiler_state.special_constants[i].constant
return NULL
# Return values: 1=true 0=false -1=error
def evaluate_boolean_and_or(jou_file: JouFile*, expr: AstExpression*, and_or: byte*) -> int:
assert strcmp(and_or, "and") == 0 or strcmp(and_or, "or") == 0
value: Constant
if not evaluate_constant_expression(jou_file, expr, &value, bool_type()):
return -1
if value.kind != ConstantKind.Bool:
# Use the same error message as typecheck
msg: byte[500]
snprintf(msg, sizeof(msg), "'%s' only works with bools, not %s", and_or, value.get_type().name)
fail(expr.location, msg)
return value.boolean as int
# Replaces \r\n with \n in-place
def crlf_to_lf(s: byte*) -> None:
out = s
while *s != '\0':
if starts_with(s, "\r\n"):
s++
*out++ = *s++
*out = '\0'
def read_embedded_file(
jou_file: JouFile*,
specified_path: byte*,
location: Location,
embed_as_text: bool,
) -> List[byte]:
msg: byte[500]
# If I remember correctly, dirname() may modify the given path
joufile_path = strdup(jou_file.path)
assert joufile_path != NULL
full_path: byte* = NULL
asprintf(&full_path, "%s/%s", dirname(joufile_path), specified_path)
assert full_path != NULL
free(joufile_path)
file = fopen(full_path, "rb")
if file == NULL:
simplify_path(full_path)
snprintf(msg, sizeof(msg), "cannot open file \"%s\": %s", full_path, strerror(get_errno()))
fail(location, msg)
file_content = List[byte]{}
buf: byte[4096]
while True:
num_read = fread(buf, 1, sizeof(buf), file)
if num_read == 0:
if ferror(file) != 0:
# TODO: include errno in the error message?
# TODO: test this?
# If you change this, you might also want to change the tokenizer.
fail(location, "cannot read file")
break
file_content.extend_from_ptr(buf, num_read)
fclose(file)
# Embedding empty binary file would create array of size zero which is disallowed.
# Embedding empty text file creates an array of size 1 (for '\0' at end) which is fine.
if file_content.len == 0 and not embed_as_text:
simplify_path(full_path)
snprintf(msg, sizeof(msg), "file \"%s\" is empty", full_path)
fail(location, msg)
if embed_as_text:
for p = file_content.ptr; p < file_content.end(); p++:
if *p == '\0':
simplify_path(full_path)
snprintf(msg, sizeof(msg), "file \"%s\" contains a zero byte", full_path)
fail(location, msg)
file_content.append('\0')
crlf_to_lf(file_content.ptr)
file_content.len = strlen(file_content.ptr) + 1
free(full_path)
return file_content
# Returns False if the expression is not a simple compile-time constant.
#
# As the naming suggests, the type hint is only a hint and result type may differ.
# Set the type hint to NULL if you don't care about it.
@public
def evaluate_constant_expression(jou_file: JouFile*, expr: AstExpression*, result: Constant*, type_hint: Type*) -> bool:
assert jou_file != NULL
msg: byte[500]
match expr.kind:
case AstExpressionKind.IntegerConstant:
if type_hint != NULL and type_hint.is_integer_type():
t = type_hint
else:
t = int_type(32)
if expr.integer_value > t.max_value():
snprintf(msg, sizeof(msg), "value does not fit into %s", t.name)
fail(expr.location, msg)
*result = int_constant(t, expr.integer_value as int64)
return True
case AstExpressionKind.Constant:
*result = expr.constant.copy()
return True
case AstExpressionKind.EmbedBinaryFile | AstExpressionKind.EmbedTextFile:
filename_constant: Constant
if not evaluate_constant_expression(jou_file, expr.operands, &filename_constant, uint_type(8).pointer_type()):
fail(expr.location, "failed to evaluate file name at compile time")
if filename_constant.kind != ConstantKind.PointerString:
snprintf(msg, sizeof(msg), "file name must be a string, not %s", filename_constant.get_type().name)
fail(expr.location, msg)
file_content = read_embedded_file(
jou_file,
filename_constant.pointer_string,
expr.location,
expr.kind == AstExpressionKind.EmbedTextFile,
)
filename_constant.free()
assert file_content.len > 0
assert file_content.len <= INT32_MAX # TODO
*result = Constant{kind = ConstantKind.ArrayOfBytes, array_of_bytes = file_content}
return True
case AstExpressionKind.EnumCount:
enum_type = type_from_ast(jou_file, NULL, &expr.enumcount.enum_type_ast)
if enum_type.kind != TypeKind.Enum:
snprintf(msg, sizeof(msg), "enum_count must be called on an enum type, not %s", enum_type.short_description())
fail(expr.location, msg)
expr.enumcount.enum_type = enum_type
*result = int_constant(int_type(32), enum_type.enum_members.len)
return True
case AstExpressionKind.GetVariable:
# Values of `const` constants, special constants (e.g. WINDOWS)
c = find_and_typecheck_constant(jou_file, expr.varname)
if c == NULL:
return False
*result = c.copy()
return True
case AstExpressionKind.And:
lhs = evaluate_boolean_and_or(jou_file, &expr.operands[0], "and")
rhs = evaluate_boolean_and_or(jou_file, &expr.operands[1], "and")
if lhs == -1 or rhs == -1:
return False
*result = Constant{kind = ConstantKind.Bool, boolean = (lhs == 1 and rhs == 1)}
return True
case AstExpressionKind.Or:
lhs = evaluate_boolean_and_or(jou_file, &expr.operands[0], "or")
rhs = evaluate_boolean_and_or(jou_file, &expr.operands[1], "or")
if lhs == -1 or rhs == -1:
return False
*result = Constant{kind = ConstantKind.Bool, boolean = (lhs == 1 or rhs == 1)}
return True
case AstExpressionKind.Not:
if not evaluate_constant_expression(jou_file, &expr.operands[0], result, bool_type()):
return False
if result.kind != ConstantKind.Bool:
# Error message is same as during type checking
snprintf(msg, sizeof(msg), "value after 'not' must be a bool, not %s", result.get_type().name)
fail(expr.location, msg)
result.boolean = not result.boolean
return True
case AstExpressionKind.Negate:
# Special-case e.g. "const foo: int8 = -128" because 128 is not a
# valid int8 but -128 is, so can't just evaluate 128 and add minus.
if (
type_hint != NULL
and type_hint.is_integer_type()
and expr.operands[0].kind == AstExpressionKind.IntegerConstant
and expr.operands[0].integer_value == (-type_hint.min_value()) as uint64
):
*result = int_constant(type_hint, type_hint.min_value())
return True
if not evaluate_constant_expression(jou_file, &expr.operands[0], result, type_hint):
return False
match result.get_type().kind:
case TypeKind.SignedInteger:
# Negating the smallest signed integer would overflow.
# For example, int8 goes from -128 to +127.
# TODO: test this when possible
if result.integer.value == result.get_type().min_value():
return False
result.integer.value *= -1
return True
case TypeKind.FloatingPoint:
result.float_or_double_value *= -1
return True
case _:
return False
# Evaluate float division in some very limited cases.
# Mostly for defining "INF = 1.0 / 0.0" and similar constants.
#
# Note: This evaluates the division on the computer that is compiling,
# not on the target. So if floating point works differently on the
# target computer, this may be off. Currently that is not the case with
# any of our supported compilation targets.
case AstExpressionKind.Div:
if type_hint != float_type() and type_hint != double_type():
return False
lhs_rhs: Constant[2]
for i = 0; i < 2; i++:
if not evaluate_constant_expression(jou_file, &expr.operands[i], &lhs_rhs[i], type_hint):
return False
if lhs_rhs[i].get_type() != type_hint:
return False
assert lhs_rhs[0].kind == lhs_rhs[1].kind
*result = Constant{
kind = lhs_rhs[0].kind,
float_or_double_value = lhs_rhs[0].float_or_double_value / lhs_rhs[1].float_or_double_value,
}
return True
case AstExpressionKind.Array:
if type_hint != NULL and type_hint.kind == TypeKind.Array:
item_type_hint = type_hint.array.item_type
else:
item_type_hint = NULL
assert expr.array.len > 0
items = List[Constant]{}
for item_ast = expr.array.ptr; item_ast < expr.array.end(); item_ast++:
item: Constant
if not evaluate_constant_expression(jou_file, item_ast, &item, item_type_hint):
for p = items.ptr; p < items.end(); p++:
p.free()
free(items.ptr)
return False
if items.len > 0 and item.get_type() != items.ptr[0].get_type():
snprintf(
msg,
sizeof(msg),
"array items have different types (%s, %s)",
items.ptr[0].get_type().name,
item.get_type().name
)
fail(expr.location, msg)
items.append(item)
*result = Constant{kind = ConstantKind.Array, array_elements = items}
return True
case _:
return False
@public
def evaluate_array_length(jou_file: JouFile*, expr: AstExpression*) -> int:
# TODO: this should probably support int64
c: Constant
if evaluate_constant_expression(jou_file, expr, &c, int_type(32)) and c.get_type() == int_type(32):
return c.integer.value as int
fail(expr.location, "cannot evaluate array length at compile time")
def choose_if_elif_branch(jou_file: JouFile*, if_stmt: AstIfStatement*) -> List[AstStatement]*:
cond: Constant
# Return the first branch whose condition is true.
# Return NULL if we fail to evaluate a condition and it must be checked at runtime.
for p = if_stmt.if_and_elifs.ptr; p < if_stmt.if_and_elifs.end(); p++:
if (not evaluate_constant_expression(jou_file, &p.condition, &cond, bool_type())) or cond.kind != ConstantKind.Bool:
return NULL
if cond.boolean:
return &p.body
# All conditions are known to be false.
return &if_stmt.else_body
# Replaces the statement body.ptr[i] with statements from a given list.
def replace(body: List[AstStatement]*, i: int, new: List[AstStatement]) -> None:
body.ptr[i].free()
body.grow(body.len + new.len)
# How many statements after index i we want to preserve
nkeep = body.len - (i+1)
# Delete body.ptr[i] and shift everything after it to their new place
memmove(&body.ptr[i + new.len], &body.ptr[i+1], nkeep * sizeof(body.ptr[0]))
# Put the new statements to their place.
memcpy(&body.ptr[i], new.ptr, new.len * sizeof(new.ptr[0]))
body.len += new.len - 1 # -1 for index i which was removed
def evaluate_if_statements_in_body(jou_file: JouFile*, body: List[AstStatement]*, must_succeed: bool) -> None:
# Must use indexes, because mutating the body may reallocate it to different memory location.
for i = 0; i < body.len; i++:
match body.ptr[i].kind:
case AstStatementKind.If:
if_stmt = &body.ptr[i].if_statement
branch = choose_if_elif_branch(jou_file, if_stmt)
if branch == NULL and must_succeed:
fail(body.ptr[i].location, "cannot evaluate condition at compile time")
if branch != NULL:
# The if/elif statement always takes the same branch.
# Replace the whole if/elif with that branch.
replacement = *branch
*branch = List[AstStatement]{} # avoid double-free
replace(body, i, replacement)
free(replacement.ptr)
i-- # cancels i++ to do same index again, so that we handle nested if statements
continue
# Recurse into inner if statements. Needed when compile-time if
# statement is inside a runtime if statement.
for p = if_stmt.if_and_elifs.ptr; p < if_stmt.if_and_elifs.end(); p++:
evaluate_if_statements_in_body(jou_file, &p.body, False)
evaluate_if_statements_in_body(jou_file, &if_stmt.else_body, False)
case AstStatementKind.WhileLoop:
evaluate_if_statements_in_body(jou_file, &body.ptr[i].while_loop.body, False)
case AstStatementKind.ForLoop:
evaluate_if_statements_in_body(jou_file, &body.ptr[i].for_loop.body, False)
case AstStatementKind.Class:
evaluate_if_statements_in_body(jou_file, &body.ptr[i].classdef.body, True)
case AstStatementKind.FunctionDef:
evaluate_if_statements_in_body(jou_file, &body.ptr[i].function.body, False)
case AstStatementKind.MethodDef:
evaluate_if_statements_in_body(jou_file, &body.ptr[i].method.body, False)
case (
AstStatementKind.ExpressionStatement
| AstStatementKind.Link
| AstStatementKind.Assert
| AstStatementKind.Pass
| AstStatementKind.Return
| AstStatementKind.Match
| AstStatementKind.Break
| AstStatementKind.Continue
| AstStatementKind.DeclareLocalVar
| AstStatementKind.Assign
| AstStatementKind.InPlaceAdd
| AstStatementKind.InPlaceSub
| AstStatementKind.InPlaceMul
| AstStatementKind.InPlaceDiv
| AstStatementKind.InPlaceFloorDiv
| AstStatementKind.InPlaceMod
| AstStatementKind.InPlaceBitAnd
| AstStatementKind.InPlaceBitOr
| AstStatementKind.InPlaceBitXor
| AstStatementKind.InPlaceBitShiftLeft
| AstStatementKind.InPlaceBitShiftRight
| AstStatementKind.FunctionDeclare
| AstStatementKind.Enum
| AstStatementKind.GlobalVariableDeclare
| AstStatementKind.GlobalVariableDef
| AstStatementKind.Import
| AstStatementKind.ClassField
| AstStatementKind.ClassUnion
| AstStatementKind.Const
| AstStatementKind.TypeDef
):
# these statements cannot contain if statements, no need to recurse inside
pass
@public
def evaluate_compile_time_if_statements(jou_file: JouFile*) -> None:
evaluate_if_statements_in_body(jou_file, &jou_file.ast, True)