-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathb.rs
More file actions
1414 lines (1245 loc) · 55 KB
/
Copy pathb.rs
File metadata and controls
1414 lines (1245 loc) · 55 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
//! # The B compiler
//!
//! ## Logging
//!
//! Right now there are 3 mechanisms to log anything in the compiler:
//! 1. Just directly output anything to stdout/stderr with (f)printf
//! 2. lexer::diagf()
//! 3. nob::log()
//!
//! Direct printf-ing is used primarily for printing help
//! messages. Flags like `-help`, `-t list`, etc.
//!
//! lexer::diagf() is used for reporting compiler diagnostics that
//! have a specific location within the source code the compiler is
//! analysing.
//!
//! nob::log() is used for reporting things that the compiler is doing
//! outside of direct analysis of the user's source code (like
//! creating files or calling external programs) that are potentially
//! affected by the -q flag.
#![no_main]
#![no_std]
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(unused_macros)]
#[macro_use]
pub mod nob;
#[macro_use]
pub mod flag;
#[macro_use]
pub mod crust;
pub mod arena;
pub mod codegen;
pub mod lexer;
pub mod targets;
pub mod params;
pub mod ir;
pub mod time;
pub mod shlex;
use core::ffi::*;
use core::mem::zeroed;
use core::ptr;
use core::slice;
use core::cmp;
use nob::*;
use flag::*;
use crust::libc::*;
use crust::assoc_lookup_cstr;
use arena::Arena;
use targets::*;
use lexer::{Lexer, Loc, Token};
use ir::*;
use time::Instant;
use shlex::*;
use params::*;
pub unsafe fn add_libb_files(path: *const c_char, target: *const c_char, inputs: &mut Array<*const c_char>, c: *mut Compiler) -> Option<bool> {
if !file_exists(path)? {
// why is rust like this.
return Some(false);
}
include_path_if_exists(inputs, arena::sprintf(&mut (*c).arena, c!("%s/all.b"), path));
include_path_if_exists(inputs, arena::sprintf(&mut (*c).arena, c!("%s/%s.b"), path, target));
Some(true)
}
pub unsafe fn expect_tokens(l: *mut Lexer, tokens: *const [Token]) -> Option<()> {
for i in 0..tokens.len() {
if (*tokens)[i] == (*l).token {
return Some(());
}
}
let mut sb: String_Builder = zeroed();
for i in 0..tokens.len() {
if i > 0 {
if i + 1 >= tokens.len() {
sb_appendf(&mut sb, c!(", or "));
} else {
sb_appendf(&mut sb, c!(", "));
}
}
sb_appendf(&mut sb, c!("%s"), lexer::display_token((*tokens)[i]));
}
da_append(&mut sb, 0);
diagf!((*l).loc, c!("ERROR: expected %s, but got %s\n"), sb.items, lexer::display_token((*l).token));
free(sb.items);
None
}
pub unsafe fn expect_token(l: *mut Lexer, token: Token) -> Option<()> {
expect_tokens(l, &[token])
}
pub unsafe fn get_and_expect_token(l: *mut Lexer, token: Token) -> Option<()> {
lexer::get_token(l)?;
expect_token(l, token)
}
pub unsafe fn get_and_expect_token_but_continue(l: *mut Lexer, c: *mut Compiler, token: Token) -> Option<()> {
let saved_point = (*l).parse_point;
lexer::get_token(l)?;
if expect_token(l, token).is_none() {
(*l).parse_point = saved_point;
bump_error_count(c)
} else {
Some(())
}
}
pub unsafe fn get_and_expect_tokens(l: *mut Lexer, clexes: *const [Token]) -> Option<()> {
lexer::get_token(l)?;
expect_tokens(l, clexes)
}
pub unsafe fn expect_token_id(l: *mut Lexer, id: *const c_char) -> Option<()> {
expect_token(l, Token::ID)?;
if strcmp((*l).string, id) != 0 {
diagf!((*l).loc, c!("ERROR: expected `%s`, but got `%s`\n"), id, (*l).string);
return None;
}
Some(())
}
pub unsafe fn get_and_expect_token_id(l: *mut Lexer, id: *const c_char) -> Option<()> {
lexer::get_token(l)?;
expect_token_id(l, id)
}
#[repr(C)]
#[derive(Clone, Copy)]
pub enum Storage {
External {name: *const c_char},
Auto {index: usize},
}
#[derive(Clone, Copy)]
pub struct Var {
pub name: *const c_char,
pub loc: Loc,
pub storage: Storage,
}
pub unsafe fn scope_push(vars: *mut Array<Array<Var>>) {
if (*vars).count < (*vars).capacity {
// Reusing already allocated scopes
(*vars).count += 1;
(*da_last_mut(vars).expect("There should be always at least the global scope")).count = 0;
} else {
da_append(vars, zeroed());
}
}
pub unsafe fn scope_pop(vars: *mut Array<Array<Var>>) {
assert!((*vars).count > 0);
(*vars).count -= 1;
}
pub unsafe fn find_var_near(vars: *const Array<Var>, name: *const c_char) -> *const Var {
for i in 0..(*vars).count {
let var = (*vars).items.add(i);
if strcmp((*var).name, name) == 0 {
return var
}
}
ptr::null()
}
pub unsafe fn find_var_deep(vars: *const Array<Array<Var>>, name: *const c_char) -> *const Var {
let mut i = (*vars).count;
while i > 0 {
let var = find_var_near((*vars).items.add(i-1), name);
if !var.is_null() {
return var;
}
i -= 1;
}
ptr::null()
}
pub unsafe fn declare_var(c: *mut Compiler, name: *const c_char, loc: Loc, storage: Storage) -> Option<()> {
let scope = da_last_mut(&mut (*c).vars).expect("There should be always at least the global scope");
let existing_var = find_var_near(scope, name);
if !existing_var.is_null() {
diagf!(loc, c!("ERROR: redefinition of variable `%s`\n"), name);
diagf!((*existing_var).loc, c!("NOTE: the first declaration is located here\n"));
return bump_error_count(c);
}
if let Storage::Auto {index} = storage {
da_append(&mut (*c).func_scope_events, ScopeEvent::Declare {name, index});
}
da_append(scope, Var {name, loc, storage});
Some(())
}
#[derive(Clone, Copy)]
pub struct GotoLabel {
name: *const c_char,
loc: Loc,
label: usize,
}
#[derive(Clone, Copy)]
pub struct Goto {
name: *const c_char,
loc: Loc,
addr: usize,
}
pub unsafe fn find_goto_label(labels: *const Array<GotoLabel>, name: *const c_char) -> *const GotoLabel {
for i in 0..(*labels).count {
let label = (*labels).items.add(i);
if strcmp((*label).name, name) == 0 {
return label
}
}
ptr::null()
}
pub unsafe fn define_goto_label(c: *mut Compiler, name: *const c_char, loc: Loc, label: usize) -> Option<()> {
let existing_label = find_goto_label(&(*c).func_goto_labels, name);
if !existing_label.is_null() {
diagf!(loc, c!("ERROR: duplicate label `%s`\n"), name);
diagf!((*existing_label).loc, c!("NOTE: the first definition is located here\n"));
return bump_error_count(c);
}
da_append(&mut (*c).func_goto_labels, GotoLabel {name, loc, label});
Some(())
}
// The higher the index of the row in this table the higher the precedence of the Binop
pub const PRECEDENCE: *const [*const [Binop]] = &[
&[Binop::BitOr],
&[Binop::BitAnd],
&[Binop::BitShl, Binop::BitShr],
&[Binop::Equal, Binop::NotEqual],
&[Binop::Less, Binop::Greater, Binop::GreaterEqual, Binop::LessEqual],
&[Binop::Plus, Binop::Minus],
&[Binop::Mult, Binop::Mod, Binop::Div],
];
impl Binop {
// The outer Option indicates success.
// The inner Option indicates whether the assign has binop associated with it.
// It's kinda confusing but I don't know how to make it "prettier"
pub fn from_assign_token(token: Token) -> Option<Option<Self>> {
match token {
Token::Eq => Some(None),
Token::PlusEq => Some(Some(Binop::Plus)),
Token::MinusEq => Some(Some(Binop::Minus)),
Token::MulEq => Some(Some(Binop::Mult)),
Token::DivEq => Some(Some(Binop::Div)),
Token::ModEq => Some(Some(Binop::Mod)),
Token::ShlEq => Some(Some(Binop::BitShl)),
Token::ShrEq => Some(Some(Binop::BitShr)),
Token::OrEq => Some(Some(Binop::BitOr)),
Token::AndEq => Some(Some(Binop::BitAnd)),
_ => None,
}
}
pub fn from_token(token: Token) -> Option<Self> {
match token {
Token::Plus => Some(Binop::Plus),
Token::Minus => Some(Binop::Minus),
Token::Mul => Some(Binop::Mult),
Token::Div => Some(Binop::Div),
Token::Mod => Some(Binop::Mod),
Token::EqEq => Some(Binop::Equal),
Token::NotEq => Some(Binop::NotEqual),
Token::Less => Some(Binop::Less),
Token::LessEq => Some(Binop::LessEqual),
Token::Greater => Some(Binop::Greater),
Token::GreaterEq => Some(Binop::GreaterEqual),
Token::Or => Some(Binop::BitOr),
Token::And => Some(Binop::BitAnd),
Token::Shl => Some(Binop::BitShl),
Token::Shr => Some(Binop::BitShr),
_ => None,
}
}
pub const MAX_PRECEDENCE: usize = PRECEDENCE.len();
pub unsafe fn precedence(self) -> usize {
for precedence in 0..PRECEDENCE.len() {
for i in 0..(*PRECEDENCE)[precedence].len() {
if self == (*(*PRECEDENCE)[precedence])[i] {
return precedence
}
}
}
unreachable!()
}
}
pub unsafe fn push_opcode(opcode: Op, loc: Loc, c: *mut Compiler) {
da_append(&mut (*c).func_body, OpWithLocation {opcode, loc, scope_events_count: (*c).func_scope_events.count });
}
/// Allocator of Auto Vars
#[derive(Clone, Copy)]
pub struct AutoVarsAtor {
/// How many autovars currently allocated
pub count: usize,
/// Maximum allocated autovars throughout the function body
pub max: usize,
}
pub unsafe fn allocate_label_index(c: *mut Compiler) -> usize {
let index = (*c).op_label_count;
(*c).op_label_count += 1;
index
}
pub unsafe fn allocate_auto_var(t: *mut AutoVarsAtor) -> usize {
(*t).count += 1;
if (*t).count > (*t).max {
(*t).max = (*t).count;
}
(*t).count
}
pub unsafe fn compile_string(string: *const c_char, c: *mut Compiler) -> usize {
let offset = (*c).program.data.count;
let string_len = strlen(string);
da_append_many(&mut (*c).program.data, slice::from_raw_parts(string as *const u8, string_len));
// TODO: Strings in B are not NULL-terminated.
// They are terminated with symbol '*e' ('*' is escape character akin to '\' in C) which according to the
// spec is called just "end-of-file" without any elaboration on what its value is. Maybe it had a specific
// value on PDP that was a common knowledge at the time? In any case that breaks compatibility with
// libc. While the language is still in development we gonna terminate it with 0. We will make it
// "spec complaint" later.
da_append(&mut (*c).program.data, 0); // NULL-terminator
offset
}
pub unsafe fn compile_primary_expression(l: *mut Lexer, c: *mut Compiler) -> Option<(Arg, bool)> {
lexer::get_token(l)?;
let arg = match (*l).token {
Token::OParen => {
let result = compile_expression(l, c)?;
get_and_expect_token_but_continue(l, c, Token::CParen)?;
Some(result)
}
Token::Not => {
let (arg, _) = compile_primary_expression(l, c)?;
let result = allocate_auto_var(&mut (*c).auto_vars_ator);
push_opcode(Op::UnaryNot{result, arg}, (*l).loc, c);
Some((Arg::AutoVar(result), false))
}
Token::Mul => {
let (arg, _) = compile_primary_expression(l, c)?;
let index = allocate_auto_var(&mut (*c).auto_vars_ator);
push_opcode(Op::AutoAssign {index, arg}, (*l).loc, c);
Some((Arg::Deref(index), true))
}
Token::Minus => {
let (arg, _) = compile_primary_expression(l, c)?;
if let Arg::Literal(v) = arg {
Some((Arg::Literal(!v + 1), false))
} else {
let index = allocate_auto_var(&mut (*c).auto_vars_ator);
push_opcode(Op::Negate {result: index, arg}, (*l).loc, c);
Some((Arg::AutoVar(index), false))
}
}
Token::And => {
let loc = (*l).loc;
let (arg, is_lvalue) = compile_primary_expression(l, c)?;
if !is_lvalue {
diagf!(loc, c!("ERROR: cannot take the address of an rvalue\n"));
return bump_error_count(c).map(|()| (Arg::Bogus, false));
}
match arg {
Arg::Deref(index) => Some((Arg::AutoVar(index), false)), // "&*x is identically x"
Arg::External(name) => Some((Arg::RefExternal(name), false)),
Arg::AutoVar(index) => Some((Arg::RefAutoVar(index), false)),
Arg::Bogus => Some((Arg::Bogus, false)), // Reference of a bogus value is a bogus value
Arg::Literal(_) | Arg::DataOffset(_) | Arg::RefAutoVar(_) | Arg::RefExternal(_) => unreachable!(),
}
}
Token::PlusPlus => {
let loc = (*l).loc;
let (arg, is_lvalue) = compile_primary_expression(l, c)?;
if !is_lvalue {
diagf!(loc, c!("ERROR: cannot increment an rvalue\n"));
return bump_error_count(c).map(|()| (Arg::Bogus, false));
}
compile_binop(arg, Arg::Literal(1), Binop::Plus, loc, c);
Some((arg, false))
}
Token::MinusMinus => {
let loc = (*l).loc;
let (arg, is_lvalue) = compile_primary_expression(l, c)?;
if !is_lvalue {
diagf!(loc, c!("ERROR: cannot decrement an rvalue\n"));
return bump_error_count(c).map(|()| (Arg::Bogus, false));
}
compile_binop(arg, Arg::Literal(1), Binop::Minus, loc, c);
Some((arg, false))
}
Token::CharLit | Token::IntLit => Some((Arg::Literal((*l).int_number), false)),
Token::ID => {
let name = arena::strdup(&mut (*c).arena, (*l).string);
let var_def = find_var_deep(&mut (*c).vars, name);
if var_def.is_null() {
da_append(&mut (*c).used_funcs, UsedFunc {name, loc: (*l).loc});
Some((Arg::External(name), true))
} else {
match (*var_def).storage {
Storage::Auto{index} => Some((Arg::AutoVar(index), true)),
Storage::External{name} => Some((Arg::External(name), true)),
}
}
}
Token::String => {
let offset = compile_string((*l).string, c);
Some((Arg::DataOffset(offset), false))
}
_ => {
diagf!((*l).loc, c!("Expected start of a primary expression but got %s\n"), lexer::display_token((*l).token));
None
}
};
let (mut arg, mut is_lvalue) = arg?;
loop {
let saved_point = (*l).parse_point;
lexer::get_token(l)?;
(arg, is_lvalue) = match (*l).token {
Token::OParen => Some((compile_function_call(l, c, arg)?, false)),
Token::OBracket => {
let (offset, _) = compile_expression(l, c)?;
get_and_expect_token_but_continue(l, c, Token::CBracket)?;
let result = allocate_auto_var(&mut (*c).auto_vars_ator);
push_opcode(Op::Index {result, arg, offset}, (*l).loc, c);
Some((Arg::Deref(result), true))
}
Token::PlusPlus => {
let loc = (*l).loc;
if !is_lvalue {
diagf!(loc, c!("ERROR: cannot increment an rvalue\n"));
return bump_error_count(c).map(|()| (Arg::Bogus, false));
}
let pre = allocate_auto_var(&mut (*c).auto_vars_ator);
push_opcode(Op::AutoAssign {index: pre, arg}, loc, c);
compile_binop(arg, Arg::Literal(1), Binop::Plus, loc, c);
Some((Arg::AutoVar(pre), false))
}
Token::MinusMinus => {
let loc = (*l).loc;
if !is_lvalue {
diagf!(loc, c!("ERROR: cannot decrement an rvalue\n"));
return bump_error_count(c).map(|()| (Arg::Bogus, false));
}
let pre = allocate_auto_var(&mut (*c).auto_vars_ator);
push_opcode(Op::AutoAssign {index: pre, arg}, loc, c);
compile_binop(arg, Arg::Literal(1), Binop::Minus, loc, c);
Some((Arg::AutoVar(pre), false))
}
_ => {
(*l).parse_point = saved_point;
return Some((arg, is_lvalue));
}
}?;
}
}
// TODO: communicate to the caller of this function that it expects `lhs` to be an lvalue
pub unsafe fn compile_binop(lhs: Arg, rhs: Arg, binop: Binop, loc: Loc, c: *mut Compiler) {
match lhs {
Arg::Deref(index) => {
let tmp = allocate_auto_var(&mut (*c).auto_vars_ator);
push_opcode(Op::Binop {binop, index: tmp, lhs, rhs}, loc, c);
push_opcode(Op::Store {index, arg: Arg::AutoVar(tmp)}, loc, c);
},
Arg::External(name) => {
let tmp = allocate_auto_var(&mut (*c).auto_vars_ator);
push_opcode(Op::Binop {binop, index: tmp, lhs, rhs}, loc, c);
push_opcode(Op::ExternalAssign {name, arg: Arg::AutoVar(tmp)}, loc, c)
}
Arg::AutoVar(index) => {
push_opcode(Op::Binop {binop, index, lhs, rhs}, loc, c)
}
Arg::Bogus => {
// Bogus value does not compile to anything
}
Arg::Literal(_) | Arg::DataOffset(_) | Arg::RefAutoVar(_) | Arg::RefExternal(_) => unreachable!(),
}
}
pub unsafe fn compile_binop_expression(l: *mut Lexer, c: *mut Compiler, precedence: usize) -> Option<(Arg, bool)> {
if precedence >= Binop::MAX_PRECEDENCE {
return compile_primary_expression(l, c);
}
let (mut lhs, mut lvalue) = compile_binop_expression(l, c, precedence + 1)?;
let mut saved_point = (*l).parse_point;
lexer::get_token(l)?;
if let Some(binop) = Binop::from_token((*l).token) {
if binop.precedence() == precedence {
while let Some(binop) = Binop::from_token((*l).token) {
if binop.precedence() != precedence { break; }
let (rhs, _) = compile_binop_expression(l, c, precedence + 1)?;
let index = allocate_auto_var(&mut (*c).auto_vars_ator);
push_opcode(Op::Binop {binop, index, lhs, rhs}, (*l).loc, c);
lhs = Arg::AutoVar(index);
lvalue = false;
saved_point = (*l).parse_point;
lexer::get_token(l)?;
}
}
}
(*l).parse_point = saved_point;
Some((lhs, lvalue))
}
pub unsafe fn compile_assign_expression(l: *mut Lexer, c: *mut Compiler) -> Option<(Arg, bool)> {
let (lhs, mut lvalue) = compile_binop_expression(l, c, 0)?;
let mut saved_point = (*l).parse_point;
lexer::get_token(l)?;
while let Some(binop) = Binop::from_assign_token((*l).token) {
let binop_loc = (*l).loc;
let (rhs, _) = compile_assign_expression(l, c)?;
if !lvalue {
diagf!(binop_loc, c!("ERROR: cannot assign to rvalue\n"));
return bump_error_count(c).map(|()| (Arg::Bogus, false));
}
if let Some(binop) = binop {
compile_binop(lhs, rhs, binop, binop_loc, c);
} else {
match lhs {
Arg::Deref(index) => {
push_opcode(Op::Store {index, arg: rhs}, binop_loc, c);
}
Arg::External(name) => {
push_opcode(Op::ExternalAssign {name, arg: rhs}, binop_loc, c);
}
Arg::AutoVar(index) => {
push_opcode(Op::AutoAssign {index, arg: rhs}, binop_loc, c);
}
Arg::Bogus => {
// Bogus value does not compile to anything
}
Arg::Literal(_) | Arg::DataOffset(_) | Arg::RefAutoVar(_) | Arg::RefExternal(_) => unreachable!(),
}
}
lvalue = false;
saved_point = (*l).parse_point;
lexer::get_token(l)?;
}
if (*l).token == Token::Question {
let result = allocate_auto_var(&mut (*c).auto_vars_ator);
let else_label = allocate_label_index(c);
push_opcode(Op::JmpIfNotLabel{label: else_label, arg: lhs}, (*l).loc, c);
let (if_true, _) = compile_expression(l, c)?;
push_opcode(Op::AutoAssign {index: result, arg: if_true}, (*l).loc, c);
let out_label = allocate_label_index(c);
push_opcode(Op::JmpLabel{label: out_label}, (*l).loc, c);
get_and_expect_token_but_continue(l, c, Token::Colon)?;
push_opcode(Op::Label{label: else_label}, (*l).loc, c);
let (if_false, _) = compile_expression(l, c)?;
push_opcode(Op::AutoAssign {index: result, arg: if_false}, (*l).loc, c);
push_opcode(Op::Label{label: out_label}, (*l).loc, c);
Some((Arg::AutoVar(result), false))
} else {
(*l).parse_point = saved_point;
Some((lhs, lvalue))
}
}
pub unsafe fn compile_expression(l: *mut Lexer, c: *mut Compiler) -> Option<(Arg, bool)> {
compile_assign_expression(l, c)
}
pub unsafe fn compile_block(l: *mut Lexer, c: *mut Compiler) -> Option<()> {
let index = (*c).func_blocks_count;
(*c).func_blocks_count += 1;
da_append(&mut (*c).func_scope_events, ScopeEvent::BlockBegin {index});
loop {
let saved_point = (*l).parse_point;
lexer::get_token(l)?;
if (*l).token == Token::CCurly { break }
(*l).parse_point = saved_point;
compile_statement(l, c)?
}
da_append(&mut (*c).func_scope_events, ScopeEvent::BlockEnd {index});
Some(())
}
unsafe fn compile_function_call(l: *mut Lexer, c: *mut Compiler, fun: Arg) -> Option<Arg> {
let mut args: Array<Arg> = zeroed();
let saved_point = (*l).parse_point;
lexer::get_token(l)?;
if (*l).token != Token::CParen {
(*l).parse_point = saved_point;
loop {
let (expr, _) = compile_expression(l, c)?;
da_append(&mut args, expr);
get_and_expect_tokens(l, &[Token::CParen, Token::Comma])?;
match (*l).token {
Token::CParen => break,
Token::Comma => continue,
_ => unreachable!(),
}
}
}
let result = allocate_auto_var(&mut (*c).auto_vars_ator);
push_opcode(Op::Funcall {result, fun, args}, (*l).loc, c);
Some(Arg::AutoVar(result))
}
pub unsafe fn name_declare_if_not_exists(names: *mut Array<*const c_char>, name: *const c_char) {
for i in 0..(*names).count {
if strcmp(*(*names).items.add(i), name) == 0 {
return;
}
}
da_append(names, name)
}
pub unsafe fn compile_asm_stmts(l: *mut Lexer, c: *mut Compiler, stmts: *mut Array<AsmStmt>) -> Option<()> {
get_and_expect_token_but_continue(l, c, Token::OParen)?;
let saved_point = (*l).parse_point;
lexer::get_token(l)?;
if (*l).token != Token::CParen {
(*l).parse_point = saved_point;
loop {
get_and_expect_token(l, Token::String)?;
match (*l).token {
Token::String => {
let line = arena::strdup(&mut (*c).arena, (*l).string);
let loc = (*l).loc;
da_append(stmts, AsmStmt { line, loc });
}
_ => unreachable!(),
}
get_and_expect_tokens(l, &[Token::Comma, Token::CParen])?;
match (*l).token {
Token::Comma => {}
Token::CParen => break,
_ => unreachable!(),
}
}
}
get_and_expect_token_but_continue(l, c, Token::SemiColon)?;
Some(())
}
pub unsafe fn compile_statement(l: *mut Lexer, c: *mut Compiler) -> Option<()> {
let saved_point = (*l).parse_point;
lexer::get_token(l)?;
match (*l).token {
Token::SemiColon => {
Some(())
},
Token::OCurly => {
scope_push(&mut (*c).vars);
let saved_auto_vars_count = (*c).auto_vars_ator.count;
compile_block(l, c)?;
(*c).auto_vars_ator.count = saved_auto_vars_count;
scope_pop(&mut (*c).vars);
Some(())
}
Token::Extrn => {
while (*l).token != Token::SemiColon {
get_and_expect_token(l, Token::ID)?;
let name = arena::strdup(&mut (*c).arena, (*l).string);
name_declare_if_not_exists(&mut (*c).program.extrns, name);
declare_var(c, name, (*l).loc, Storage::External {name})?;
get_and_expect_tokens(l, &[Token::SemiColon, Token::Comma])?;
}
compile_statement(l, c)
}
Token::Auto => {
while (*l).token != Token::SemiColon {
get_and_expect_token(l, Token::ID)?;
let name = arena::strdup(&mut (*c).arena, (*l).string);
let index = allocate_auto_var(&mut (*c).auto_vars_ator);
declare_var(c, name, (*l).loc, Storage::Auto {index})?;
get_and_expect_tokens(l, &[Token::SemiColon, Token::Comma, Token::IntLit, Token::CharLit])?;
if (*l).token == Token::IntLit || (*l).token == Token::CharLit {
let size = (*l).int_number as usize;
if size == 0 {
missingf!((*l).loc, c!("It's unclear how to compile automatic vector of size 0\n"));
}
for _ in 0..size {
allocate_auto_var(&mut (*c).auto_vars_ator);
}
// TODO: Here we assume the stack grows down. Should we
// instead find a way for the target to decide that?
// See TODO(2025-06-05 17:45:36)
let arg = Arg::RefAutoVar(index + size);
push_opcode(Op::AutoAssign {index, arg}, (*l).loc, c);
get_and_expect_tokens(l, &[Token::SemiColon, Token::Comma])?;
}
}
compile_statement(l, c)
}
Token::If => {
get_and_expect_token_but_continue(l, c, Token::OParen)?;
let saved_auto_vars_count = (*c).auto_vars_ator.count;
let (cond, _) = compile_expression(l, c)?;
let else_label = allocate_label_index(c);
push_opcode(Op::JmpIfNotLabel{label: else_label, arg: cond}, (*l).loc, c);
(*c).auto_vars_ator.count = saved_auto_vars_count;
get_and_expect_token_but_continue(l, c, Token::CParen)?;
compile_statement(l, c)?;
let saved_point = (*l).parse_point;
lexer::get_token(l)?;
if (*l).token == Token::Else {
let out_label = allocate_label_index(c);
push_opcode(Op::JmpLabel{label: out_label}, (*l).loc, c);
push_opcode(Op::Label{label: else_label}, (*l).loc, c);
compile_statement(l, c)?;
push_opcode(Op::Label{label: out_label}, (*l).loc, c);
} else {
(*l).parse_point = saved_point;
push_opcode(Op::Label{label: else_label}, (*l).loc, c);
}
Some(())
}
Token::While => {
let cond_label = allocate_label_index(c);
push_opcode(Op::Label {label: cond_label}, (*l).loc, c);
get_and_expect_token_but_continue(l, c, Token::OParen)?;
let saved_auto_vars_count = (*c).auto_vars_ator.count;
let (arg, _) = compile_expression(l, c)?;
(*c).auto_vars_ator.count = saved_auto_vars_count;
get_and_expect_token_but_continue(l, c, Token::CParen)?;
let out_label = allocate_label_index(c);
push_opcode(Op::JmpIfNotLabel{label: out_label, arg}, (*l).loc, c);
compile_statement(l, c)?;
push_opcode(Op::JmpLabel{label: cond_label}, (*l).loc, c);
push_opcode(Op::Label {label: out_label}, (*l).loc, c);
Some(())
}
Token::Return => {
get_and_expect_tokens(l, &[Token::SemiColon, Token::OParen])?;
if (*l).token == Token::SemiColon {
push_opcode(Op::Return {arg: None}, (*l).loc, c);
} else if (*l).token == Token::OParen {
let (arg, _) = compile_expression(l, c)?;
get_and_expect_token_but_continue(l, c, Token::CParen)?;
get_and_expect_token_but_continue(l, c, Token::SemiColon)?;
push_opcode(Op::Return {arg: Some(arg)}, (*l).loc, c);
} else {
unreachable!();
}
Some(())
}
Token::Goto => {
get_and_expect_token(l, Token::ID)?;
let name = arena::strdup(&mut (*c).arena, (*l).string);
let loc = (*l).loc;
let addr = (*c).func_body.count;
da_append(&mut (*c).func_gotos, Goto {name, loc, addr});
get_and_expect_token_but_continue(l, c, Token::SemiColon)?;
push_opcode(Op::Bogus, (*l).loc, c);
Some(())
}
Token::Asm => {
let loc = (*l).loc;
let mut stmts: Array<AsmStmt> = zeroed();
compile_asm_stmts(l, c, &mut stmts)?;
push_opcode(Op::Asm {stmts}, loc, c);
Some(())
}
Token::Case => {
let case_loc = (*l).loc;
lexer::get_token(l);
expect_tokens(l, &[Token::IntLit, Token::CharLit])?; // TODO: String ??!
let case_value = (*l).int_number;
get_and_expect_token_but_continue(l, c, Token::Colon)?;
if let Some(switch_frame) = da_last_mut(&mut (*c).switch_stack) {
let fallthrough_label = allocate_label_index(c);
push_opcode(Op::JmpLabel{label: fallthrough_label}, case_loc, c);
push_opcode(Op::Label{
label: (*switch_frame).label
}, case_loc, c);
push_opcode(Op::Binop{
binop: Binop::Equal,
index: (*switch_frame).cond,
lhs: (*switch_frame).value,
rhs: Arg::Literal(case_value)
}, case_loc, c);
let next_case_label = allocate_label_index(c);
push_opcode(Op::JmpIfNotLabel {
label: next_case_label,
arg: Arg::AutoVar((*switch_frame).cond)
}, case_loc, c);
(*switch_frame).label = next_case_label;
push_opcode(Op::Label{label: fallthrough_label}, case_loc, c);
Some(())
} else {
diagf!(case_loc, c!("ERROR: case label outside of switch\n"));
bump_error_count(c)
}
}
Token::Switch => {
let saved_auto_vars_count = (*c).auto_vars_ator.count;
let switch_loc = (*l).loc;
let (value, _) = compile_expression(l, c)?;
let cond = allocate_auto_var(&mut (*c).auto_vars_ator);
let label = allocate_label_index(c);
da_append(&mut (*c).switch_stack, Switch {label, value, cond});
push_opcode(Op::JmpLabel {label}, switch_loc, c);
compile_statement(l, c)?;
let switch_frame = da_last_mut(&mut (*c).switch_stack).expect("Switch stack was modified by somebody else");
push_opcode(Op::Label{label: (*switch_frame).label}, (*l).loc, c);
(*c).switch_stack.count -= 1;
(*c).auto_vars_ator.count = saved_auto_vars_count;
Some(())
}
_ => {
if (*l).token == Token::ID {
let name = arena::strdup(&mut (*c).arena, (*l).string);
let name_loc = (*l).loc;
lexer::get_token(l)?;
if (*l).token == Token::Colon {
let label = allocate_label_index(c);
push_opcode(Op::Label{label}, name_loc, c);
define_goto_label(c, name, name_loc, label)?;
return Some(());
}
}
(*l).parse_point = saved_point;
let saved_auto_vars_count = (*c).auto_vars_ator.count;
compile_expression(l, c)?;
(*c).auto_vars_ator.count = saved_auto_vars_count;
get_and_expect_token_but_continue(l, c, Token::SemiColon)?;
Some(())
}
}
}
pub unsafe fn usage() {
fprintf(stderr(), c!("B compiler\n"));
fprintf(stderr(), c!("Usage: %s [OPTIONS] <inputs...> [--] [run arguments]\n"), flag_program_name());
fprintf(stderr(), c!("OPTIONS:\n"));
flag_print_options(stderr());
}
#[derive(Clone, Copy)]
pub struct Switch {
pub label: usize,
pub value: Arg,
pub cond: usize,
}
#[derive(Clone, Copy)]
pub struct Compiler {
pub program: Program,
pub vars: Array<Array<Var>>,
pub auto_vars_ator: AutoVarsAtor,
pub func_body: Array<OpWithLocation>,
pub func_goto_labels: Array<GotoLabel>,
pub func_gotos: Array<Goto>,
pub func_scope_events: Array<ScopeEvent>,
pub func_blocks_count: usize,
pub used_funcs: Array<UsedFunc>,
pub op_label_count: usize,
pub switch_stack: Array<Switch>,
/// Arena into which the Compiler allocates all the names and
/// objects that need to live for the duration of the
/// compilation. Even if some object/names don't need to live that
/// long (for example, function labels need to live only for the
/// duration of that function compilation), just letting them live
/// longer makes the memory management easier.
///
/// Basically just dump everything into this arena and if you ever
/// need to reset the state of the Compiler, just reset all its
/// Dynamic Arrays and this Arena.
pub arena: Arena,
pub error_count: usize,
pub historical: bool,
}
#[derive(Clone, Copy)]
pub struct UsedFunc {
name: *const c_char,
loc: Loc,
}
pub const MAX_ERROR_COUNT: usize = 100;
/// The point of this function is to indicate that a compilation error happened, but continue the compilation anyway
/// even if the state of the Compiler became bogus. This is needed to report as many compilation errors as possible.
/// After calling this function always continue the compilation like nothing happened.
pub unsafe fn bump_error_count(c: *mut Compiler) -> Option<()> {
(*c).error_count += 1;
if (*c).error_count >= MAX_ERROR_COUNT {
fprintf(stderr(), c!("TOO MANY ERRORS! Fix your program!\n"));
return None
}
Some(())
}
pub unsafe fn compile_program(l: *mut Lexer, c: *mut Compiler) -> Option<()> {
'def: loop {
lexer::get_token(l)?;
match (*l).token {
Token::EOF => break 'def,
Token::Variadic => {
get_and_expect_token_but_continue(l, c, Token::OParen)?;
get_and_expect_token_but_continue(l, c, Token::ID)?;
let func = arena::strdup(&mut (*c).arena, (*l).string);
let func_loc = (*l).loc;
if let Some(existing_variadic) = assoc_lookup_cstr(da_slice((*c).program.variadics), func) {
// TODO: report all the duplicate variadics maybe?
diagf!(func_loc, c!("ERROR: duplicate variadic declaration `%s`\n"), func);
diagf!((*existing_variadic).loc, c!("NOTE: the first declaration is located here\n"));
bump_error_count(c)?;
}
get_and_expect_token_but_continue(l, c, Token::Comma)?;
get_and_expect_token_but_continue(l, c, Token::IntLit)?;
if (*l).int_number == 0 {
diagf!((*l).loc, c!("ERROR: variadic function `%s` cannot have 0 arguments\n"), func);
bump_error_count(c)?;
}
da_append(&mut (*c).program.variadics, (func, Variadic {
loc: func_loc,
fixed_args: (*l).int_number as usize,
}));
get_and_expect_token_but_continue(l, c, Token::CParen)?;
get_and_expect_token_but_continue(l, c, Token::SemiColon)?;
}
Token::Extrn => {
while (*l).token != Token::SemiColon {
get_and_expect_token(l, Token::ID)?;
let name = arena::strdup(&mut (*c).arena, (*l).string);
name_declare_if_not_exists(&mut (*c).program.extrns, name);
declare_var(c, name, (*l).loc, Storage::External {name})?;
get_and_expect_tokens(l, &[Token::SemiColon, Token::Comma])?;
}
}