This repository has been archived by the owner on Jun 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
mod.rs
1954 lines (1887 loc) · 73.9 KB
/
mod.rs
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
mod expr;
mod init;
mod stmt;
use std::collections::{HashSet, VecDeque};
use std::convert::TryInto;
use counter::Counter;
use crate::data::{error::Warning, hir::*, lex::Keyword, *};
use crate::intern::InternedStr;
use crate::parse::{Lexer, Parser};
use crate::RecursionGuard;
pub(crate) type TagScope = Scope<InternedStr, TagEntry>;
#[derive(Clone, Debug)]
pub(crate) enum TagEntry {
Struct(StructRef),
Union(StructRef),
// list of (name, value)s
Enum(Vec<(InternedStr, i64)>),
}
/// The driver for `PureAnalyzer`.
///
/// This implements `Iterator` and ensures that declarations and errors are returned in the correct error.
/// Use this if you want to compile an entire C program,
/// or if it is important to show errors in the correct order relative to declarations.
pub struct Analyzer<T: Lexer> {
declarations: Parser<T>,
pub inner: PureAnalyzer,
/// Whether to print each declaration as it is seen
pub debug: bool,
}
/// A `PureAnalyzer` turns AST types into HIR types.
///
/// In particular, it performs type checking and semantic analysis.
/// Use this if you need to analyze a specific AST data type without parsing a whole program.
// The struct is used mostly for holding scopes and error handler.
pub struct PureAnalyzer {
// in case a `Declaration` has multiple declarators
pending: VecDeque<Locatable<Declaration>>,
/// objects that are in scope
/// C actually has 4 different scopes:
/// 1. ordinary identifiers
/// 2. tags
/// 3. label names
/// 4. members
///
/// This holds the scope for ordinary identifiers: variables and typedefs
scope: Scope<InternedStr, Symbol>,
/// the compound types that have been declared (struct/union/enum)
/// scope 2. from above
tag_scope: TagScope,
/// Stores all variables that have been initialized so far
initialized: HashSet<Symbol>,
/// Internal API which makes it easier to return errors lazily
error_handler: ErrorHandler,
/// Internal API which prevents segfaults due to stack overflow
recursion_guard: RecursionGuard,
/// Hack to make compound assignment work
///
/// For `a += b`, `a` must only be evaluated once.
/// The way `assignment_expr` handles this is by desugaring to
/// `tmp = &a; *tmp = *tmp + b;`
/// However, the backend still has to see the declaration.
/// There's no way to return a statement from an expression,
/// so instead we store it in a side channel.
///
/// TODO: this should be a field on `FunctionAnalyzer`, not `Analyzer`
decl_side_channel: Vec<Locatable<Declaration>>,
}
impl<T: Lexer> Iterator for Analyzer<T> {
type Item = CompileResult<Locatable<Declaration>>;
fn next(&mut self) -> Option<Self::Item> {
loop {
// Instead of returning `SemanticResult`, the analyzer puts all errors into `error_handler`.
// This simplifies the logic in `next` greatly.
// NOTE: this returns errors for a declaration before the declaration itself
if let Some(err) = self.inner.error_handler.pop_front() {
return Some(Err(err));
// If we saw `int i, j, k;`, we treated those as different declarations
// `j, k` will be stored into `pending`
} else if let Some(decl) = self.inner.pending.pop_front() {
if self.debug {
println!("hir: {}", decl.data);
}
return Some(Ok(decl));
}
// Now do the real work.
let next = match self.declarations.next()? {
Err(err) => return Some(Err(err)),
Ok(decl) => decl,
};
let decls = self.inner.parse_external_declaration(next);
// TODO: if an error occurs, should we still add the declaration to `pending`?
self.inner.pending.extend(decls);
}
}
}
impl<I: Lexer> Analyzer<I> {
pub fn new(parser: Parser<I>, debug: bool) -> Self {
Self {
declarations: parser,
debug,
inner: PureAnalyzer::new(),
}
}
}
impl Default for PureAnalyzer {
fn default() -> Self {
Self::new()
}
}
impl PureAnalyzer {
pub fn new() -> Self {
Self {
error_handler: ErrorHandler::new(),
scope: Scope::new(),
tag_scope: Scope::new(),
pending: VecDeque::new(),
initialized: HashSet::new(),
recursion_guard: RecursionGuard::default(),
decl_side_channel: Vec::new(),
}
}
/// Return all warnings seen so far.
///
/// These warnings are consumed and will not be returned if you call
/// `warnings()` again.
pub fn warnings(&mut self) -> VecDeque<CompileWarning> {
std::mem::take(&mut self.error_handler.warnings)
}
// I type these a lot
#[inline(always)]
fn err(&mut self, e: SemanticError, l: Location) {
self.error_handler.error(e, l);
}
#[inline(always)]
fn warn(&mut self, w: Warning, l: Location) {
self.error_handler.warn(w, l);
}
fn recursion_check(&mut self) -> RecursionGuard {
self.recursion_guard
.recursion_check(&mut self.error_handler)
}
/// 6.9 External Definitions
///
/// Either a function or a list of declarations.
fn parse_external_declaration(
&mut self,
next: Locatable<ast::ExternalDeclaration>,
) -> Vec<Locatable<Declaration>> {
use ast::ExternalDeclaration;
match next.data {
ExternalDeclaration::Function(func) => {
let id = func.id;
let (meta_ref, body) = FunctionAnalyzer::analyze(func, self, next.location);
self.scope.insert(id, meta_ref);
let decl = Declaration {
symbol: meta_ref,
init: Some(Initializer::FunctionBody(body)),
};
vec![Locatable::new(decl, next.location)]
}
ExternalDeclaration::Declaration(declaration) => {
self.parse_declaration(declaration, next.location)
}
}
}
/// A list of declarations: `int i, j, k;`
fn parse_declaration(
&mut self,
declaration: ast::Declaration,
location: Location,
) -> Vec<Locatable<Declaration>> {
let original = self.parse_specifiers(declaration.specifiers, location);
if original.storage_class == Some(StorageClass::Auto) && self.scope.is_global() {
self.err(SemanticError::AutoAtGlobalScope, location);
}
// TODO: this is such a hack: https://github.com/jyn514/rcc/issues/371
let sc = original.storage_class.unwrap_or(StorageClass::Auto);
let mut decls = Vec::new();
for d in declaration.declarators {
let mut ctype =
self.parse_declarator(original.ctype.clone(), d.data.declarator.decl, d.location);
if !ctype.is_function() && original.qualifiers.func != FunctionQualifiers::default() {
self.err(
SemanticError::FuncQualifiersNotAllowed(original.qualifiers.func),
d.location,
);
}
let id = d.data.declarator.id;
let id = match id {
Some(i) => i,
// int i, ();
None => {
self.err("declarations cannot be abstract".into(), d.location);
"<error>".into()
}
};
// NOTE: the parser handles typedefs on its own
if ctype == Type::Void && sc != StorageClass::Typedef {
// TODO: catch this error for types besides void?
self.err(SemanticError::VoidType, location);
ctype = Type::Error;
}
let init = if let Some(init) = d.data.init {
Some(self.parse_initializer(init, &ctype, d.location))
} else {
None
};
let symbol = Variable {
ctype,
id,
qualifiers: original.qualifiers,
storage_class: sc,
};
let symbol = self.declare(symbol, init.is_some(), d.location);
if init.is_some() {
self.initialized.insert(symbol);
}
decls.push(Locatable::new(Declaration { symbol, init }, d.location));
}
// int;
if decls.is_empty() && !original.declared_compound_type {
self.warn(Warning::EmptyDeclaration, location);
}
decls
}
#[cfg(test)]
#[inline(always)]
// used only for testing, so that I can keep `parse_typename` private most of the time
pub(crate) fn parse_typename_test(&mut self, ctype: ast::TypeName, location: Location) -> Type {
self.parse_typename(ctype, location)
}
/// Perform checks for parsing a single type name.
///
/// Type names are used most often in casts: `(int)i`
/// This allows `int` or `int *` or `int (*)()`, but not `int i, j;` or `int i`
///
/// 6.7.7 Type names
fn parse_typename(&mut self, ctype: ast::TypeName, location: Location) -> Type {
let parsed = self.parse_type(ctype.specifiers, ctype.declarator.decl, location);
// TODO: should these be syntax errors instead?
// extern int
if let Some(sc) = parsed.storage_class {
self.err(SemanticError::IllegalStorageClass(sc), location);
}
// const int
if parsed.qualifiers != Qualifiers::default() {
self.warn(Warning::IgnoredQualifier(parsed.qualifiers), location);
}
// int i
if let Some(id) = ctype.declarator.id {
self.err(SemanticError::IdInTypeName(id), location);
}
parsed.ctype
}
/// Parse a single type, given the specifiers and declarator.
fn parse_type(
&mut self,
specifiers: Vec<ast::DeclarationSpecifier>,
declarator: ast::DeclaratorType,
location: Location,
) -> ParsedType {
let mut specs = self.parse_specifiers(specifiers, location);
specs.ctype = self.parse_declarator(specs.ctype, declarator, location);
if !specs.ctype.is_function() && specs.qualifiers.func != FunctionQualifiers::default() {
self.err(
SemanticError::FuncQualifiersNotAllowed(specs.qualifiers.func),
location,
);
}
specs
}
/// The specifiers for a declaration: `const extern long int`
///
/// Note that specifiers are also used for declaring structs, such as
/// ```c
/// struct s { int i; };
/// ```
/// Normally, we warn when a declaration is empty,
/// but if we declared a struct, union, or enum, then no warning is emitted.
/// This is kept track of by `declared_compound_type`.
fn parse_specifiers(
&mut self,
specifiers: Vec<ast::DeclarationSpecifier>,
location: Location,
) -> ParsedType {
use ast::{DeclarationSpecifier::*, UnitSpecifier::*};
// need to parse specifiers now
// it's not enough to collect into a `Set` since `long long` has a different meaning than `long`
// instead, we see how many times each specifier is present
// however, for some specifiers this doesn't really make sense:
// if we see `struct s { int i; }` twice in a row,
// it's more likely that the user forgot a semicolon in between than tried to make some weird double struct type.
// so: count the specifiers that are keywords and store the rest somewhere out of the way
// 6.7.2 Type specifiers
let (counter, compounds) = count_specifiers(specifiers, &mut self.error_handler, location);
// Now that we've separated this into unit specifiers and compound specifiers,
// see if we can pick up the proper types and qualifiers.
let signed = match (counter.get(&Signed), counter.get(&Unsigned)) {
// `int i` or `signed i`
(None, None) | (Some(_), None) => true,
// `unsigned i`
(None, Some(_)) => false,
// `unsigned signed i`
(Some(_), Some(_)) => {
self.err(SemanticError::ConflictingSigned, location);
true
}
};
// `long` is special because of `long long` and `long double`
let mut ctype = None;
if let Some(&long_count) = counter.get(&Long) {
match long_count {
0 => panic!("constraint violation, should only set count if > 0"),
1 => {
// NOTE: this is handled later by the big `for type in [...]` loop
// see notes there
if counter.get(&Double).is_none() {
ctype = Some(Type::Long(signed));
}
}
// TODO: implement `long long` as a separate type
2 => ctype = Some(Type::Long(signed)),
_ => {
self.err(SemanticError::TooLong(long_count), location);
ctype = Some(Type::Long(signed));
}
}
}
// 6.7.3 Type qualifiers
let qualifiers = Qualifiers {
c_const: counter.get(&Const).is_some(),
volatile: counter.get(&Volatile).is_some(),
func: FunctionQualifiers {
inline: counter.get(&Inline).is_some(),
no_return: counter.get(&NoReturn).is_some(),
},
};
// 6.7.1 Storage-class specifiers
let mut storage_class = None;
for (spec, sc) in &[
(Auto, StorageClass::Auto),
(Register, StorageClass::Register),
(Static, StorageClass::Static),
(Extern, StorageClass::Extern),
(UnitSpecifier::Typedef, StorageClass::Typedef),
] {
if counter.get(spec).is_some() {
if let Some(existing) = storage_class {
self.err(
SemanticError::ConflictingStorageClass(existing, *sc),
location,
);
}
storage_class = Some(*sc);
}
}
// back to type specifiers
// TODO: maybe use `iter!` macro instead of `vec!` to avoid an allocation?
// https://play.rust-lang.org/?gist=0535aa4f749a14cb1b28d658446f3c13
for (spec, new_ctype) in vec![
(Bool, Type::Bool),
(Char, Type::Char(signed)),
(Short, Type::Short(signed)),
// already handled `long` when we handled `long long`
(Float, Type::Float),
// NOTE: if we saw `long double` before, we'll set `ctype` to `double` now
// TODO: make `long double` different from `double`
(Double, Type::Double),
(Void, Type::Void),
(VaList, Type::VaList),
] {
if counter.get(&spec).is_some() {
match (spec, ctype) {
// `short int` and `long int` are valid, see 6.7.2
// `long` is handled earlier, so we don't have to worry
// about it here.
(_, None) | (Short, Some(Type::Int(_))) => {}
(_, Some(existing)) => {
self.err(
SemanticError::ConflictingType(existing, new_ctype.clone()),
location,
);
}
}
ctype = Some(new_ctype);
}
}
if counter.get(&Int).is_some() {
match ctype {
None => ctype = Some(Type::Int(signed)),
// `long int` is valid
Some(Type::Short(_)) | Some(Type::Long(_)) => {}
Some(existing) => {
self.err(
SemanticError::ConflictingType(existing, Type::Int(signed)),
location,
);
ctype = Some(Type::Int(signed));
}
}
}
let mut declared_compound_type = false;
for compound in compounds {
let parsed = match compound {
Unit(_) => unreachable!("already caught"),
DeclarationSpecifier::Typedef(name) => {
let meta = self
.scope
.get(&name)
.expect("scope of parser and analyzer should match")
.get();
assert_eq!(meta.storage_class, StorageClass::Typedef);
meta.ctype.clone()
}
Struct(s) => self.struct_specifier(s, true, &mut declared_compound_type, location),
Union(s) => self.struct_specifier(s, false, &mut declared_compound_type, location),
Enum { name, members } => {
self.enum_specifier(name, members, &mut declared_compound_type, location)
}
};
// TODO: this should report the name of the typedef, not the type itself
if let Some(existing) = &ctype {
self.err(
SemanticError::ConflictingType(existing.clone(), parsed.clone()),
location,
);
}
ctype = Some(parsed);
}
// Check to see if we had a conflicting `signed` specifier
// Note we use `counter` instead of the `signed` bool
// because we've already set the default and forgotten whether it was originally present.
if counter.get(&Signed).is_some() || counter.get(&Unsigned).is_some() {
match &ctype {
// unsigned int
Some(Type::Char(_)) | Some(Type::Short(_)) | Some(Type::Int(_))
| Some(Type::Long(_)) => {}
// unsigned float
Some(other) => {
let err = SemanticError::CannotBeSigned(other.clone());
self.err(err, location);
}
// unsigned i
None => ctype = Some(Type::Int(signed)),
}
}
// `i;` or `const i;`, etc.
let ctype = ctype.unwrap_or_else(|| {
self.warn(Warning::ImplicitInt, location);
Type::Int(true)
});
ParsedType {
qualifiers,
storage_class,
ctype,
declared_compound_type,
}
}
// 6.7.2.1 Structure and union specifiers
fn struct_specifier(
&mut self,
struct_spec: ast::StructSpecifier,
is_struct: bool,
declared_struct: &mut bool,
location: Location,
) -> Type {
let ast_members = match struct_spec.members {
// struct { int i; }
Some(members) => members,
// struct s
None => {
let name = if let Some(name) = struct_spec.name {
name
} else {
// struct;
let err = format!(
"bare '{}' as type specifier is not allowed",
if is_struct { "struct" } else { "union " }
);
self.error_handler.error(SemanticError::from(err), location);
return Type::Error;
};
let keyword = if is_struct {
Keyword::Struct
} else {
Keyword::Union
};
return match (is_struct, self.tag_scope.get(&name)) {
// `struct s *p;`
(_, None) => self.forward_declaration(keyword, name, location),
// `struct s; struct s;` or `struct s { int i; }; struct s`
(true, Some(TagEntry::Struct(s))) => Type::Struct(StructType::Named(name, *s)),
// `union s; union s;` or `union s { int i; }; union s`
(false, Some(TagEntry::Union(s))) => Type::Union(StructType::Named(name, *s)),
(_, Some(_)) => {
// `union s; struct s;`
if self.tag_scope.get_immediate(&name).is_some() {
let kind = if is_struct { "struct" } else { "union " };
// TODO: say what the previous declaration was
let err = SemanticError::from(format!("use of '{}' with type tag '{}' that does not match previous struct declaration", name, kind));
self.error_handler.push_back(Locatable::new(err, location));
Type::Error
} else {
// `union s; { struct s; }`
self.forward_declaration(keyword, name, location)
}
}
};
}
};
let members: Vec<_> = ast_members
.into_iter()
.map(|m| self.struct_declarator_list(m, location).into_iter())
.flatten()
.collect();
if members.is_empty() {
self.err(SemanticError::from("cannot have empty struct"), location);
return Type::Error;
}
let constructor = if is_struct { Type::Struct } else { Type::Union };
if let Some(id) = struct_spec.name {
let struct_ref = if let Some(TagEntry::Struct(struct_ref))
| Some(TagEntry::Union(struct_ref)) =
self.tag_scope.get_immediate(&id)
{
let struct_ref = *struct_ref;
// struct s { int i; }; struct s { int i; };
if !struct_ref.get().is_empty() {
self.err(
SemanticError::from(format!(
"redefinition of {} '{}'",
if is_struct { "struct" } else { "union" },
id
)),
location,
);
}
struct_ref
} else {
StructRef::new()
};
struct_ref.update(members);
let entry = if is_struct {
TagEntry::Struct
} else {
TagEntry::Union
}(struct_ref);
self.tag_scope.insert(id, entry);
*declared_struct = true;
constructor(StructType::Named(id, struct_ref))
} else {
// struct { int i; }
constructor(StructType::Anonymous(std::rc::Rc::new(members)))
}
}
/*
struct_declarator_list: struct_declarator (',' struct_declarator)* ;
struct_declarator
: declarator
| ':' constant_expr // bitfield, not supported
| declarator ':' constant_expr
;
*/
fn struct_declarator_list(
&mut self,
members: ast::StructDeclarationList,
location: Location,
) -> Vec<Variable> {
let parsed_type = self.parse_specifiers(members.specifiers, location);
if parsed_type.qualifiers.has_func_qualifiers() {
self.err(
SemanticError::FuncQualifiersNotAllowed(parsed_type.qualifiers.func),
location,
);
}
let mut parsed_members = Vec::new();
// A member of a structure or union may have any complete object type other than a variably modified type.
for ast::StructDeclarator { decl, bitfield } in members.declarators {
let decl = match decl {
// 12 A bit-field declaration with no declarator, but only a colon and a width, indicates an unnamed bit-field.
// TODO: this should give an error if `bitfield` is None.
None => continue,
Some(d) => d,
};
let ctype = match self.parse_declarator(parsed_type.ctype.clone(), decl.decl, location)
{
Type::Void => {
// TODO: catch this error for types besides void?
self.err(SemanticError::VoidType, location);
Type::Error
}
other => other,
};
let mut symbol = Variable {
storage_class: StorageClass::Auto,
qualifiers: parsed_type.qualifiers,
ctype,
id: decl.id.expect("struct members should have an id"),
};
// struct s { int i: 5 };
if let Some(bitfield) = bitfield {
let bit_size = match Self::const_uint(self.expr(bitfield)) {
Ok(e) => e,
Err(err) => {
self.error_handler.push_back(err);
1
}
};
let type_size = symbol.ctype.sizeof().unwrap_or(0);
if bit_size == 0 {
let err = SemanticError::from(format!(
"C does not have zero-sized types. hint: omit the declarator {}",
symbol.id
));
self.err(err, location);
// struct s { int i: 65 }
} else if bit_size > type_size * u64::from(crate::arch::CHAR_BIT) {
let err = SemanticError::from(format!(
"cannot have bitfield {} with size {} larger than containing type {}",
symbol.id, bit_size, symbol.ctype
));
self.err(err, location);
}
self.error_handler.warn(
"bitfields are not implemented and will be ignored",
location,
);
}
match symbol.ctype {
Type::Struct(StructType::Named(_, inner_members))
| Type::Union(StructType::Named(_, inner_members))
if inner_members.get().is_empty() =>
{
self.err(
SemanticError::from(format!(
"cannot use type '{}' before it has been defined",
symbol.ctype
)),
location,
);
// add this as a member anyway because
// later code depends on structs being non-empty
symbol.ctype = Type::Error;
}
_ => {}
}
parsed_members.push(symbol);
}
// struct s { extern int i; };
if let Some(class) = parsed_type.storage_class {
let member = parsed_members
.last()
.expect("should have seen at least one declaration");
self.err(
SemanticError::from(format!(
"cannot specify storage class '{}' for struct member '{}'",
class, member.id,
)),
location,
);
}
parsed_members
}
// 6.7.2.2 Enumeration specifiers
fn enum_specifier(
&mut self,
enum_name: Option<InternedStr>,
ast_members: Option<Vec<(InternedStr, Option<ast::Expr>)>>,
saw_enum: &mut bool,
location: Location,
) -> Type {
*saw_enum = true;
let ast_members = match ast_members {
Some(members) => members,
None => {
// enum e
let name = if let Some(name) = enum_name {
name
} else {
// enum;
let err = SemanticError::from("bare 'enum' as type specifier is not allowed");
self.error_handler.error(err, location);
return Type::Error;
};
match self.tag_scope.get(&name) {
// enum e { A }; enum e my_e;
Some(TagEntry::Enum(members)) => {
*saw_enum = false;
return Type::Enum(Some(name), members.clone());
}
// struct e; enum e my_e;
Some(_) => {
// TODO: say what the previous type was
let err = SemanticError::from(format!("use of '{}' with type tag 'enum' that does not match previous struct declaration", name));
self.error_handler.push_back(Locatable::new(err, location));
return Type::Error;
}
// `enum e;` (invalid)
None => return self.forward_declaration(Keyword::Enum, name, location),
}
}
};
let mut discriminant = 0;
let mut members = vec![];
for (name, maybe_value) in ast_members {
// enum E { A = 5 };
if let Some(value) = maybe_value {
discriminant = Self::const_sint(self.expr(value)).unwrap_or_else(|err| {
self.error_handler.push_back(err);
std::i64::MIN
});
}
members.push((name, discriminant));
// TODO: this is such a hack
let tmp_symbol = Variable {
id: name,
qualifiers: Qualifiers {
c_const: true,
..Default::default()
},
storage_class: StorageClass::Register,
ctype: Type::Enum(None, vec![(name, discriminant)]),
};
self.declare(tmp_symbol, false, location);
discriminant = discriminant.checked_add(1).unwrap_or_else(|| {
self.error_handler
.push_back(location.error(SemanticError::EnumOverflow));
0
});
}
for (name, _) in &members {
self.scope._remove(name);
}
// enum e {}
if members.is_empty() {
self.err(SemanticError::from("enums cannot be empty"), location)
}
if let Some(id) = enum_name {
// enum e { A }; enum e { A };
if self
.tag_scope
.insert(id, TagEntry::Enum(members.clone()))
.is_some()
{
self.err(format!("redefition of enum '{}'", id).into(), location);
}
}
let ctype = Type::Enum(enum_name, members);
match &ctype {
Type::Enum(_, members) => {
for &(id, _) in members {
self.scope.insert(
id,
Variable {
id,
storage_class: StorageClass::Register,
qualifiers: Qualifiers::NONE,
ctype: ctype.clone(),
}
.insert(),
);
}
}
_ => unreachable!(),
}
ctype
}
/// Used for forward declaration of structs and unions.
///
/// Does not correspond to any grammar type.
/// e.g. `struct s;`
///
/// See also 6.7.2.3 Tags:
/// > A declaration of the form `struct-or-union identifier ;`
/// > specifies a structure or union type and declares the identifier as a tag of that type.
/// > If a type specifier of the form `struct-or-union identifier`
/// > occurs other than as part of one of the above forms, and no other declaration of the identifier as a tag is visible,
/// > then it declares an incomplete structure or union type, and declares the identifier as the tag of that type.
fn forward_declaration(
&mut self,
kind: Keyword,
ident: InternedStr,
location: Location,
) -> Type {
if kind == Keyword::Enum {
// see section 6.7.2.3 of the C11 standard
self.err(
SemanticError::from(format!(
"cannot have forward reference to enum type '{}'",
ident
)),
location,
);
return Type::Enum(Some(ident), vec![]);
}
let struct_ref = StructRef::new();
let (entry_type, tag_type): (fn(_) -> _, fn(_) -> _) = if kind == Keyword::Struct {
(TagEntry::Struct, Type::Struct)
} else {
(TagEntry::Union, Type::Union)
};
let entry = entry_type(struct_ref);
self.tag_scope.insert(ident, entry);
tag_type(StructType::Named(ident, struct_ref))
}
/// Parse the declarator for a variable, given a starting type.
/// e.g. for `int *p`, takes `start: Type::Int(true)` and returns `Type::Pointer(Type::Int(true))`
///
/// The parser generated a linked list `DeclaratorType`,
/// which we now transform into the recursive `Type`.
///
/// 6.7.6 Declarators
fn parse_declarator(
&mut self,
current: Type,
decl: ast::DeclaratorType,
location: Location,
) -> Type {
use crate::data::ast::DeclaratorType::*;
use crate::data::types::{ArrayType, FunctionType};
let _guard = self.recursion_check();
match decl {
End => current,
Pointer { to, qualifiers } => {
use UnitSpecifier::*;
let inner = self.parse_declarator(current, *to, location);
// we reuse `count_specifiers` even though we really only want the qualifiers
let (counter, compounds) =
count_specifiers(qualifiers, &mut self.error_handler, location);
// *const volatile
// TODO: this shouldn't allow `inline` or `_Noreturn`
let qualifiers = Qualifiers {
c_const: counter.get(&Const).is_some(),
volatile: counter.get(&Volatile).is_some(),
func: FunctionQualifiers {
inline: counter.get(&Inline).is_some(),
no_return: counter.get(&NoReturn).is_some(),
},
};
for &q in counter.keys() {
if !q.is_qualifier() {
// *extern
self.err(SemanticError::NotAQualifier(q.into()), location);
}
}
for spec in compounds {
// *struct s {}
self.err(SemanticError::NotAQualifier(spec), location);
}
Type::Pointer(Box::new(inner), qualifiers)
}
Array { of, size } => {
// int a[5]
let size = if let Some(expr) = size {
let size = Self::const_uint(self.expr(*expr)).unwrap_or_else(|err| {
self.error_handler.push_back(err);
1
});
ArrayType::Fixed(size)
} else {
// int a[]
ArrayType::Unbounded
};
let of = self.parse_declarator(current, *of, location);
// int a[]()
if let Type::Function(_) = &of {
self.err(SemanticError::ArrayStoringFunction(of.clone()), location);
}
Type::Array(Box::new(of), size)
}
Function(func) => {
// TODO: give a warning for `const int f();` somewhere
let return_type = self.parse_declarator(current, *func.return_type, location);
match &return_type {
// int a()[]
Type::Array(_, _) => self.err(
SemanticError::IllegalReturnType(return_type.clone()),
location,
),
// int a()()
Type::Function(_) => self.err(
SemanticError::IllegalReturnType(return_type.clone()),
location,
),
_ => {}
}
let mut names = HashSet::new();
let mut params = Vec::new();
for param in func.params {
// TODO: this location should be that of the param, not of the function
let mut param_type =
self.parse_type(param.specifiers, param.declarator.decl, location);
// `int f(int a[])` -> `int f(int *a)`
if let Type::Array(to, _) = param_type.ctype {
param_type.ctype = Type::Pointer(to, Qualifiers::default());
}
// C11 Standard 6.7.6.3 paragraph 8
// "A declaration of a parameter as 'function returning type' shall be
// adjusted to 'pointer to function returning type', as in 6.3.2.1."
// `int f(int g())` -> `int f(int (*g)())`
if param_type.ctype.is_function() {
param_type.ctype =
Type::Pointer(Box::new(param_type.ctype), Qualifiers::default());
}
// int a(extern int i)
if let Some(sc) = param_type.storage_class {
self.err(SemanticError::ParameterStorageClass(sc), location);
}
let id = if let Some(name) = param.declarator.id {
// int f(int a, int a)
if names.contains(&name) {
self.err(SemanticError::DuplicateParameter(name), location)
}
names.insert(name);
name
} else {
// int f(int)
InternedStr::default()
};
let meta = Variable {
ctype: param_type.ctype,
id,
qualifiers: param_type.qualifiers,
storage_class: StorageClass::Auto,
};
params.push(meta);
}
// int f(void);
let is_void = match params.as_slice() {
[Variable {
ctype: Type::Void, ..
}] => true,
_ => false,
};
// int f(void, int) or int f(int, void) or ...
if !is_void
&& params.iter().any(|param| match param.ctype {
Type::Void => true,
_ => false,
})
{
self.err(SemanticError::InvalidVoidParameter, location);
// int f(void, ...)
} else if func.varargs && is_void {
self.err(SemanticError::VoidVarargs, location);
// int f(...)
} else if func.varargs && params.is_empty() {
self.err(SemanticError::VarargsWithoutParam, location);
}
Type::Function(FunctionType {
params: params.into_iter().map(|m| m.insert()).collect(),
return_type: Box::new(return_type),
varargs: func.varargs,
})
}
}
}
// used for arrays like `int a[BUF_SIZE - 1];` and enums like `enum { A = 1 }`
fn const_literal(expr: Expr) -> CompileResult<LiteralValue> {
let location = expr.location;
expr.const_fold()?.into_literal().map_err(|runtime_expr| {
Locatable::new(SemanticError::NotConstant(runtime_expr).into(), location)
})
}
/// Return an unsigned integer that can be evaluated at compile time, or an error otherwise.
fn const_uint(expr: Expr) -> CompileResult<crate::arch::SIZE_T> {
use LiteralValue::*;
let location = expr.location;