-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbcc.cpp
More file actions
1880 lines (1710 loc) · 56.4 KB
/
Copy pathbcc.cpp
File metadata and controls
1880 lines (1710 loc) · 56.4 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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// bcc - BLang Compiler Driver
//
// User-facing CLI that orchestrates the full compilation pipeline:
// 1. Parse + generate LLVM IR (via qcc)
// 2. Compile IR to object file (via llc)
// 3. Link to native binary (via cc)
//
// Usage:
// bcc source.b # compile and link -> a.out
// bcc source.b -o myprogram # compile and link -> myprogram
// bcc -S source.b # emit LLVM IR only -> source.ll
// bcc -c source.b # compile to object only -> source.o
// bcc -v source.b # verbose, show each pipeline step
// bcc test # discover and run test files
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <set>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <sys/wait.h>
#include "sha256.h"
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include "ProjectConfig.h"
#include "BuildCache.h"
#include "Type.h"
#include "Expression.h"
#include "SchemaMigration.h"
#include "runtime/blang_db.h"
using namespace std;
struct Options
{
string inputFile;
string outputFile;
bool emitIROnly = false; // -S
bool compileOnly = false; // -c
bool verbose = false; // -v
bool jsonDiagnostics = false;// --json (forwarded to qcc)
bool werror = false; // -Werror (forwarded to qcc)
string optLevel; // -O<n>: "" none, else 0..3/s/z (U2)
bool release = false; // --release: implies -O2 (U2)
string targetTriple; // --target <triple>: cross-compile (U2)
bool debugInfo = false; // -g: emit DWARF debug info; forces -O0 (U3)
vector<string> linkerFlags; // -l, -L, etc.
};
static void printUsage( const char *progName )
{
cerr << "Usage: " << progName << " [options] <source.b>" << endl;
cerr << " " << progName << " test [--verbose]" << endl;
cerr << endl;
cerr << "Subcommands:" << endl;
cerr << " build Build project from blang.toml" << endl;
cerr << " clean Remove build cache (~/.cache/blang/)" << endl;
cerr << " test Discover and run BLang test files" << endl;
cerr << " migrate Schema migration (--preview, --apply, --generate)" << endl;
cerr << endl;
cerr << "Options:" << endl;
cerr << " -o <file> Output file name" << endl;
cerr << " -S Emit LLVM IR only (.ll)" << endl;
cerr << " -c Compile to object file only (.o)" << endl;
cerr << " -v Verbose output" << endl;
cerr << " --json Emit compiler diagnostics as JSON" << endl;
cerr << " -Werror Treat warnings as errors" << endl;
cerr << " -O<n> Optimize (0..3, s, z); bare -O = -O2" << endl;
cerr << " --release Optimized build (implies -O2)" << endl;
cerr << " --target <t> Cross-compile to target triple (object emission)" << endl;
cerr << " -g Emit DWARF debug info (forces -O0)" << endl;
cerr << " -l<lib> Link with library" << endl;
cerr << " -L<dir> Add library search path" << endl;
cerr << " -h, --help Show this help" << endl;
}
static bool parseArgs( int argc, char *argv[], Options &opts )
{
for ( int i = 1; i < argc; i++ )
{
string arg = argv[i];
if ( arg == "-h" || arg == "--help" )
{
printUsage( argv[0] );
exit( 0 );
}
else if ( arg == "-o" )
{
if ( i + 1 >= argc )
{
cerr << "error: -o requires an argument" << endl;
return false;
}
opts.outputFile = argv[++i];
}
else if ( arg == "-S" )
{
opts.emitIROnly = true;
}
else if ( arg == "-c" )
{
opts.compileOnly = true;
}
else if ( arg == "-v" )
{
opts.verbose = true;
}
else if ( arg == "--json" )
{
opts.jsonDiagnostics = true;
}
else if ( arg == "-Werror" )
{
opts.werror = true;
}
else if ( arg == "--release" )
{
opts.release = true;
}
else if ( arg == "--target" )
{
if ( i + 1 >= argc )
{
cerr << "error: --target requires a triple argument" << endl;
return false;
}
opts.targetTriple = argv[++i];
}
else if ( arg == "-O" )
{
opts.optLevel = "2"; // bare -O means -O2
}
else if ( arg.size() > 2 && arg.substr( 0, 2 ) == "-O" )
{
opts.optLevel = arg.substr( 2 ); // -O0/1/2/3/s/z
}
else if ( arg == "-g" )
{
opts.debugInfo = true; // DWARF debug info (U3)
}
else if ( arg.substr( 0, 2 ) == "-l" || arg.substr( 0, 2 ) == "-L" )
{
opts.linkerFlags.push_back( arg );
}
else if ( arg[0] == '-' )
{
cerr << "error: unknown option '" << arg << "'" << endl;
return false;
}
else
{
if ( !opts.inputFile.empty() )
{
cerr << "error: multiple input files not supported" << endl;
return false;
}
opts.inputFile = arg;
}
}
if ( opts.inputFile.empty() )
{
cerr << "error: no input file" << endl;
return false;
}
return true;
}
// Get the base name without extension
static string getBaseName( const string &path )
{
// Strip directory
size_t slash = path.rfind( '/' );
string name = ( slash != string::npos ) ? path.substr( slash + 1 ) : path;
// Strip extension
size_t dot = name.rfind( '.' );
if ( dot != string::npos )
name = name.substr( 0, dot );
return name;
}
// Get directory of file
static string getDirName( const string &path )
{
size_t slash = path.rfind( '/' );
if ( slash != string::npos )
return path.substr( 0, slash );
return ".";
}
// Get directory of the bcc executable itself
static string getExeDir( const char *argv0 )
{
// Try /proc/self/exe first (Linux)
char buf[4096];
ssize_t len = readlink( "/proc/self/exe", buf, sizeof( buf ) - 1 );
if ( len > 0 )
{
buf[len] = '\0';
string exePath = buf;
size_t slash = exePath.rfind( '/' );
if ( slash != string::npos )
return exePath.substr( 0, slash );
}
// Fallback: assume qcc is in the same directory as bcc
string arg0 = argv0;
size_t slash = arg0.rfind( '/' );
if ( slash != string::npos )
return arg0.substr( 0, slash );
return ".";
}
// Run a command and return its exit code.
//
// Executed WITHOUT a shell: fork + execvp with the args passed as a literal
// argv vector, so no string is ever handed to /bin/sh. This is a security
// boundary — a dependency's git URL (or any other arg) cannot inject shell
// metacharacters. `git = "https://x/$(rm -rf ~)"` in a blang.toml is passed
// to git verbatim rather than evaluated, which the previous system() path
// (double-quote wrapping does not stop $()/backticks) did not prevent.
static int runCommand( const vector<string> &args, bool verbose, bool suppressOutput = false )
{
if ( args.empty() )
return -1;
if ( verbose )
{
for ( size_t i = 0; i < args.size(); i++ )
{
if ( i > 0 ) cerr << " ";
cerr << args[i];
}
cerr << endl;
}
pid_t pid = fork();
if ( pid < 0 )
{
cerr << "error: fork failed running '" << args[0] << "'" << endl;
return -1;
}
if ( pid == 0 )
{
// Child. Replicate the old shell redirect (>/dev/null
// 2>/tmp/bcc_stderr.txt) with dup2 so callers can still read captured
// stderr from the temp file on failure.
if ( suppressOutput && !verbose )
{
int devnull = open( "/dev/null", O_WRONLY );
if ( devnull >= 0 )
{
dup2( devnull, STDOUT_FILENO );
close( devnull );
}
int errfd = open( "/tmp/bcc_stderr.txt",
O_WRONLY | O_CREAT | O_TRUNC, 0600 );
if ( errfd >= 0 )
{
dup2( errfd, STDERR_FILENO );
close( errfd );
}
}
// execvp searches PATH for argv[0]; argv must be NULL-terminated. The
// const_cast is the standard idiom (execvp does not modify argv).
vector<char *> argv;
argv.reserve( args.size() + 1 );
for ( const auto &a : args )
argv.push_back( const_cast<char *>( a.c_str() ) );
argv.push_back( nullptr );
execvp( argv[0], argv.data() );
_exit( 127 ); // only reached if exec failed (matches shell's "not found")
}
// Parent.
int status = 0;
if ( waitpid( pid, &status, 0 ) < 0 )
return -1;
if ( WIFEXITED( status ) )
return WEXITSTATUS( status );
return -1;
}
// Find a tool, checking multiple possible names
static string findTool( const string &name, const vector<string> &alternatives )
{
// Check each candidate with 'which'
vector<string> candidates;
candidates.push_back( name );
for ( const auto &alt : alternatives )
candidates.push_back( alt );
for ( const auto &candidate : candidates )
{
string cmd = "which " + candidate + " >/dev/null 2>&1";
if ( system( cmd.c_str() ) == 0 )
return candidate;
}
return "";
}
// ---------------------------------------------------------------------------
// Pipeline foundation (epic 001-toolchain-and-stdlib, U0)
//
// The bcc→qcc→llc→cc pipeline used to duplicate the llc object-emission block
// 4x and the runtime-link library list 3x. These helpers are the single site
// for each. Later units extend the pipeline HERE, in one place:
// - U2 (-O / --target): emitObject() owns the llc flags + the host triple.
// - U3 (-g): emitObject() is the llc-side hook (the qcc-emit side is the qcc
// arg loop); debug metadata must survive the text-.ll boundary through here.
// - U4/U5 (new stdlib .a): appendRuntimeLibs() is the one place a lib is added.
// ---------------------------------------------------------------------------
// Resolve the llc tool once (build-time baked path, then PATH). Empty on failure.
static string resolveLlc()
{
string llc;
#ifdef BCC_LLC_PATH
if ( access( BCC_LLC_PATH, X_OK ) == 0 )
llc = BCC_LLC_PATH;
#endif
if ( llc.empty() )
llc = findTool( "llc-18", { "llc" } );
return llc;
}
// Emit a native object from a textual .ll via llc. Owns the -filetype=obj flag
// vector, the backend optimization level (U2 layer 2), and the target triple.
// Returns llc's exit code (0 == ok). Per-path error messages and IR-file cleanup
// stay at the call sites.
// optLevel — "" for none, else "0".."3"/"s"/"z" → llc -O<n>.
// targetTriple — "" for the host-baked triple (byte-identical to pre-U2), else
// the given triple (cross-compile, U2 --target).
// debugInfo — currently informational only: DWARF debug metadata carried in
// the textual .ll is emitted into the object by llc automatically
// (llc has no -g flag). qcc already forced -O0 when -g (S-A
// stance). Kept as a parameter so the single llc site owns the
// knob if a future backend needs an explicit flag.
static int emitObject( const string &llc, const string &llFile,
const string &objFile, bool verbose,
const string &optLevel = "",
const string &targetTriple = "",
bool debugInfo = false )
{
(void)debugInfo;
vector<string> cmd = { llc, "-filetype=obj", "--relocation-model=pic" };
if ( !optLevel.empty() )
{
// llc's -O accepts only numeric 0..3. The size levels (-Os/-Oz) are
// applied as IR passes in qcc (layer 1); map them to backend -O2 here so
// llc gets a valid level.
string llcOpt = ( optLevel == "s" || optLevel == "z" ) ? "2" : optLevel;
cmd.push_back( string( "-O" ) + llcOpt );
}
if ( !targetTriple.empty() )
{
cmd.push_back( string( "-mtriple=" ) + targetTriple );
}
else
{
#if defined(BCC_HOST_ARCH)
#if defined(PLATFORM_DARWIN)
cmd.push_back( string( "-mtriple=" ) + BCC_HOST_ARCH + "-apple-darwin" );
#elif defined(PLATFORM_LINUX)
cmd.push_back( string( "-mtriple=" ) + BCC_HOST_ARCH + "-unknown-linux-gnu" );
#endif
#endif
}
cmd.push_back( llFile );
cmd.push_back( "-o" );
cmd.push_back( objFile );
return runCommand( cmd, verbose );
}
// Which runtime libs a link line needs. The `bcc test` path links the test
// driver and omits the db lib; program builds (single-file + combined) link the
// db lib and omit the test driver.
struct RuntimeLinkProfile
{
bool withTestRunner;
bool withDb;
};
// Append the ordered libblang_*.a list to a link command (dependents before
// dependencies). THIS IS THE ONE PLACE a new stdlib .a is added (U4/U5). Only
// the libblang_*.a list is appended here; each path's tail (BCC_DB_LINKFLAGS,
// -lpthread, -o, user linker flags, -luv) stays at the call site so argument
// order is preserved byte-for-byte.
static void appendRuntimeLibs( vector<string> &cmd, const string &exeDir,
const RuntimeLinkProfile &profile )
{
auto findLib = [&]( const char *baked, const char *name ) -> string {
string lib;
if ( baked != nullptr )
lib = baked;
if ( lib.empty() || access( lib.c_str(), F_OK ) != 0 )
{
string fallback = exeDir + "/lib" + name + ".a";
if ( access( fallback.c_str(), F_OK ) == 0 )
lib = fallback;
else
lib.clear();
}
return lib;
};
const char *bakedTestRunner = nullptr, *bakedRuntime = nullptr, *bakedString = nullptr;
const char *bakedArray = nullptr, *bakedBuffer = nullptr, *bakedJson = nullptr;
const char *bakedNet = nullptr, *bakedFs = nullptr, *bakedSys = nullptr, *bakedDb = nullptr;
// Native stdlib modules (U4). Their .a's are offered to the linker
// unconditionally (like sys/fs/net) and dropped when unreferenced — import
// gating happens at the .b combine layer (kKnownOrder), not here.
const char *bakedMath = nullptr, *bakedTime = nullptr, *bakedRandom = nullptr, *bakedEnv = nullptr;
const char *bakedHash = nullptr; // U5: FNV-1a for hashed collections
#ifdef BCC_TESTRUNNER_LIB
bakedTestRunner = BCC_TESTRUNNER_LIB;
#endif
#ifdef BCC_RUNTIME_LIB
bakedRuntime = BCC_RUNTIME_LIB;
#endif
#ifdef BCC_STRING_LIB
bakedString = BCC_STRING_LIB;
#endif
#ifdef BCC_ARRAY_LIB
bakedArray = BCC_ARRAY_LIB;
#endif
#ifdef BCC_BUFFER_LIB
bakedBuffer = BCC_BUFFER_LIB;
#endif
#ifdef BCC_JSON_LIB
bakedJson = BCC_JSON_LIB;
#endif
#ifdef BCC_NET_LIB
bakedNet = BCC_NET_LIB;
#endif
#ifdef BCC_FS_LIB
bakedFs = BCC_FS_LIB;
#endif
#ifdef BCC_SYS_LIB
bakedSys = BCC_SYS_LIB;
#endif
#ifdef BCC_DB_LIB
bakedDb = BCC_DB_LIB;
#endif
#ifdef BCC_MATH_LIB
bakedMath = BCC_MATH_LIB;
#endif
#ifdef BCC_TIME_LIB
bakedTime = BCC_TIME_LIB;
#endif
#ifdef BCC_RANDOM_LIB
bakedRandom = BCC_RANDOM_LIB;
#endif
#ifdef BCC_ENV_LIB
bakedEnv = BCC_ENV_LIB;
#endif
#ifdef BCC_HASH_LIB
bakedHash = BCC_HASH_LIB;
#endif
// Leading lib (test driver or db), then the shared dependents->deps chain.
vector<string> libs;
if ( profile.withTestRunner )
libs.push_back( findLib( bakedTestRunner, "blang_testrunner" ) );
if ( profile.withDb )
libs.push_back( findLib( bakedDb, "blang_db" ) );
libs.push_back( findLib( bakedSys, "blang_sys" ) );
// Native stdlib modules (U4) — placed before their deps (string/array) so
// GNU ld resolves them; math's libm dep is added as a trailing -lm below.
libs.push_back( findLib( bakedMath, "blang_math" ) );
libs.push_back( findLib( bakedTime, "blang_time" ) );
libs.push_back( findLib( bakedRandom, "blang_random" ) );
libs.push_back( findLib( bakedEnv, "blang_env" ) );
// blang_hash (U5) is a leaf dep of the collections .b combine layer (only
// user code references it), so its position is order-tolerant; placed before
// its blang_string dep for GNU ld.
libs.push_back( findLib( bakedHash, "blang_hash" ) );
libs.push_back( findLib( bakedFs, "blang_fs" ) );
libs.push_back( findLib( bakedNet, "blang_net" ) );
libs.push_back( findLib( bakedJson, "blang_json" ) );
libs.push_back( findLib( bakedBuffer, "blang_buffer" ) );
libs.push_back( findLib( bakedArray, "blang_array" ) );
libs.push_back( findLib( bakedString, "blang_string" ) );
libs.push_back( findLib( bakedRuntime, "blang_runtime" ) );
for ( const auto &lib : libs )
{
if ( !lib.empty() )
cmd.push_back( lib );
}
// Math (U4) needs libm. Appended as a trailing system-linker token (not a
// findLib path) AFTER blang_math.a so GNU ld resolves math's sqrt/pow/etc.
// Harmless when math is unused (no libm symbol is referenced, so nothing is
// pulled in). System libm is always present.
cmd.push_back( "-lm" );
}
// Check whether a path is an existing directory
static bool isDirectory( const string &path )
{
struct stat st;
if ( stat( path.c_str(), &st ) != 0 )
return false;
return S_ISDIR( st.st_mode );
}
// Collect .b files by running find via popen
static vector<string> collectTestFiles( const string &searchRoot )
{
vector<string> files;
string cmd = "find \"" + searchRoot + "\" -name \"*.b\" 2>/dev/null";
FILE *fp = popen( cmd.c_str(), "r" );
if ( !fp )
return files;
char buf[4096];
while ( fgets( buf, sizeof( buf ), fp ) )
{
string line = buf;
// Strip trailing newline
while ( !line.empty() && ( line.back() == '\n' || line.back() == '\r' ) )
line.pop_back();
if ( !line.empty() )
files.push_back( line );
}
pclose( fp );
return files;
}
// Compile a single .b test file with the test-runner entry point and run it.
//
// Mirrors the normal bcc pipeline (qcc --combine <stdlib> <file>
// --emit-test-main -> llc -> cc) but links the fork-isolated test driver
// (libblang_testrunner.a). The produced binary registers each test{} block and
// dispatches to __blang_test_main, forwarding `--filter <name>` when set.
// Returns the test binary's exit code (non-zero iff a test failed), or a
// non-zero sentinel on a compile/link failure.
static set<string> parseImports( const string &path );
static vector<string> resolveStdlibFiles( const string &exeDir,
const set<string> &imports );
static int compileAndRunTestFile( const string &exeDir, const string &qcc,
const string &file, const string &filter, bool verbose )
{
string baseName = getBaseName( file );
string srcDir = getDirName( file );
// Collect stdlib .b files for --combine — the SAME resolution as the normal
// compile path (base modules always; env/cli/math/... gated on the file's
// imports), so a test file can exercise exactly what its program uses. The
// previous hand-rolled subset here (base + collections/timer only) made
// `bcc test` fail on files importing env/cli/etc. that `bcc build` accepts.
vector<string> stdlibFiles =
resolveStdlibFiles( exeDir, parseImports( file ) );
// Step 1: qcc --combine <stdlib...> <file> --emit-test-main
{
vector<string> cmd = { qcc, "--combine" };
for ( const auto &sf : stdlibFiles )
cmd.push_back( sf );
cmd.push_back( file );
cmd.push_back( "--emit-test-main" );
int ret = runCommand( cmd, verbose, !verbose );
if ( ret != 0 )
{
cerr << "bcc test: compilation failed for " << file << endl;
return 2;
}
}
// qcc (combine mode) writes IR derived from the last source file (the user
// file) as <file-with-.ll>.
string irFile = srcDir + "/" + baseName + ".ll";
if ( access( irFile.c_str(), F_OK ) != 0 )
{
cerr << "bcc test: no .ll generated for " << file
<< " (is qcc built with LLVM?)" << endl;
return 2;
}
// Step 2: llc -> object
string llc = resolveLlc();
if ( llc.empty() )
{
cerr << "bcc test: llc not found" << endl;
remove( irFile.c_str() );
return 2;
}
string objFile = "/tmp/" + baseName + "_bcctest.o";
{
int ret = emitObject( llc, irFile, objFile, verbose );
remove( irFile.c_str() );
if ( ret != 0 )
{
cerr << "bcc test: IR compilation failed for " << file << endl;
return 2;
}
}
// Step 3: link with the test driver + BLang runtime libs
string binFile = "/tmp/" + baseName + "_bcctest_bin";
{
string cc = "cc";
#ifdef BCC_CC_PATH
cc = BCC_CC_PATH;
#endif
vector<string> cmd = { cc };
#if defined(BCC_HOST_ARCH) && defined(PLATFORM_DARWIN)
cmd.push_back( "-arch" );
cmd.push_back( BCC_HOST_ARCH );
#endif
cmd.push_back( objFile );
// Test driver first (referenced by the emitted main), then the runtime
// libs; the test path links no db lib.
appendRuntimeLibs( cmd, exeDir,
RuntimeLinkProfile{ /*withTestRunner=*/true, /*withDb=*/false } );
cmd.push_back( "-lpthread" );
cmd.push_back( "-o" );
cmd.push_back( binFile );
#ifdef BCC_HAS_LIBUV
cmd.push_back( "-luv" );
#endif
int ret = runCommand( cmd, verbose );
remove( objFile.c_str() );
if ( ret != 0 )
{
cerr << "bcc test: linking failed for " << file << endl;
return 2;
}
}
// Step 4: run the test binary, forwarding --filter. Its stdout/stderr are
// inherited so per-test PASS/FAIL, located failures, and the summary appear.
int exitCode;
{
string runCmd = "\"" + binFile + "\"";
if ( !filter.empty() )
runCmd += " --filter \"" + filter + "\"";
int ret = system( runCmd.c_str() );
if ( WIFEXITED( ret ) )
exitCode = WEXITSTATUS( ret );
else
exitCode = 3; // crashed / signaled
}
remove( binFile.c_str() );
return exitCode;
}
// bcc test subcommand
//
// bcc test [--filter <name>] <file.b> [<file2.b> ...]
// Compile each file with the test-runner entry point and run its test{}
// blocks, reporting per-test PASS/FAIL with file:line on failure. Exit code
// is non-zero iff any test fails.
//
// bcc test [--filter <name>] (no file given)
// Legacy discovery: search tests/ (or the current directory) and run each
// discovered .b file the same way.
static int runTests( int argc, char *argv[], const string &exeDir )
{
bool verbose = false;
string filter;
vector<string> fileArgs;
for ( int i = 2; i < argc; i++ )
{
string arg = argv[i];
if ( arg == "--verbose" || arg == "-v" )
verbose = true;
else if ( arg == "--filter" && i + 1 < argc )
filter = argv[++i];
else if ( arg.rfind( "--filter=", 0 ) == 0 )
filter = arg.substr( 9 );
else if ( !arg.empty() && arg[0] != '-' )
fileArgs.push_back( arg );
}
string qcc = exeDir + "/qcc";
// Determine the set of files to run: explicit args, else discovery.
vector<string> files = fileArgs;
if ( files.empty() )
{
string searchRoot;
if ( isDirectory( "tests" ) )
{
searchRoot = "tests";
cerr << "bcc test: searching tests/ directory" << endl;
}
else
{
searchRoot = ".";
cerr << "bcc test: no tests/ directory found, searching current directory for *.b files" << endl;
}
files = collectTestFiles( searchRoot );
}
if ( files.empty() )
{
cerr << "bcc test: no .b files found" << endl;
return 0;
}
int worstExit = 0;
for ( const auto &file : files )
{
if ( files.size() > 1 )
cout << "=== " << file << " ===" << endl;
int rc = compileAndRunTestFile( exeDir, qcc, file, filter, verbose );
if ( rc != 0 )
worstExit = rc;
}
return worstExit;
}
// Forward declarations (defined later) so migrate can resolve stdlib imports
// the same way `bcc build` does.
static set<string> parseImports( const string &path );
static vector<string> resolveStdlibFiles( const string &exeDir,
const set<string> &imports );
// bcc migrate subcommand
//
// Compares current table struct definitions against stored schema snapshot
// and generates migration SQL.
//
// Usage:
// bcc migrate --preview Show what would change
// bcc migrate --apply Apply changes to the database
// bcc migrate --generate Generate migration SQL to stdout
static int runMigrate( int argc, char *argv[] )
{
string mode = "--preview"; // default
bool allowDestructive = false;
vector<string> sourceFiles;
for ( int i = 2; i < argc; i++ )
{
string arg = argv[i];
if ( arg == "--preview" || arg == "--apply" || arg == "--generate" )
mode = arg;
else if ( arg == "--allow-destructive" )
allowDestructive = true;
else if ( arg[0] != '-' )
sourceFiles.push_back( arg );
}
if ( sourceFiles.empty() )
{
// Try to find .b files in the current directory
vector<string> found = collectTestFiles( "." );
for ( const auto &f : found )
sourceFiles.push_back( f );
}
if ( sourceFiles.empty() )
{
cerr << "bcc migrate: no source files found" << endl;
return 1;
}
// 1. Obtain the current schema by parsing the sources with qcc and having
// it emit the table-struct schema as JSON (qcc owns the parser).
string exeDir = getExeDir( argv[0] );
string qcc = exeDir + "/qcc";
mkdir( ".blang", 0755 );
string storedSchemaPath = ".blang/schema.json";
string currentSchemaPath = ".blang/schema.current.json";
// Resolve stdlib imports so projects that `import net;` (etc.) parse — the
// table struct lives in a source file that references stdlib symbols, so the
// stdlib modules must be combined into the same parse, exactly as bcc build
// does. User sources go last (combine treats the last file as user scope).
set<string> imports;
for ( const auto &f : sourceFiles )
for ( const auto &imp : parseImports( f ) )
imports.insert( imp );
vector<string> stdlibFiles = resolveStdlibFiles( exeDir, imports );
vector<string> qccCmd = { qcc };
if ( !stdlibFiles.empty() )
qccCmd.push_back( "--combine" );
qccCmd.push_back( "--emit-schema" );
qccCmd.push_back( currentSchemaPath );
for ( const auto &sf : stdlibFiles )
qccCmd.push_back( sf );
for ( const auto &f : sourceFiles )
qccCmd.push_back( f );
if ( runCommand( qccCmd, false, true ) != 0 )
{
cerr << "bcc migrate: failed to extract schema from sources" << endl;
return 1;
}
// 2. Diff the stored snapshot against the current schema.
QLang::SchemaMigration mig;
mig.loadSchema( storedSchemaPath ); // stored (empty on first run)
mig.loadCurrentSchema( currentSchemaPath ); // current
vector<QLang::MigrationStep> steps = mig.computeDiff();
if ( mode == "--preview" )
{
cout << mig.preview();
remove( currentSchemaPath.c_str() );
return 0;
}
if ( mode == "--generate" )
{
cout << mig.generateSQL();
remove( currentSchemaPath.c_str() );
return 0;
}
// mode == "--apply"
if ( steps.empty() )
{
cout << "No schema changes to apply." << endl;
remove( currentSchemaPath.c_str() );
return 0;
}
// Destructive changes (DROP TABLE / DROP COLUMN) require explicit consent.
// The @drop annotation marks an intentional removal in source; since a
// removed entity no longer exists in source, apply additionally gates on
// the --allow-destructive flag as the CLI confirmation path.
if ( mig.hasDestructiveChanges() && !allowDestructive )
{
cerr << "bcc migrate: refusing to apply destructive changes without "
<< "--allow-destructive:" << endl;
for ( const auto &step : steps )
if ( step.isDestructive )
cerr << " [DESTRUCTIVE] " << step.description << endl;
remove( currentSchemaPath.c_str() );
return 1;
}
// Resolve the database connection from blang.toml [database] or the
// BLANG_DATABASE_URL environment variable.
string driver = "sqlite";
string url;
ProjectConfig *cfg = ProjectConfig::loadFromDirectory( "." );
if ( cfg != nullptr )
{
if ( !cfg->getDbDriver().empty() ) driver = cfg->getDbDriver();
url = cfg->getDbUrl();
delete cfg;
}
if ( url.empty() )
{
const char *envUrl = getenv( "BLANG_DATABASE_URL" );
if ( envUrl != nullptr )
url = envUrl;
}
if ( url.empty() )
{
cerr << "bcc migrate: no database url configured (set [database].url in "
<< "blang.toml or BLANG_DATABASE_URL)" << endl;
remove( currentSchemaPath.c_str() );
return 1;
}
const char *errMsg = nullptr;
BlangDBConn *conn = __blang_db_open(
__blang_db_driver_from_name( driver.c_str() ), url.c_str(), &errMsg );
if ( conn == nullptr )
{
cerr << "bcc migrate: cannot open database: "
<< ( errMsg ? errMsg : "unknown error" ) << endl;
remove( currentSchemaPath.c_str() );
return 1;
}
int applied = 0;
for ( const auto &step : steps )
{
const char *stepErr = nullptr;
if ( __blang_db_exec_raw( conn, step.sql.c_str(), &stepErr ) != 0 )
{
cerr << "bcc migrate: failed: " << step.description << endl;
cerr << " SQL: " << step.sql << endl;
cerr << " error: " << ( stepErr ? stepErr : "unknown" ) << endl;
__blang_db_close( conn );
remove( currentSchemaPath.c_str() );
return 1;
}
cout << "applied: " << step.description << endl;
applied++;
}
__blang_db_close( conn );
// Snapshot the now-current schema as the new stored baseline.
mig.saveSchema( storedSchemaPath );
remove( currentSchemaPath.c_str() );
cout << "Migration complete: " << applied << " step(s) applied." << endl;
return 0;
}
// Discover all .b files in a directory (non-recursive, project root only)
static vector<string> discoverSourceFiles( const string &dir )
{
vector<string> files;
DIR *d = opendir( dir.c_str() );
if ( !d )
return files;
struct dirent *entry;
while ( ( entry = readdir( d ) ) != nullptr )
{
string name = entry->d_name;
if ( name.size() > 2 && name.substr( name.size() - 2 ) == ".b" )
{
string path = dir;
if ( !path.empty() && path.back() != '/' )
path += '/';
path += name;
files.push_back( path );
}
}
closedir( d );
sort( files.begin(), files.end() );
return files;
}
// Read file content as string for cache key computation
static string readFileToString( const string &path )
{
ifstream f( path, ios::binary );
if ( !f.is_open() )
return "";
ostringstream ss;
ss << f.rdbuf();
return ss.str();
}
// Extract the set of imported module names from a BLang source file.
// Recognizes top-level `import name;` and `import name.sub;` statements,
// returning just the leading identifier ("name"). Comments and other tokens
// are ignored well enough for stdlib resolution.
static set<string> parseImports( const string &path )
{
set<string> imports;
string src = readFileToString( path );
istringstream in( src );
string line;
while ( getline( in, line ) )
{
// Strip a trailing line comment.
size_t cpos = line.find( "//" );
if ( cpos != string::npos )
line = line.substr( 0, cpos );
// Find the first non-space character.
size_t i = 0;
while ( i < line.size() && isspace( (unsigned char)line[i] ) )
i++;
if ( line.compare( i, 7, "import " ) != 0 )
continue;
i += 7;
while ( i < line.size() && isspace( (unsigned char)line[i] ) )
i++;
// Read the leading identifier of the module path.
size_t start = i;
while ( i < line.size() &&
( isalnum( (unsigned char)line[i] ) || line[i] == '_' ) )
i++;
if ( i > start )
imports.insert( line.substr( start, i - start ) );
}
return imports;
}
// Given the user's imports, return the stdlib `.b` files to combine, in a
// dependency-safe order. Only modules the program actually imports are pulled