-
Notifications
You must be signed in to change notification settings - Fork 254
/
Copy pathmod.rs
2124 lines (1875 loc) · 63.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
use c2rust_ast_exporter::clang_ast::LRValue;
use indexmap::{IndexMap, IndexSet};
use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::fmt::{self, Debug, Display};
use std::mem;
use std::ops::Index;
use std::path::{Path, PathBuf};
use std::rc::Rc;
pub use c2rust_ast_exporter::clang_ast::{BuiltinVaListKind, SrcFile, SrcLoc, SrcSpan};
#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Copy, Clone)]
pub struct CTypeId(pub u64);
#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Copy, Clone)]
pub struct CExprId(pub u64);
#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Copy, Clone)]
pub struct CDeclId(pub u64);
#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Copy, Clone)]
pub struct CStmtId(pub u64);
// These are references into particular variants of AST nodes
pub type CLabelId = CStmtId; // Labels point into the 'StmtKind::Label' that declared the label
pub type CFieldId = CDeclId; // Records always contain 'DeclKind::Field's
pub type CParamId = CDeclId; // Parameters always contain 'DeclKind::Variable's
pub type CFuncTypeId = CTypeId; // Function declarations always have types which are 'TypeKind::Function'
pub type CRecordId = CDeclId; // Record types need to point to 'DeclKind::Record'
pub type CTypedefId = CDeclId; // Typedef types need to point to 'DeclKind::Typedef'
pub type CEnumId = CDeclId; // Enum types need to point to 'DeclKind::Enum'
pub type CEnumConstantId = CDeclId; // Enum's need to point to child 'DeclKind::EnumConstant's
pub use self::conversion::*;
pub use self::print::Printer;
mod conversion;
pub mod iterators;
mod print;
use iterators::{DFNodes, SomeId};
/// AST context containing all of the nodes in the Clang AST
#[derive(Debug, Clone)]
pub struct TypedAstContext {
c_types: HashMap<CTypeId, CType>,
c_exprs: HashMap<CExprId, CExpr>,
c_stmts: HashMap<CStmtId, CStmt>,
// Decls require a stable iteration order as this map will be
// iterated over export all defined types during translation.
c_decls: IndexMap<CDeclId, CDecl>,
pub c_decls_top: Vec<CDeclId>,
pub c_main: Option<CDeclId>,
pub parents: HashMap<CDeclId, CDeclId>, // record fields and enum constants
// Mapping from FileId to SrcFile. Deduplicated by file path.
files: Vec<SrcFile>,
// Mapping from clang file id to translator FileId
file_map: Vec<FileId>,
// Vector of include paths, indexed by FileId. Each include path is the
// sequence of #include statement locations and the file being included at
// that location.
include_map: Vec<Vec<SrcLoc>>,
// Names of the labels defined in the C source code.
pub label_names: IndexMap<CLabelId, Rc<str>>,
// map expressions to the stack of macros they were expanded from
pub macro_invocations: HashMap<CExprId, Vec<CDeclId>>,
// map macro decls to the expressions they expand to
pub macro_expansions: HashMap<CDeclId, Vec<CExprId>>,
// map expressions to the text of the macro invocation they expanded from,
// if any
pub macro_expansion_text: HashMap<CExprId, String>,
pub comments: Vec<Located<String>>,
// The key is the typedef decl being squashed away,
// and the value is the decl id to the corresponding structure
pub prenamed_decls: IndexMap<CDeclId, CDeclId>,
pub va_list_kind: BuiltinVaListKind,
pub target: String,
}
/// Comments associated with a typed AST context
#[derive(Debug, Clone)]
pub struct CommentContext {
comments_by_file: HashMap<FileId, RefCell<Vec<Located<String>>>>,
}
#[derive(Debug, Clone)]
pub struct DisplaySrcSpan {
file: Option<PathBuf>,
loc: SrcSpan,
}
impl Display for DisplaySrcSpan {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(ref file) = self.file {
write!(
f,
"{}:{}:{}",
file.display(),
self.loc.begin_line,
self.loc.begin_column
)
} else {
Debug::fmt(self, f)
}
}
}
pub type FileId = usize;
/// Represents some AST node possibly with source location information bundled with it
#[derive(Debug, Clone)]
pub struct Located<T> {
pub loc: Option<SrcSpan>,
pub kind: T,
}
impl<T> Located<T> {
pub fn begin_loc(&self) -> Option<SrcLoc> {
self.loc.map(|loc| loc.begin())
}
pub fn end_loc(&self) -> Option<SrcLoc> {
self.loc.map(|loc| loc.end())
}
}
impl TypedAstContext {
// TODO: build the TypedAstContext during initialization, rather than
// building an empty one and filling it later.
pub fn new(clang_files: &[SrcFile]) -> TypedAstContext {
let mut files: Vec<SrcFile> = vec![];
let mut file_map: Vec<FileId> = vec![];
for file in clang_files {
if let Some(existing) = files.iter().position(|f| f.path == file.path) {
file_map.push(existing);
} else {
file_map.push(files.len());
files.push(file.clone());
}
}
let mut include_map = vec![];
for (fileid, mut cur) in files.iter().enumerate() {
let mut include_path = vec![];
while let Some(include_loc) = &cur.include_loc {
include_path.push(SrcLoc {
fileid: fileid as u64,
line: include_loc.line,
column: include_loc.column,
});
cur = &clang_files[include_loc.fileid as usize];
}
include_path.reverse();
include_map.push(include_path);
}
TypedAstContext {
c_types: HashMap::new(),
c_exprs: HashMap::new(),
c_decls: IndexMap::new(),
c_stmts: HashMap::new(),
c_decls_top: Vec::new(),
c_main: None,
files,
file_map,
include_map,
parents: HashMap::new(),
macro_invocations: HashMap::new(),
macro_expansions: HashMap::new(),
macro_expansion_text: HashMap::new(),
label_names: Default::default(),
comments: Vec::new(),
prenamed_decls: IndexMap::new(),
va_list_kind: BuiltinVaListKind::CharPtrBuiltinVaList,
target: String::new(),
}
}
pub fn display_loc(&self, loc: &Option<SrcSpan>) -> Option<DisplaySrcSpan> {
loc.as_ref().map(|loc| DisplaySrcSpan {
file: self.files[self.file_map[loc.fileid as usize]].path.clone(),
loc: *loc,
})
}
pub fn get_source_path<'a, T>(&'a self, node: &Located<T>) -> Option<&'a Path> {
self.file_id(node)
.and_then(|fileid| self.get_file_path(fileid))
}
pub fn get_file_path(&self, id: FileId) -> Option<&Path> {
self.files[id].path.as_deref()
}
/// Compare two [`SrcLoc`]s based on their import path
pub fn compare_src_locs(&self, a: &SrcLoc, b: &SrcLoc) -> Ordering {
/// Compare without regard to `fileid`.
fn cmp_pos(a: &SrcLoc, b: &SrcLoc) -> Ordering {
(a.line, a.column).cmp(&(b.line, b.column))
}
use Ordering::*;
let path_a = &self.include_map[self.file_map[a.fileid as usize]][..];
let path_b = &self.include_map[self.file_map[b.fileid as usize]][..];
// Find the first include that does not match between the two
let common_len = path_a.len().min(path_b.len());
let order = path_a[..common_len].cmp(&path_b[..common_len]);
if order != Equal {
return order;
}
// Either all parent includes are the same, or the include paths are of different lengths
// because .zip() stops when one of the iterators is empty.
match path_a.len().cmp(&path_b.len()) {
Less => {
// a has the shorter path, which means b was included in a's file
// so extract that include and compare the position to a
let b = &path_b[path_a.len()];
cmp_pos(a, b)
}
Equal => a.cmp(b), // a and b have the same include path and are thus in the same file
Greater => {
// b has the shorter path, which means a was included in b's file
// so extract that include and compare the position to b
let a = &path_a[path_b.len()];
cmp_pos(a, b)
}
}
}
pub fn get_file_include_line_number(&self, file: FileId) -> Option<u64> {
self.include_map[file].first().map(|loc| loc.line)
}
pub fn find_file_id(&self, path: &Path) -> Option<FileId> {
self.files
.iter()
.position(|f| f.path.as_ref().map_or(false, |p| p == path))
}
pub fn file_id<T>(&self, located: &Located<T>) -> Option<FileId> {
located
.loc
.as_ref()
.and_then(|loc| self.file_map.get(loc.fileid as usize).copied())
}
pub fn get_src_loc(&self, id: SomeId) -> Option<SrcSpan> {
use SomeId::*;
match id {
Stmt(id) => self.index(id).loc,
Expr(id) => self.index(id).loc,
Decl(id) => self.index(id).loc,
Type(id) => self.index(id).loc,
}
}
pub fn iter_decls(&self) -> indexmap::map::Iter<CDeclId, CDecl> {
self.c_decls.iter()
}
pub fn iter_mut_decls(&mut self) -> indexmap::map::IterMut<CDeclId, CDecl> {
self.c_decls.iter_mut()
}
pub fn get_decl(&self, key: &CDeclId) -> Option<&CDecl> {
self.c_decls.get(key)
}
pub fn is_null_expr(&self, expr_id: CExprId) -> bool {
use CExprKind::*;
match self[expr_id].kind {
ExplicitCast(_, _, CastKind::NullToPointer, _, _)
| ImplicitCast(_, _, CastKind::NullToPointer, _, _) => true,
ExplicitCast(ty, e, CastKind::BitCast, _, _)
| ImplicitCast(ty, e, CastKind::BitCast, _, _) => {
self.resolve_type(ty.ctype).kind.is_pointer() && self.is_null_expr(e)
}
_ => false,
}
}
/// Predicate for struct, union, and enum declarations without
/// bodies. These forward declarations are suitable for use as
/// the targets of pointers
pub fn is_forward_declared_type(&self, typ: CTypeId) -> bool {
use CDeclKind::*;
|| -> Option<()> {
let decl_id = self.resolve_type(typ).kind.as_underlying_decl()?;
matches!(
self[decl_id].kind,
Struct { fields: None, .. }
| Union { fields: None, .. }
| Enum {
integral_type: None,
..
}
)
.then(|| ())
}()
.is_some()
}
/// Follow a chain of typedefs and return true iff the last typedef is named
/// `__builtin_va_list` thus naming the type clang uses to represent `va_list`s.
pub fn is_builtin_va_list(&self, typ: CTypeId) -> bool {
match self.index(typ).kind {
CTypeKind::Typedef(decl) => match &self.index(decl).kind {
CDeclKind::Typedef {
name: name_,
typ: ty,
..
} => {
if name_ == "__builtin_va_list" {
true
} else {
self.is_builtin_va_list(ty.ctype)
}
}
_ => panic!("Typedef decl did not point to a typedef"),
},
_ => false,
}
}
/// Predicate for types that are used to implement C's `va_list`.
/// FIXME: can we get rid of this method and use `is_builtin_va_list` instead?
pub fn is_va_list_struct(&self, typ: CTypeId) -> bool {
// detect `va_list`s based on typedef (should work across implementations)
// if self.is_builtin_va_list(typ) {
// return true;
// }
// detect `va_list`s based on type (assumes struct-based implementation)
let resolved_ctype = self.resolve_type(typ);
use CTypeKind::*;
match resolved_ctype.kind {
Struct(record_id) => {
if let CDeclKind::Struct {
name: Some(ref name_),
..
} = &self[record_id].kind
{
name_ == "__va_list_tag" || name_ == "__va_list"
} else {
false
}
}
// va_list is a 1 element array; return true iff element type is struct __va_list_tag
ConstantArray(typ, 1) => self.is_va_list(typ),
_ => false,
}
}
/// Predicate for pointers to types that are used to implement C's `va_list`.
pub fn is_va_list(&self, typ: CTypeId) -> bool {
use BuiltinVaListKind::*;
match self.va_list_kind {
CharPtrBuiltinVaList | VoidPtrBuiltinVaList | X86_64ABIBuiltinVaList => {
match self.resolve_type(typ).kind {
CTypeKind::Pointer(CQualTypeId { ctype, .. })
| CTypeKind::ConstantArray(ctype, _) => self.is_va_list_struct(ctype),
_ => false,
}
}
AArch64ABIBuiltinVaList => self.is_va_list_struct(typ),
AAPCSABIBuiltinVaList => {
// The mechanism applies: va_list is a `struct __va_list { ... }` as per
// https://documentation-service.arm.com/static/5f201281bb903e39c84d7eae
// ("Procedure Call Standard for the Arm Architecture Release 2020Q2, Document
// number IHI 0042J") Section 8.1.4 "Additional Types"
self.is_va_list_struct(typ)
}
kind => unimplemented!("va_list type {:?} not yet implemented", kind),
}
}
/// Predicate for function pointers
pub fn is_function_pointer(&self, typ: CTypeId) -> bool {
let resolved_ctype = self.resolve_type(typ);
use CTypeKind::*;
if let Pointer(p) = resolved_ctype.kind {
matches!(self.resolve_type(p.ctype).kind, Function { .. })
} else {
false
}
}
/// Can the given field decl be a flexible array member?
pub fn maybe_flexible_array(&self, typ: CTypeId) -> bool {
let field_ty = self.resolve_type(typ);
use CTypeKind::*;
matches!(field_ty.kind, IncompleteArray(_) | ConstantArray(_, 0 | 1))
}
pub fn get_pointee_qual_type(&self, typ: CTypeId) -> Option<CQualTypeId> {
let resolved_ctype = self.resolve_type(typ);
if let CTypeKind::Pointer(p) = resolved_ctype.kind {
Some(p)
} else {
None
}
}
/// Resolve expression value, ignoring any casts
pub fn resolve_expr(&self, expr_id: CExprId) -> (CExprId, &CExprKind) {
let expr = &self.index(expr_id).kind;
use CExprKind::*;
match expr {
ImplicitCast(_, subexpr, _, _, _)
| ExplicitCast(_, subexpr, _, _, _)
| Paren(_, subexpr) => self.resolve_expr(*subexpr),
_ => (expr_id, expr),
}
}
/// Resolve true expression type, iterating through any casts and variable
/// references.
pub fn resolve_expr_type_id(&self, expr_id: CExprId) -> Option<(CExprId, CTypeId)> {
let expr = &self.index(expr_id).kind;
let mut ty = expr.get_type();
use CExprKind::*;
match expr {
ImplicitCast(_, subexpr, _, _, _)
| ExplicitCast(_, subexpr, _, _, _)
| Paren(_, subexpr) => {
return self.resolve_expr_type_id(*subexpr);
}
DeclRef(_, decl_id, _) => {
let decl = self.index(*decl_id);
use CDeclKind::*;
match decl.kind {
Function { typ, .. } => {
ty = Some(self.resolve_type_id(typ));
}
Variable { typ, .. } | Typedef { typ, .. } => {
ty = Some(self.resolve_type_id(typ.ctype));
}
_ => {}
}
}
_ => {}
}
ty.map(|ty| (expr_id, ty))
}
pub fn resolve_type_id(&self, typ: CTypeId) -> CTypeId {
use CTypeKind::*;
let ty = match self.index(typ).kind {
Attributed(ty, _) => ty.ctype,
Elaborated(ty) => ty,
Decayed(ty) => ty,
TypeOf(ty) => ty,
Paren(ty) => ty,
Typedef(decl) => match self.index(decl).kind {
CDeclKind::Typedef { typ: ty, .. } => ty.ctype,
_ => panic!("Typedef decl did not point to a typedef"),
},
_ => return typ,
};
self.resolve_type_id(ty)
}
pub fn resolve_type(&self, typ: CTypeId) -> &CType {
let resolved_typ_id = self.resolve_type_id(typ);
self.index(resolved_typ_id)
}
/// Pessimistically try to check if an expression has side effects. If it does, or we can't tell
/// that it doesn't, return `false`.
pub fn is_expr_pure(&self, expr: CExprId) -> bool {
use CExprKind::*;
let pure = |expr| self.is_expr_pure(expr);
match self.index(expr).kind {
BadExpr |
ShuffleVector(..) |
ConvertVector(..) |
Call(..) |
Unary(_, UnOp::PreIncrement, _, _) |
Unary(_, UnOp::PostIncrement, _, _) |
Unary(_, UnOp::PreDecrement, _, _) |
Unary(_, UnOp::PostDecrement, _, _) |
Binary(_, BinOp::Assign, _, _, _, _) |
InitList { .. } |
ImplicitValueInit { .. } |
Predefined(..) |
Statements(..) | // TODO: more precision
VAArg(..) |
Atomic{..} => false,
Literal(_, _) |
DeclRef(_, _, _) |
UnaryType(_, _, _, _) |
OffsetOf(..) |
ConstantExpr(..) => true,
DesignatedInitExpr(_,_,e) |
ImplicitCast(_, e, _, _, _) |
ExplicitCast(_, e, _, _, _) |
Member(_, e, _, _, _) |
Paren(_, e) |
CompoundLiteral(_, e) |
Unary(_, _, e, _) => pure(e),
Binary(_, op, _, _, _, _) if op.underlying_assignment().is_some() => false,
Binary(_, _, lhs, rhs, _, _) => pure(lhs) && pure(rhs),
ArraySubscript(_, lhs, rhs, _) => pure(lhs) && pure(rhs),
Conditional(_, c, lhs, rhs) => pure(c) && pure(lhs) && pure(rhs),
BinaryConditional(_, c, rhs) => pure(c) && pure(rhs),
Choose(_, c, lhs, rhs, _) => pure(c) && pure(lhs) && pure(rhs),
}
}
// Pessimistically try to check if an expression doesn't return. If it does, or we can't tell
/// that it doesn't, return `false`.
pub fn expr_diverges(&self, expr_id: CExprId) -> bool {
let func_id = match self.index(expr_id).kind {
CExprKind::Call(_, func_id, _) => func_id,
_ => return false,
};
let type_id = match self[func_id].kind.get_type() {
None => return false,
Some(t) => t,
};
let pointed_id = match self.index(type_id).kind {
CTypeKind::Pointer(pointer_qualtype) => pointer_qualtype.ctype,
_ => return false,
};
match self.index(pointed_id).kind {
CTypeKind::Function(_, _, _, no_return, _) => no_return,
_ => false,
}
}
pub fn prune_unwanted_decls(&mut self, want_unused_functions: bool) {
// Starting from a set of root declarations, walk each one to find declarations it
// depends on. Then walk each of those, recursively.
// Declarations we still need to walk. Everything in here is also in `wanted`.
let mut to_walk: Vec<CDeclId> = Vec::new();
// Declarations accessible from a root.
let mut wanted: HashSet<CDeclId> = HashSet::new();
// Mark all the roots as wanted. Roots are all top-level functions and variables that might
// be visible from another compilation unit.
//
// In addition, mark any other (unused) function wanted if configured.
for &decl_id in &self.c_decls_top {
let decl = self.index(decl_id);
use CDeclKind::*;
let is_wanted = match decl.kind {
Function {
body: Some(_),
is_global: true,
is_inline,
is_inline_externally_visible,
..
// Depending on the C specification and dialect, an inlined function
// may be externally visible. We rely on clang to determine visibility.
} if !is_inline || is_inline_externally_visible => true,
Function {
body: Some(_),
..
} if want_unused_functions => true,
Variable {
is_defn: true,
is_externally_visible: true,
..
} => true,
Variable { ref attrs, .. } | Function { ref attrs, .. }
if attrs.contains(&Attribute::Used) => true,
_ => false,
};
if is_wanted {
to_walk.push(decl_id);
wanted.insert(decl_id);
}
}
// Add all referenced macros to the set of wanted decls
// wanted.extend(self.macro_expansions.values().flatten());
while let Some(enclosing_decl_id) = to_walk.pop() {
for some_id in DFNodes::new(self, SomeId::Decl(enclosing_decl_id)) {
use SomeId::*;
match some_id {
Type(type_id) => {
if let CTypeKind::Elaborated(decl_type_id) = self.c_types[&type_id].kind {
// This is a reference to a previously declared type. If we look
// through it we should(?) get something that looks like a declaration,
// which we can mark as wanted.
let decl_id = self.c_types[&decl_type_id]
.kind
.as_decl_or_typedef()
.expect("target of CTypeKind::Elaborated isn't a decl?");
if wanted.insert(decl_id) {
to_walk.push(decl_id);
}
} else {
// For everything else (including `Struct` etc.), DFNodes will walk the
// corresponding declaration.
}
}
Expr(expr_id) => {
let expr = self.index(expr_id);
if let Some(macs) = self.macro_invocations.get(&expr_id) {
for mac_id in macs {
if wanted.insert(*mac_id) {
to_walk.push(*mac_id);
}
}
}
if let CExprKind::DeclRef(_, decl_id, _) = &expr.kind {
if wanted.insert(*decl_id) {
to_walk.push(*decl_id);
}
}
}
Decl(decl_id) => {
if wanted.insert(decl_id) {
to_walk.push(decl_id);
}
if let CDeclKind::EnumConstant { .. } = self.c_decls[&decl_id].kind {
// Special case for enums. The enum constant is used, so the whole
// enum is also used.
let parent_id = self.parents[&decl_id];
if wanted.insert(parent_id) {
to_walk.push(parent_id);
}
}
}
// Stmts can include decls, but we'll see the DeclId itself in a later
// iteration.
Stmt(_) => {}
}
}
}
// Unset c_main if we are not retaining its declaration
if let Some(main_id) = self.c_main {
if !wanted.contains(&main_id) {
self.c_main = None;
}
}
// Prune any declaration that isn't considered live
self.c_decls
.retain(|&decl_id, _decl| wanted.contains(&decl_id));
// Prune top declarations that are not considered live
self.c_decls_top.retain(|x| wanted.contains(x));
}
pub fn sort_top_decls(&mut self) {
// Group and sort declarations by file and by position
let mut decls_top = mem::take(&mut self.c_decls_top);
decls_top.sort_unstable_by(|a, b| {
let a = self.index(*a);
let b = self.index(*b);
use Ordering::*;
match (&a.loc, &b.loc) {
(None, None) => Equal,
(None, _) => Less,
(_, None) => Greater,
(Some(a), Some(b)) => self.compare_src_locs(&a.begin(), &b.begin()),
}
});
self.c_decls_top = decls_top;
}
pub fn has_inner_struct_decl(&self, decl_id: CDeclId) -> bool {
matches!(
self.index(decl_id).kind,
CDeclKind::Struct {
manual_alignment: Some(_),
..
}
)
}
pub fn is_packed_struct_decl(&self, decl_id: CDeclId) -> bool {
use CDeclKind::*;
matches!(
self.index(decl_id).kind,
Struct {
is_packed: true,
..
} | Struct {
max_field_alignment: Some(_),
..
}
)
}
pub fn is_aligned_struct_type(&self, typ: CTypeId) -> bool {
if let Some(decl_id) = self.resolve_type(typ).kind.as_underlying_decl() {
if let CDeclKind::Struct {
manual_alignment: Some(_),
..
} = self.index(decl_id).kind
{
return true;
}
}
false
}
}
impl CommentContext {
pub fn empty() -> CommentContext {
CommentContext {
comments_by_file: HashMap::new(),
}
}
/// Build a CommentContext from the comments in this `ast_context`
pub fn new(ast_context: &mut TypedAstContext) -> CommentContext {
let mut comments_by_file: HashMap<FileId, Vec<Located<String>>> = HashMap::new();
// Group comments by their file
for comment in &ast_context.comments {
// Comments without a valid FileId are probably clang
// compiler-internal definitions
if let Some(file_id) = ast_context.file_id(comment) {
comments_by_file
.entry(file_id)
.or_default()
.push(comment.clone());
}
}
// Sort in REVERSE! Last element is the first in file source
// ordering. This makes it easy to pop the next comment off.
for comments in comments_by_file.values_mut() {
comments.sort_by(|a, b| {
ast_context.compare_src_locs(&b.loc.unwrap().begin(), &a.loc.unwrap().begin())
});
}
let comments_by_file = comments_by_file
.into_iter()
.map(|(k, v)| (k, RefCell::new(v)))
.collect();
CommentContext { comments_by_file }
}
pub fn get_comments_before(&self, loc: SrcLoc, ctx: &TypedAstContext) -> Vec<String> {
let file_id = ctx.file_map[loc.fileid as usize];
let mut extracted_comments = vec![];
let mut comments = match self.comments_by_file.get(&file_id) {
None => return extracted_comments,
Some(comments) => comments.borrow_mut(),
};
while !comments.is_empty() {
let next_comment_loc = comments
.last()
.unwrap()
.begin_loc()
.expect("All comments must have a source location");
if ctx.compare_src_locs(&next_comment_loc, &loc) != Ordering::Less {
break;
}
extracted_comments.push(comments.pop().unwrap().kind);
}
extracted_comments
}
pub fn get_comments_before_located<T>(
&self,
located: &Located<T>,
ctx: &TypedAstContext,
) -> Vec<String> {
match located.begin_loc() {
None => vec![],
Some(loc) => self.get_comments_before(loc, ctx),
}
}
pub fn peek_next_comment_on_line(
&self,
loc: SrcLoc,
ctx: &TypedAstContext,
) -> Option<Located<String>> {
let file_id = ctx.file_map[loc.fileid as usize];
let comments = self.comments_by_file.get(&file_id)?.borrow();
comments.last().and_then(|comment| {
let next_comment_loc = comment
.begin_loc()
.expect("All comments must have a source location");
if next_comment_loc.line != loc.line {
None
} else {
Some(comment.clone())
}
})
}
/// Advance over the current comment in `file`
pub fn advance_comment(&self, file: FileId) {
if let Some(comments) = self.comments_by_file.get(&file) {
let _ = comments.borrow_mut().pop();
}
}
pub fn get_remaining_comments(&mut self, file_id: FileId) -> Vec<String> {
match self.comments_by_file.remove(&file_id) {
Some(comments) => comments.into_inner().into_iter().map(|c| c.kind).collect(),
None => vec![],
}
}
}
impl Index<CTypeId> for TypedAstContext {
type Output = CType;
fn index(&self, index: CTypeId) -> &CType {
match self.c_types.get(&index) {
None => panic!("Could not find {:?} in TypedAstContext", index),
Some(ty) => ty,
}
}
}
impl Index<CExprId> for TypedAstContext {
type Output = CExpr;
fn index(&self, index: CExprId) -> &CExpr {
static BADEXPR: CExpr = Located {
loc: None,
kind: CExprKind::BadExpr,
};
match self.c_exprs.get(&index) {
None => &BADEXPR, // panic!("Could not find {:?} in TypedAstContext", index),
Some(e) => {
// Transparently index through Paren expressions
if let CExprKind::Paren(_, subexpr) = e.kind {
self.index(subexpr)
} else {
e
}
}
}
}
}
impl Index<CDeclId> for TypedAstContext {
type Output = CDecl;
fn index(&self, index: CDeclId) -> &CDecl {
match self.c_decls.get(&index) {
None => panic!("Could not find {:?} in TypedAstContext", index),
Some(ty) => ty,
}
}
}
impl Index<CStmtId> for TypedAstContext {
type Output = CStmt;
fn index(&self, index: CStmtId) -> &CStmt {
match self.c_stmts.get(&index) {
None => panic!("Could not find {:?} in TypedAstContext", index),
Some(ty) => ty,
}
}
}
/// All of our AST types should have location information bundled with them
pub type CDecl = Located<CDeclKind>;
pub type CStmt = Located<CStmtKind>;
pub type CExpr = Located<CExprKind>;
pub type CType = Located<CTypeKind>;
#[derive(Debug, Clone)]
pub enum CDeclKind {
// http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html
Function {
is_global: bool,
is_inline: bool,
is_implicit: bool,
is_extern: bool,
is_inline_externally_visible: bool,
typ: CFuncTypeId,
name: String,
parameters: Vec<CParamId>,
body: Option<CStmtId>,
attrs: IndexSet<Attribute>,
},
// http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html
Variable {
has_static_duration: bool,
has_thread_duration: bool,
is_externally_visible: bool,
is_defn: bool,
ident: String,
initializer: Option<CExprId>,
typ: CQualTypeId,
attrs: IndexSet<Attribute>,
},
// Enum (http://clang.llvm.org/doxygen/classclang_1_1EnumDecl.html)
Enum {
name: Option<String>,
variants: Vec<CEnumConstantId>,
integral_type: Option<CQualTypeId>,
},
EnumConstant {
name: String,
value: ConstIntExpr,
},
// Typedef
Typedef {
name: String,
typ: CQualTypeId,
is_implicit: bool,
},
// Struct
Struct {
name: Option<String>,
fields: Option<Vec<CFieldId>>,
is_packed: bool,
manual_alignment: Option<u64>,
max_field_alignment: Option<u64>,
platform_byte_size: u64,
platform_alignment: u64,
},
// Union
Union {
name: Option<String>,
fields: Option<Vec<CFieldId>>,
is_packed: bool,
},
// Field
Field {
name: String,
typ: CQualTypeId,
bitfield_width: Option<u64>,
platform_bit_offset: u64,
platform_type_bitwidth: u64,
},
MacroObject {
name: String,
// replacements: Vec<CExprId>,
},
MacroFunction {
name: String,
// replacements: Vec<CExprId>,
},
NonCanonicalDecl {
canonical_decl: CDeclId,
},
StaticAssert {
assert_expr: CExprId,
message: Option<CExprId>,
},
}
impl CDeclKind {
pub fn get_name(&self) -> Option<&String> {
use CDeclKind::*;
Some(match self {