-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_codegen.sh
More file actions
executable file
·851 lines (799 loc) · 33.1 KB
/
Copy pathtest_codegen.sh
File metadata and controls
executable file
·851 lines (799 loc) · 33.1 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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
#!/bin/bash
# Test the full compilation pipeline: BLang source -> LLVM IR -> native binary -> run
# Requires: LLVM dev headers installed and qcc built with -DBLANG_HAS_LLVM
#
# Usage:
# ./test_codegen.sh # Run ALL codegen_*.b tests
# ./test_codegen.sh [test_file...] # Run specific test file(s)
# ./test_codegen.sh --verbose # Run all tests with IR output
# BUILD_DIR=path ./test_codegen.sh # Use a different build directory
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
BUILD_DIR="${BUILD_DIR:-${SCRIPT_DIR}/build}"
QCC="${BUILD_DIR}/qcc"
# U2 (optimization): OPT_LEVEL=<0..3|s|z> builds the whole suite at that -O level
# (qcc in-process IR passes + llc backend -O) so correctness under optimization
# is a hard gate. Empty = unoptimized (default, byte-identical to pre-U2).
OPT_LEVEL="${OPT_LEVEL:-}"
# llc accepts only numeric -O; the size levels run as IR passes in qcc, so map
# s/z to backend -O2 for the llc step.
LLC_OPT_LEVEL="${OPT_LEVEL}"
if [ "${LLC_OPT_LEVEL}" = "s" ] || [ "${LLC_OPT_LEVEL}" = "z" ]; then
LLC_OPT_LEVEL="2"
fi
# U3 (debug info): DEBUG_INFO=1 builds the whole suite with -g (DWARF emission)
# so correctness with debug info is a hard gate (done-condition #1). Empty =
# no debug info (default, byte-identical to pre-U3).
DEBUG_INFO="${DEBUG_INFO:-}"
RUNTIME_LIB="${BUILD_DIR}/libblang_runtime.a"
STRING_LIB="${BUILD_DIR}/libblang_string.a"
ARRAY_LIB="${BUILD_DIR}/libblang_array.a"
BUFFER_LIB="${BUILD_DIR}/libblang_buffer.a"
JSON_LIB="${BUILD_DIR}/libblang_json.a"
NET_LIB="${BUILD_DIR}/libblang_net.a"
FS_LIB="${BUILD_DIR}/libblang_fs.a"
SYS_LIB="${BUILD_DIR}/libblang_sys.a"
DB_LIB="${BUILD_DIR}/libblang_db.a"
MATH_LIB="${BUILD_DIR}/libblang_math.a"
TIME_LIB="${BUILD_DIR}/libblang_time.a"
RANDOM_LIB="${BUILD_DIR}/libblang_random.a"
ENV_LIB="${BUILD_DIR}/libblang_env.a"
HASH_LIB="${BUILD_DIR}/libblang_hash.a"
STDLIB_IO="${SCRIPT_DIR}/stdlib/io.b"
STDLIB_NET="${SCRIPT_DIR}/stdlib/net.b"
STDLIB_FS="${SCRIPT_DIR}/stdlib/fs.b"
STDLIB_SYS="${SCRIPT_DIR}/stdlib/sys.b"
STDLIB_BUFFER="${SCRIPT_DIR}/stdlib/buffer.b"
STDLIB_TIMER="${SCRIPT_DIR}/stdlib/timer.b"
STDLIB_COLLECTIONS="${SCRIPT_DIR}/stdlib/collections.b"
# Native stdlib modules (U4) — content-gated by `import <m>;` (see below).
STDLIB_MATH="${SCRIPT_DIR}/stdlib/math.b"
STDLIB_TIME="${SCRIPT_DIR}/stdlib/time.b"
STDLIB_RANDOM="${SCRIPT_DIR}/stdlib/random.b"
STDLIB_ENV="${SCRIPT_DIR}/stdlib/env.b"
STDLIB_CLI="${SCRIPT_DIR}/stdlib/cli.b"
# Colors — emitted only to a terminal. When stdout is a pipe/file (CI, and the
# epic-acceptance greps like `grep -Eq 'Leaks:[[:space:]]*0'`), ANSI codes are
# suppressed so the summary text is plain and machine-greppable (an ESC[0m reset
# between "Leaks:" and the count would otherwise defeat the grep).
if [ -t 1 ]; then
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
CYAN='\033[0;36m'
NC='\033[0m'
else
RED='' GREEN='' YELLOW='' CYAN='' NC=''
fi
VERBOSE=0
FILE_ARGS=()
LEAK_CHECK=0
VALGRIND=0
UPDATE_GOLDENS=0
SELFCHECK=0
for arg in "$@"; do
case "$arg" in
--verbose) VERBOSE=1 ;;
--leak-check) LEAK_CHECK=1 ;;
--valgrind) VALGRIND=1 ;;
--update-goldens) UPDATE_GOLDENS=1 ;;
--selfcheck) SELFCHECK=1 ;;
--help)
echo "Usage: $0 [--verbose] [--leak-check] [--valgrind] [--update-goldens] [--selfcheck] [test_file...]"
echo " --verbose Show IR output for each test"
echo " --leak-check Link with AddressSanitizer and report memory leaks"
echo " --valgrind Run each binary under Valgrind to detect memory leaks"
echo " --update-goldens Regenerate stdout goldens (test_files/<name>.expected.out)"
echo " for deterministic (non-quarantined) tests; never touches"
echo " quarantined tests."
echo " --selfcheck Prove the golden comparator has teeth: corrupt a real"
echo " committed golden in a TEMP copy, assert the suite goes red,"
echo " print 'SELFCHECK: OK', and exit non-zero. Never mutates a"
echo " committed golden."
echo " test_file... Run only the specified test file(s)"
echo ""
echo "By default each non-quarantined test's stdout is compared exactly (modulo a"
echo "single trailing newline) against its golden test_files/<name>.expected.out;"
echo "a mismatch fails the test with a diff. Quarantined tests"
echo "(test_files/codegen_quarantine.txt) run for exit code only."
echo ""
echo "With no test files, runs all test_files/codegen_*.b tests."
echo "Environment: BUILD_DIR overrides the build directory (default: ./build)."
exit 0
;;
*) FILE_ARGS+=("$arg") ;;
esac
done
# --leak-check: prefer ASan-INSTRUMENTED runtime archives (build-asan) when
# present. Linking the plain archives with -fsanitize only intercepts
# malloc/free — a read of freed memory inside uninstrumented runtime code
# (e.g. __blang_rc_release) goes undetected; that blind spot hid a real
# use-after-free that only surfaced on CI's allocator. With instrumented
# archives ASan traps the UAF itself, not just the leak. The archives are
# compiled with address,undefined, so the link flags must match.
ASAN_BUILD_DIR="${ASAN_BUILD_DIR:-${SCRIPT_DIR}/build-asan}"
LEAK_SANITIZE_FLAGS="-fsanitize=address,leak"
if [ "$LEAK_CHECK" -eq 1 ] && [ -f "${ASAN_BUILD_DIR}/libblang_runtime.a" ]; then
LEAK_SANITIZE_FLAGS="-fsanitize=address,undefined,leak"
for _mod in runtime string array buffer json net fs sys db math time random env hash; do
_asan_lib="${ASAN_BUILD_DIR}/libblang_${_mod}.a"
if [ -f "${_asan_lib}" ]; then
_var="$(echo "${_mod}" | tr 'a-z' 'A-Z')_LIB"
eval "${_var}=\"${_asan_lib}\""
fi
done
echo "--leak-check: using ASan-instrumented runtime archives from ${ASAN_BUILD_DIR}"
elif [ "$LEAK_CHECK" -eq 1 ]; then
# The ASan-instrumented archives are absent. Linking the PLAIN archives with
# -fsanitize only intercepts malloc/free, so a use-after-free READ inside
# uninstrumented runtime code (e.g. __blang_rc_release) goes undetected — the
# blind spot the U2 (modules-v2-graph) string-ARC regression lock exists to
# guard. Under CI a silent fallback would report green over an unrun check, so
# it is a HARD FAILURE (KI-5 action 3 precedent, test_build/run_build_tests.sh).
# Locally it degrades to a loud warning so a dev without build-asan can still run.
if [ "${CI:-}" = "true" ]; then
echo -e "${RED}Error: --leak-check requires the ASan-instrumented runtime archives, absent at ${ASAN_BUILD_DIR}${NC}"
echo " CI must provision them before the leak-check leg:"
echo " cmake -S . -B build-asan -DBLANG_SANITIZE=address,undefined"
echo " cmake --build build-asan --parallel"
exit 1
fi
echo -e "${YELLOW}--leak-check WARNING: ASan-instrumented archives absent at ${ASAN_BUILD_DIR}; using plain archives (UAF reads inside runtime code will NOT be trapped). Build build-asan for full coverage.${NC}"
fi
if [ "$VALGRIND" -eq 1 ]; then
if ! command -v valgrind &>/dev/null; then
echo -e "${RED}Error: valgrind not found on PATH${NC}"
exit 1
fi
fi
if [ ! -x "$QCC" ]; then
echo -e "${RED}Error: qcc not found at $QCC${NC}"
echo "Build with: cd build && cmake .. -DLLVM_DIR=/usr/lib/llvm-18/lib/cmake/llvm && make"
exit 1
fi
QUARANTINE_FILE="${SCRIPT_DIR}/test_files/codegen_quarantine.txt"
# When set, run_one_test compares against this golden path instead of the default
# test_files/<name>.expected.out. Used only by --selfcheck (never in normal runs).
GOLDEN_OVERRIDE=""
# Strip exactly ONE trailing newline from a file's contents (the only permitted
# normalization, per design.md D2) and write the result to stdout with no added
# newline. Uses a sentinel so command substitution does not eat other newlines.
strip_one_trailing_nl() {
local content
content=$(cat "$1"; printf x)
content=${content%x}
content=${content%$'\n'}
printf '%s' "$content"
}
# Exact-match compare (after single-trailing-newline strip) of an actual-stdout
# file vs a golden file. Returns 0 on match, 1 on mismatch. No loose/substring/
# regex/whitespace matching — cmp on the normalized bytes.
golden_matches() {
local a="$1" g="$2" na ng rc
na="$(mktemp)"; ng="$(mktemp)"
strip_one_trailing_nl "$a" > "$na"
strip_one_trailing_nl "$g" > "$ng"
cmp -s "$na" "$ng"; rc=$?
rm -f "$na" "$ng"
return $rc
}
# Is a test (base name, e.g. codegen_http) quarantined from golden comparison?
# Reads codegen_quarantine.txt; '#' comments and blank lines ignored; entries may
# be listed with or without the .b extension.
is_quarantined() {
local name="$1" entry
[ -f "$QUARANTINE_FILE" ] || return 1
while IFS= read -r entry || [ -n "$entry" ]; do
entry="${entry%%#*}"
entry="$(printf '%s' "$entry" | tr -d '[:space:]')"
[ -z "$entry" ] && continue
if [ "$entry" = "$name" ] || [ "$entry" = "${name}.b" ]; then
return 0
fi
done < "$QUARANTINE_FILE"
return 1
}
# Leak quarantine (U4): a MINIMAL, review-gated list of tests with a KNOWN,
# tracked leak (see codegen_leak_quarantine.txt + Open Question OQ-1). A leak in
# a quarantined test is reported as KNOWN-LEAK and does NOT make --leak-check
# fatal; a leak in ANY OTHER test is fatal (teeth against new/injected leaks).
LEAK_QUARANTINE_FILE="${SCRIPT_DIR}/test_files/codegen_leak_quarantine.txt"
is_leak_quarantined() {
local name="$1" entry
[ -f "$LEAK_QUARANTINE_FILE" ] || return 1
while IFS= read -r entry || [ -n "$entry" ]; do
entry="${entry%%#*}"
entry="$(printf '%s' "$entry" | tr -d '[:space:]')"
[ -z "$entry" ] && continue
if [ "$entry" = "$name" ] || [ "$entry" = "${name}.b" ]; then
return 0
fi
done < "$LEAK_QUARANTINE_FILE"
return 1
}
# Parked tests (feature-integration epic): origin/master feature codegen tests
# whose codegen has not yet been ported into local's CG*/Sema architecture.
# Listed in codegen_parked.txt (annotated by owning unit U2-U6). A parked test
# is SKIPPED entirely — reported as PARKED, excluded from pass/fail/TOTAL — so
# the suite stays honestly green while the ports land one unit at a time. Each
# unit removes its own entries; U8 requires the file empty. '#'/blank ignored;
# entries may carry or omit the .b suffix.
PARKED_FILE="${SCRIPT_DIR}/test_files/codegen_parked.txt"
is_parked() {
local name="$1" entry
[ -f "$PARKED_FILE" ] || return 1
while IFS= read -r entry || [ -n "$entry" ]; do
entry="${entry%%#*}"
entry="$(printf '%s' "$entry" | tr -d '[:space:]')"
[ -z "$entry" ] && continue
if [ "$entry" = "$name" ] || [ "$entry" = "${name}.b" ]; then
return 0
fi
done < "$PARKED_FILE"
return 1
}
PASS_COUNT=0
FAIL_COUNT=0
LEAK_TOTAL=0
KNOWN_LEAK_TOTAL=0
SKIP_COUNT=0
PARKED_COUNT=0
TOTAL=0
GOLDEN_PASS_COUNT=0
NOGOLDEN_COUNT=0
QUARANTINE_COUNT=0
# Run one test through the full pipeline: qcc -> llc -> cc -> run
# Returns 0 on success, 1 on failure
run_one_test() {
local test_file="$1"
local show_ir="$2" # 1 to show IR, 0 to suppress
local base_name
base_name="$(basename "${test_file}" .b)"
local ir_file="/tmp/${base_name}.ll"
local obj_file="/tmp/${base_name}.o"
local bin_file="/tmp/${base_name}"
# Database tests need a SQLite-backed libblang_db. If the DB runtime was
# built without SQLite (stub), skip rather than fail — there is no backend
# to execute against.
local is_db_test=0
if [[ "${base_name}" == *"db"* ]] || [[ "${base_name}" == *"query"* ]]; then
is_db_test=1
if [ ! -f "${DB_LIB}" ] || ! nm "${DB_LIB}" 2>/dev/null | grep -q "U sqlite3_"; then
echo -e " ${YELLOW}SKIP${NC} ${test_file} (SQLite backend not built)"
SKIP_COUNT=$((SKIP_COUNT + 1))
return 0
fi
fi
TOTAL=$((TOTAL + 1))
# Step 1: Parse and generate IR
# Use --combine to include stdlib files (sys.b always, net.b for networking tests)
local qcc_args=()
local need_combine=0
local stdlib_files=()
if [ -f "${STDLIB_SYS}" ]; then
stdlib_files+=("${STDLIB_SYS}")
need_combine=1
fi
# Buffer is a fundamental type used by fs.b and net.b — always include it
if [ -f "${STDLIB_BUFFER}" ]; then
stdlib_files+=("${STDLIB_BUFFER}")
need_combine=1
fi
# net.b: filename patterns (historical) OR an explicit `import net;` in the
# test (content-gated, mirroring bcc's real stdlib resolution).
if [[ "${base_name}" == *"tcp"* ]] || [[ "${base_name}" == *"selector"* ]] || [[ "${base_name}" == *"net"* ]] || [[ "${base_name}" == *"sys_args"* ]] || [[ "${base_name}" == *"http"* ]] \
|| grep -qE '^[[:space:]]*import[[:space:]]+net[[:space:]]*;' "${test_file}" 2>/dev/null; then
if [ -f "${STDLIB_NET}" ]; then
stdlib_files+=("${STDLIB_NET}")
need_combine=1
fi
fi
if [[ "${base_name}" == *"file"* ]] || [[ "${base_name}" == *"fs"* ]]; then
if [ -f "${STDLIB_FS}" ]; then
stdlib_files+=("${STDLIB_FS}")
need_combine=1
fi
fi
if [[ "${base_name}" == *"timer"* ]] || [[ "${base_name}" == *"event"* ]]; then
if [ -f "${STDLIB_TIMER}" ]; then
stdlib_files+=("${STDLIB_TIMER}")
need_combine=1
fi
fi
# collections.b (Map/Set = PRELUDE types) is now LOADED UNCONDITIONALLY
# (modules-v2-graph U3, D13): prelude types are automatically in scope with zero
# imports, so the harness mirrors bcc's unconditional prelude load. qcc parses it
# into a prelude holding scope and PROMOTES only Map/Set (its free function `sort`
# stays qualified as collections.sort). A test that defines its OWN Map/Set with
# no import (codegen_map.b, codegen_arc_map_struct_value.b,
# codegen_ix_method_chain_field.b) is unaffected: its definition SHADOWS the
# prelude one (combineScope is a child of the prelude scope). collections.b must
# precede cli.b (cli.b uses Map).
if [ -f "${STDLIB_COLLECTIONS}" ]; then
stdlib_files+=("${STDLIB_COLLECTIONS}")
need_combine=1
fi
if grep -q '^[[:space:]]*import[[:space:]]\+cli[[:space:]]*;' "${test_file}" 2>/dev/null; then
if [ -f "${STDLIB_CLI}" ]; then
stdlib_files+=("${STDLIB_CLI}")
need_combine=1
fi
fi
# nsarc.b (U2, modules-v2-graph): the module-prefix string-ARC regression-lock
# module. Combined as a NAMESPACED module (kept out of every promotion list) so
# it gets a module prefix — the config the retired qcc.cpp:303-307 rationale
# claimed double-freed. Content-gated on `import nsarc;`. The `@nsarc__`-mangled
# internal callee is asserted below (need_nsarc) to guarantee the prefixed
# config, and the binary is exercised under --leak-check against the
# ASan-instrumented runtime.
local need_nsarc=0
if grep -qE '^[[:space:]]*import[[:space:]]+nsarc[[:space:]]*;' "${test_file}" 2>/dev/null; then
if [ -f "${SCRIPT_DIR}/test_files/nsarc.b" ]; then
stdlib_files+=("${SCRIPT_DIR}/test_files/nsarc.b")
need_combine=1
need_nsarc=1
fi
fi
# Native stdlib modules (U4): content-gated on `import <m>;`, mirroring bcc's
# kKnownOrder resolution — combined only when the test imports the module.
local _mod _modfile
for _mod in math time random env; do
eval "_modfile=\${STDLIB_${_mod^^}}"
if grep -q "^[[:space:]]*import[[:space:]]\+${_mod}[[:space:]]*;" "${test_file}" 2>/dev/null; then
if [ -f "${_modfile}" ]; then
stdlib_files+=("${_modfile}")
need_combine=1
fi
fi
done
if [ $need_combine -eq 1 ]; then
qcc_args+=("--combine" "${stdlib_files[@]}")
fi
if [ -n "${OPT_LEVEL}" ]; then
qcc_args+=("-O${OPT_LEVEL}") # layer 1: in-process IR passes
fi
if [ -n "${DEBUG_INFO}" ]; then
qcc_args+=("-g") # U3: emit DWARF debug info
fi
local qcc_output
qcc_output=$("${QCC}" "${qcc_args[@]}" "${test_file}" 2>&1)
local qcc_exit=$?
if [ $qcc_exit -ne 0 ]; then
echo -e " ${RED}FAIL${NC} ${test_file} (qcc failed, exit $qcc_exit)"
if [ "$VERBOSE" -eq 1 ]; then
echo "$qcc_output" | tail -5 | sed 's/^/ /'
fi
FAIL_COUNT=$((FAIL_COUNT + 1))
return 1
fi
# Find the generated .ll file
local src_ll
src_ll="$(dirname "${test_file}")/${base_name}.ll"
if [ -f "${src_ll}" ]; then
cp "${src_ll}" "${ir_file}"
elif [ -f "${base_name}.ll" ]; then
cp "${base_name}.ll" "${ir_file}"
fi
if [ ! -f "${ir_file}" ]; then
echo -e " ${RED}FAIL${NC} ${test_file} (no .ll file generated)"
FAIL_COUNT=$((FAIL_COUNT + 1))
return 1
fi
if [ "$show_ir" -eq 1 ]; then
echo "--- IR for ${base_name} ---"
cat "${ir_file}"
echo ""
fi
# U2 (modules-v2-graph) teeth: the nsarc regression-lock fixture MUST run the
# PREFIXED namespace config. If `@nsarc__`-mangled internal callees are absent,
# the module was taken through the promoted (prefix-free) path — the wrong
# config — and the test would pass vacuously. Fail loudly instead.
if [ "${need_nsarc:-0}" -eq 1 ]; then
if ! grep -q '@nsarc__' "${ir_file}"; then
echo -e " ${RED}FAIL${NC} ${test_file} (nsarc not module-prefixed — expected @nsarc__ callees in IR; wrong config for the string-ARC regression lock)"
FAIL_COUNT=$((FAIL_COUNT + 1))
return 1
fi
fi
# Step 2: Compile IR to object file
local llc_output
local llc_opt_flag=()
if [ -n "${LLC_OPT_LEVEL}" ]; then
llc_opt_flag=("-O${LLC_OPT_LEVEL}") # layer 2: backend codegen opt
fi
llc_output=$(llc-18 "${llc_opt_flag[@]}" -filetype=obj -relocation-model=pic "${ir_file}" -o "${obj_file}" 2>&1) || \
llc_output=$(llc "${llc_opt_flag[@]}" -filetype=obj -relocation-model=pic "${ir_file}" -o "${obj_file}" 2>&1)
if [ $? -ne 0 ]; then
echo -e " ${RED}FAIL${NC} ${test_file} (llc failed)"
if [ "$VERBOSE" -eq 1 ]; then
echo "$llc_output" | tail -5 | sed 's/^/ /'
fi
rm -f "${ir_file}"
FAIL_COUNT=$((FAIL_COUNT + 1))
return 1
fi
# Step 3: Link to native binary
local cc_output
local extra_libs=""
local sanitize_flags=""
# Detect libuv for async/await event loop support
if pkg-config --exists libuv 2>/dev/null; then
extra_libs="-luv"
fi
if [ "$LEAK_CHECK" -eq 1 ]; then
sanitize_flags="${LEAK_SANITIZE_FLAGS}"
fi
local json_link=""
if [ -f "${JSON_LIB}" ]; then
json_link="${JSON_LIB}"
fi
local string_link=""
if [ -f "${STRING_LIB}" ]; then
string_link="${STRING_LIB}"
fi
local array_link=""
if [ -f "${ARRAY_LIB}" ]; then
array_link="${ARRAY_LIB}"
fi
local buffer_link=""
if [ -f "${BUFFER_LIB}" ]; then
buffer_link="${BUFFER_LIB}"
fi
local net_link=""
if [ -f "${NET_LIB}" ]; then
net_link="${NET_LIB}"
fi
local fs_link=""
if [ -f "${FS_LIB}" ]; then
fs_link="${FS_LIB}"
fi
local sys_link=""
if [ -f "${SYS_LIB}" ]; then
sys_link="${SYS_LIB}"
fi
# Native stdlib modules (U4). Linked when present (before their string/array
# deps); the linker drops any that the test does not reference. -lm follows
# blang_math.a for GNU ld resolution of libm symbols.
local stdlib_native_link=""
[ -f "${MATH_LIB}" ] && stdlib_native_link="${stdlib_native_link} ${MATH_LIB}"
[ -f "${TIME_LIB}" ] && stdlib_native_link="${stdlib_native_link} ${TIME_LIB}"
[ -f "${RANDOM_LIB}" ] && stdlib_native_link="${stdlib_native_link} ${RANDOM_LIB}"
[ -f "${ENV_LIB}" ] && stdlib_native_link="${stdlib_native_link} ${ENV_LIB}"
[ -f "${HASH_LIB}" ] && stdlib_native_link="${stdlib_native_link} ${HASH_LIB}"
# Database tests link the DB runtime + its SQLite backend. By this point a
# db test is known to have a SQLite-enabled libblang_db (otherwise skipped
# above), so resolve the sqlite link flags, preferring pkg-config but
# falling back to a plain -lsqlite3 when pkg-config metadata is absent.
local db_link=""
local db_sys_flags=""
if [ "$is_db_test" -eq 1 ]; then
db_link="${DB_LIB}"
# Link whichever backends were compiled into libblang_db.a. The lib may
# reference sqlite3_* and/or PQ* depending on which dev packages CMake
# found; link the matching system libraries (pkg-config, else -l<name>).
local db_syms
db_syms="$(nm "${DB_LIB}" 2>/dev/null)"
if echo "$db_syms" | grep -q "U sqlite3_"; then
if pkg-config --exists sqlite3 2>/dev/null; then
db_sys_flags="${db_sys_flags} $(pkg-config --libs sqlite3)"
else
db_sys_flags="${db_sys_flags} -lsqlite3"
fi
fi
if echo "$db_syms" | grep -q "U PQ"; then
if pkg-config --exists libpq 2>/dev/null; then
db_sys_flags="${db_sys_flags} $(pkg-config --libs libpq)"
else
db_sys_flags="${db_sys_flags} -lpq"
fi
fi
fi
if [ -f "${RUNTIME_LIB}" ]; then
cc_output=$(cc ${sanitize_flags} "${obj_file}" "${RUNTIME_LIB}" ${db_link} ${sys_link} ${stdlib_native_link} ${fs_link} ${net_link} ${json_link} ${buffer_link} ${array_link} ${string_link} ${db_sys_flags} -lpthread -lm ${extra_libs} -o "${bin_file}" 2>&1)
else
cc_output=$(cc ${sanitize_flags} "${obj_file}" ${db_link} ${sys_link} ${stdlib_native_link} ${fs_link} ${net_link} ${json_link} ${buffer_link} ${array_link} ${string_link} ${db_sys_flags} -lm -o "${bin_file}" 2>&1)
fi
if [ $? -ne 0 ]; then
echo -e " ${RED}FAIL${NC} ${test_file} (link failed)"
# Always surface the linker error — link failures are environment-
# specific (missing system libs) and hard to diagnose without it.
echo "$cc_output" | tail -8 | sed 's/^/ /'
rm -f "${ir_file}" "${obj_file}"
FAIL_COUNT=$((FAIL_COUNT + 1))
return 1
fi
# Step 4: Run with timeout (catches hangs from missing runtime shutdown, etc.)
local run_output
local run_env=""
if [ "$LEAK_CHECK" -eq 1 ]; then
run_env="ASAN_OPTIONS=detect_leaks=1 LSAN_OPTIONS=exitcode=23"
else
# Poison freed memory in the plain build: glibc often leaves freed data
# intact, so a use-after-free read passes locally and crashes only on
# other allocators (how the Map UAF slipped through). PERTURB fills
# freed blocks; CHECK_=3 aborts on heap inconsistencies.
run_env="MALLOC_PERTURB_=42 MALLOC_CHECK_=3"
fi
# Database tests use an in-memory SQLite DB unless the test ships a blang.toml.
# (The binary is actually run below — in the VALGRIND branch or, for the
# normal/leak path, in the else branch that splits stdout/stderr for the
# golden compare — so we only seed run_env here, not run the binary.)
if [[ "${base_name}" == *"db"* ]] || [[ "${base_name}" == *"query"* ]]; then
run_env="${run_env} BLANG_DATABASE_URL=:memory: BLANG_DATABASE_DRIVER=sqlite"
fi
if [ "$VALGRIND" -eq 1 ]; then
run_output=$(timeout 30 valgrind --leak-check=full \
--error-exitcode=42 "${bin_file}" 2>&1)
local exit_code=$?
# Parse Valgrind summary
local definitely_lost
definitely_lost=$(echo "$run_output" | grep -oP 'definitely lost: \K[0-9,]+' | tr -d ',')
local indirectly_lost
indirectly_lost=$(echo "$run_output" | grep -oP 'indirectly lost: \K[0-9,]+' | tr -d ',')
local total_leaked=$(( ${definitely_lost:-0} + ${indirectly_lost:-0} ))
if [ $exit_code -eq 124 ]; then
echo -e " ${RED}FAIL${NC} ${test_file} (timeout — binary hung)"
FAIL_COUNT=$((FAIL_COUNT + 1))
rm -f "${ir_file}" "${obj_file}" "${bin_file}"
return 1
fi
# Valgrind exit code 42 = errors detected; other non-zero = program failure
if [ $exit_code -ne 0 ] && [ $exit_code -ne 42 ]; then
echo -e " ${RED}FAIL${NC} ${test_file} (runtime exit $exit_code)"
if [ "$VERBOSE" -eq 1 ]; then
echo "$run_output" | tail -10 | sed 's/^/ /'
fi
FAIL_COUNT=$((FAIL_COUNT + 1))
rm -f "${ir_file}" "${obj_file}" "${bin_file}"
return 1
fi
if [ "$total_leaked" -gt 0 ]; then
local leak_summary
leak_summary=$(echo "$run_output" | grep 'definitely lost:\|indirectly lost:' | head -2)
echo -e " ${YELLOW}LEAK${NC} ${test_file} (${definitely_lost:-0} direct + ${indirectly_lost:-0} indirect bytes)"
if [ "$VERBOSE" -eq 1 ]; then
echo "$run_output" | sed 's/^/ /'
fi
PASS_COUNT=$((PASS_COUNT + 1))
LEAK_TOTAL=$((LEAK_TOTAL + 1))
rm -f "${ir_file}" "${obj_file}" "${bin_file}"
return 0
fi
echo -e " ${GREEN}CLEAN${NC} ${test_file}"
PASS_COUNT=$((PASS_COUNT + 1))
else
# Capture stdout and stderr separately: the golden compares against
# stdout only (per REQ-001 / design.md), while stderr is retained for
# leak-mode parsing and verbose display.
local stdout_cap="/tmp/${base_name}.stdout.$$"
local stderr_cap="/tmp/${base_name}.stderr.$$"
timeout 10 env ${run_env} "${bin_file}" >"${stdout_cap}" 2>"${stderr_cap}"
local exit_code=$?
run_output="$(cat "${stdout_cap}" "${stderr_cap}" 2>/dev/null)"
# With leak check, LSan returns exit code 23 (forced via LSAN_OPTIONS=exitcode=23).
# U4: leaks are now FATAL. A leak in a leak-quarantined test (known, tracked
# ARC leak — see codegen_leak_quarantine.txt + OQ-1) is reported as
# KNOWN-LEAK and does NOT count toward the fatal LEAK_TOTAL; a leak in any
# other test increments LEAK_TOTAL, which forces a non-zero script exit.
if [ "$LEAK_CHECK" -eq 1 ] && [ $exit_code -eq 23 ]; then
local leak_summary
leak_summary=$(echo "$run_output" | grep 'SUMMARY:' | head -1)
if is_leak_quarantined "${base_name}"; then
echo -e " ${CYAN}KNOWN-LEAK${NC} ${test_file} ($leak_summary)"
KNOWN_LEAK_TOTAL=$((KNOWN_LEAK_TOTAL + 1))
else
echo -e " ${YELLOW}LEAK${NC} ${test_file} ($leak_summary)"
LEAK_TOTAL=$((LEAK_TOTAL + 1))
fi
if [ "$VERBOSE" -eq 1 ]; then
echo "$run_output" | grep -A1 'Direct leak\|Indirect leak' | sed 's/^/ /'
fi
PASS_COUNT=$((PASS_COUNT + 1))
rm -f "${ir_file}" "${obj_file}" "${bin_file}" "${stdout_cap}" "${stderr_cap}"
return 0
fi
if [ $exit_code -eq 124 ]; then
echo -e " ${RED}FAIL${NC} ${test_file} (timeout — binary hung)"
FAIL_COUNT=$((FAIL_COUNT + 1))
rm -f "${ir_file}" "${obj_file}" "${bin_file}" "${stdout_cap}" "${stderr_cap}"
return 1
elif [ $exit_code -ne 0 ]; then
echo -e " ${RED}FAIL${NC} ${test_file} (runtime exit $exit_code)"
if [ "$VERBOSE" -eq 1 ]; then
echo "$run_output" | tail -5 | sed 's/^/ /'
fi
FAIL_COUNT=$((FAIL_COUNT + 1))
rm -f "${ir_file}" "${obj_file}" "${bin_file}" "${stdout_cap}" "${stderr_cap}"
return 1
fi
# --- Exit code 0. ---
# In leak-check mode we do NOT golden-compare: output carries sanitizer
# noise and leak correctness (not stdout correctness) is the concern.
if [ "$LEAK_CHECK" -eq 1 ]; then
echo -e " ${GREEN}CLEAN${NC} ${test_file}"
PASS_COUNT=$((PASS_COUNT + 1))
rm -f "${ir_file}" "${obj_file}" "${bin_file}" "${stdout_cap}" "${stderr_cap}"
return 0
fi
# --- Golden-output verification (normal mode only) ---
# Quarantined tests: exit code already checked above; skip golden compare.
if is_quarantined "${base_name}"; then
echo -e " ${GREEN}PASS${NC} ${test_file} ${CYAN}(quarantined: exit-code only)${NC}"
QUARANTINE_COUNT=$((QUARANTINE_COUNT + 1))
PASS_COUNT=$((PASS_COUNT + 1))
rm -f "${ir_file}" "${obj_file}" "${bin_file}" "${stdout_cap}" "${stderr_cap}"
return 0
fi
local golden="${GOLDEN_OVERRIDE:-${SCRIPT_DIR}/test_files/${base_name}.expected.out}"
# --update-goldens: (re)write the golden from current stdout; do not compare.
# Never writes a golden for a quarantined test (handled above).
if [ "$UPDATE_GOLDENS" -eq 1 ]; then
cp "${stdout_cap}" "${SCRIPT_DIR}/test_files/${base_name}.expected.out"
echo -e " ${CYAN}WROTE${NC} ${test_file} (golden updated)"
PASS_COUNT=$((PASS_COUNT + 1))
rm -f "${ir_file}" "${obj_file}" "${bin_file}" "${stdout_cap}" "${stderr_cap}"
return 0
fi
# Missing golden: VISIBLE, non-fatal (still exit-code-checked). Never a
# silent golden pass — once a golden exists, wrong output is fatal below.
if [ ! -f "${golden}" ]; then
echo -e " ${YELLOW}NO GOLDEN${NC} ${test_file} (exit-code only; run --update-goldens to create)"
NOGOLDEN_COUNT=$((NOGOLDEN_COUNT + 1))
PASS_COUNT=$((PASS_COUNT + 1))
rm -f "${ir_file}" "${obj_file}" "${bin_file}" "${stdout_cap}" "${stderr_cap}"
return 0
fi
# Exact-match comparison; ONLY normalization is stripping one trailing newline.
if golden_matches "${stdout_cap}" "${golden}"; then
echo -e " ${GREEN}PASS${NC} ${test_file}"
GOLDEN_PASS_COUNT=$((GOLDEN_PASS_COUNT + 1))
PASS_COUNT=$((PASS_COUNT + 1))
rm -f "${ir_file}" "${obj_file}" "${bin_file}" "${stdout_cap}" "${stderr_cap}"
return 0
else
echo -e " ${RED}FAIL${NC} ${test_file} (stdout does not match golden)"
local na ng
na="$(mktemp)"; ng="$(mktemp)"
strip_one_trailing_nl "${golden}" > "${ng}"
strip_one_trailing_nl "${stdout_cap}" > "${na}"
echo " --- diff (- expected golden / + actual stdout) ---"
diff -u "${ng}" "${na}" 2>/dev/null | tail -n +3 | head -30 | sed 's/^/ /'
rm -f "${na}" "${ng}"
FAIL_COUNT=$((FAIL_COUNT + 1))
rm -f "${ir_file}" "${obj_file}" "${bin_file}" "${stdout_cap}" "${stderr_cap}"
return 1
fi
fi
# Cleanup (only the valgrind branch falls through to here; the normal branch
# returns explicitly above).
rm -f "${ir_file}" "${obj_file}" "${bin_file}"
return 0
}
# --selfcheck: prove the golden comparator has TEETH. Corrupt a real committed
# golden in a TEMP copy only, drive run_one_test with that corrupted golden, and
# assert the suite went red. The committed golden is never mutated. On success
# prints the literal line 'SELFCHECK: OK' and exits non-zero; if the comparator
# fails to detect the corruption (or mutates the committed file), a DISTINCT
# message is printed and 'SELFCHECK: OK' is NOT emitted.
run_selfcheck() {
echo "==========================================="
echo " Golden-comparison self-check (teeth proof)"
echo "==========================================="
local golden_file="" tb tf gf
for gf in $(ls "${SCRIPT_DIR}"/test_files/codegen_*.expected.out 2>/dev/null | sort); do
tb="$(basename "$gf" .expected.out)"
is_quarantined "$tb" && continue
if [ -f "${SCRIPT_DIR}/test_files/${tb}.b" ]; then
golden_file="$gf"; break
fi
done
if [ -z "$golden_file" ]; then
echo "SELFCHECK: FAILED — no committed non-quarantined golden found to corrupt"
exit 3
fi
tb="$(basename "$golden_file" .expected.out)"
tf="${SCRIPT_DIR}/test_files/${tb}.b"
echo " Using golden: test_files/${tb}.expected.out"
local before_sum after_sum
before_sum="$(sha256sum "$golden_file" | awk '{print $1}')"
# Phase A: the real golden must PASS (harness matches correct output).
PASS_COUNT=0; FAIL_COUNT=0; TOTAL=0; GOLDEN_OVERRIDE=""
run_one_test "$tf" 0 >/dev/null 2>&1
local real_ret=$?
# Phase B: corrupt a TEMP COPY; the comparison must go RED.
local tmp_golden
tmp_golden="$(mktemp)"
cat "$golden_file" > "$tmp_golden"
printf '\nSELFCHECK-CORRUPTION-%s\n' "$$" >> "$tmp_golden"
PASS_COUNT=0; FAIL_COUNT=0; TOTAL=0
GOLDEN_OVERRIDE="$tmp_golden"
run_one_test "$tf" 0 >/dev/null 2>&1
local corrupt_ret=$?
GOLDEN_OVERRIDE=""
rm -f "$tmp_golden"
after_sum="$(sha256sum "$golden_file" | awk '{print $1}')"
if [ "$before_sum" != "$after_sum" ]; then
echo "SELFCHECK: FAILED — committed golden was mutated during self-check"
exit 4
fi
if [ "$real_ret" -ne 0 ]; then
echo "SELFCHECK: FAILED — real golden did not match its own test (harness broken)"
exit 5
fi
if [ "$corrupt_ret" -eq 0 ]; then
echo "SELFCHECK: FAILED — comparator did NOT detect a corrupted golden (no teeth)"
exit 6
fi
echo " real golden -> PASS (matched)"
echo " corrupted golden -> FAIL (mismatch detected, suite went red)"
echo " committed golden -> unchanged (sha256 stable)"
echo "SELFCHECK: OK"
exit 1
}
if [ "$SELFCHECK" -eq 1 ]; then
run_selfcheck
fi
echo "==========================================="
echo " BLang Codegen E2E Test Suite"
echo "==========================================="
echo ""
if [ ${#FILE_ARGS[@]} -eq 1 ]; then
# Single-file mode: show IR by default
echo -e "${CYAN}--- Single test: ${FILE_ARGS[0]} ---${NC}"
run_one_test "${FILE_ARGS[0]}" 1
elif [ ${#FILE_ARGS[@]} -gt 1 ]; then
# Explicit file list
echo -e "${CYAN}--- Selected tests (${#FILE_ARGS[@]} files) ---${NC}"
for f in "${FILE_ARGS[@]}"; do
run_one_test "$f" "$VERBOSE"
done
else
# Multi-file mode: run all codegen_*.b tests
TEST_FILES=$(find "$SCRIPT_DIR/test_files" -maxdepth 1 -name 'codegen_*.b' 2>/dev/null | sort)
if [ -z "$TEST_FILES" ]; then
echo -e "${YELLOW}No codegen test files found in test_files/codegen_*.b${NC}"
exit 0
fi
echo -e "${CYAN}--- E2E codegen tests (parse → IR → compile → link → run) ---${NC}"
while IFS= read -r f; do
# Parked (feature-integration): origin feature tests whose codegen is
# not yet ported. Skip in the full-suite run so the suite stays green;
# an explicitly-named test (FILE_ARGS) still runs, so it can never be
# falsely green once its owning unit removes it from the parked list.
pk_base="$(basename "$f" .b)"
if is_parked "$pk_base"; then
echo -e " ${YELLOW}PARKED${NC} $f (codegen not yet ported — see codegen_parked.txt)"
PARKED_COUNT=$((PARKED_COUNT + 1))
continue
fi
run_one_test "$f" "$VERBOSE"
done <<< "$TEST_FILES"
fi
echo ""
echo "==========================================="
echo " Results"
echo "==========================================="
echo -e " ${GREEN}Passed:${NC} $PASS_COUNT"
echo -e " ${RED}Failed:${NC} $FAIL_COUNT"
if [ "$SKIP_COUNT" -gt 0 ]; then
echo -e " ${YELLOW}Skipped:${NC} $SKIP_COUNT"
fi
if [ "$PARKED_COUNT" -gt 0 ]; then
echo -e " ${YELLOW}Parked:${NC} $PARKED_COUNT ${CYAN}(feature-integration: origin tests pending port — see codegen_parked.txt)${NC}"
fi
if [ "$LEAK_CHECK" -eq 1 ]; then
echo -e " ${YELLOW}Leaks:${NC} $LEAK_TOTAL"
echo -e " ${CYAN}Known-leaks (quarantined):${NC} $KNOWN_LEAK_TOTAL"
fi
if [ "$LEAK_CHECK" -eq 0 ] && [ "$VALGRIND" -eq 0 ] && [ "$UPDATE_GOLDENS" -eq 0 ]; then
echo -e " ${CYAN}Golden-checked:${NC} $GOLDEN_PASS_COUNT ${YELLOW}No golden:${NC} $NOGOLDEN_COUNT ${CYAN}Quarantined:${NC} $QUARANTINE_COUNT"
fi
echo " Total: $TOTAL"
echo "==========================================="
if [ $FAIL_COUNT -gt 0 ]; then
exit 1
fi
# U4: an UNEXPECTED leak (not leak-quarantined) is fatal to --leak-check's exit.
if [ "$LEAK_CHECK" -eq 1 ] && [ "$LEAK_TOTAL" -gt 0 ]; then
exit 1
fi
exit 0