-
Notifications
You must be signed in to change notification settings - Fork 707
/
clang.rs
2236 lines (1987 loc) · 66.9 KB
/
clang.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
//! A higher level Clang API built on top of the generated bindings in the
//! `clang_sys` module.
#![allow(non_upper_case_globals, dead_code)]
#![deny(clippy::missing_docs_in_private_items)]
use crate::ir::context::BindgenContext;
use clang_sys::*;
use std::ffi::{CStr, CString};
use std::fmt;
use std::hash::Hash;
use std::hash::Hasher;
use std::os::raw::{c_char, c_int, c_longlong, c_uint, c_ulong, c_ulonglong};
use std::{mem, ptr, slice};
/// Type representing a clang attribute.
///
/// Values of this type can be used to check for different attributes using the `has_attrs`
/// function.
pub(crate) struct Attribute {
name: &'static [u8],
kind: Option<CXCursorKind>,
token_kind: CXTokenKind,
}
impl Attribute {
/// A `warn_unused_result` attribute.
pub(crate) const MUST_USE: Self = Self {
name: b"warn_unused_result",
// FIXME(emilio): clang-sys doesn't expose `CXCursor_WarnUnusedResultAttr` (from clang 9).
kind: Some(440),
token_kind: CXToken_Identifier,
};
/// A `_Noreturn` attribute.
pub(crate) const NO_RETURN: Self = Self {
name: b"_Noreturn",
kind: None,
token_kind: CXToken_Keyword,
};
/// A `[[noreturn]]` attribute.
pub(crate) const NO_RETURN_CPP: Self = Self {
name: b"noreturn",
kind: None,
token_kind: CXToken_Identifier,
};
}
/// A cursor into the Clang AST, pointing to an AST node.
///
/// We call the AST node pointed to by the cursor the cursor's "referent".
#[derive(Copy, Clone)]
pub(crate) struct Cursor {
x: CXCursor,
}
impl fmt::Debug for Cursor {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(
fmt,
"Cursor({} kind: {}, loc: {}, usr: {:?})",
self.spelling(),
kind_to_str(self.kind()),
self.location(),
self.usr()
)
}
}
impl Cursor {
/// Get the Unified Symbol Resolution for this cursor's referent, if
/// available.
///
/// The USR can be used to compare entities across translation units.
pub(crate) fn usr(&self) -> Option<String> {
let s = unsafe { cxstring_into_string(clang_getCursorUSR(self.x)) };
if s.is_empty() {
None
} else {
Some(s)
}
}
/// Is this cursor's referent a declaration?
pub(crate) fn is_declaration(&self) -> bool {
unsafe { clang_isDeclaration(self.kind()) != 0 }
}
/// Is this cursor's referent an anonymous record or so?
pub(crate) fn is_anonymous(&self) -> bool {
unsafe { clang_Cursor_isAnonymous(self.x) != 0 }
}
/// Get this cursor's referent's spelling.
pub(crate) fn spelling(&self) -> String {
unsafe { cxstring_into_string(clang_getCursorSpelling(self.x)) }
}
/// Get this cursor's referent's display name.
///
/// This is not necessarily a valid identifier. It includes extra
/// information, such as parameters for a function, etc.
pub(crate) fn display_name(&self) -> String {
unsafe { cxstring_into_string(clang_getCursorDisplayName(self.x)) }
}
/// Get the mangled name of this cursor's referent.
pub(crate) fn mangling(&self) -> String {
unsafe { cxstring_into_string(clang_Cursor_getMangling(self.x)) }
}
/// Gets the C++ manglings for this cursor, or an error if the manglings
/// are not available.
pub(crate) fn cxx_manglings(&self) -> Result<Vec<String>, ()> {
use clang_sys::*;
unsafe {
let manglings = clang_Cursor_getCXXManglings(self.x);
if manglings.is_null() {
return Err(());
}
let count = (*manglings).Count as usize;
let mut result = Vec::with_capacity(count);
for i in 0..count {
let string_ptr = (*manglings).Strings.add(i);
result.push(cxstring_to_string_leaky(*string_ptr));
}
clang_disposeStringSet(manglings);
Ok(result)
}
}
/// Returns whether the cursor refers to a built-in definition.
pub(crate) fn is_builtin(&self) -> bool {
let (file, _, _, _) = self.location().location();
file.name().is_none()
}
/// Get the `Cursor` for this cursor's referent's lexical parent.
///
/// The lexical parent is the parent of the definition. The semantic parent
/// is the parent of the declaration. Generally, the lexical parent doesn't
/// have any effect on semantics, while the semantic parent does.
///
/// In the following snippet, the `Foo` class would be the semantic parent
/// of the out-of-line `method` definition, while the lexical parent is the
/// translation unit.
///
/// ```c++
/// class Foo {
/// void method();
/// };
///
/// void Foo::method() { /* ... */ }
/// ```
pub(crate) fn lexical_parent(&self) -> Cursor {
unsafe {
Cursor {
x: clang_getCursorLexicalParent(self.x),
}
}
}
/// Get the referent's semantic parent, if one is available.
///
/// See documentation for `lexical_parent` for details on semantic vs
/// lexical parents.
pub(crate) fn fallible_semantic_parent(&self) -> Option<Cursor> {
let sp = unsafe {
Cursor {
x: clang_getCursorSemanticParent(self.x),
}
};
if sp == *self || !sp.is_valid() {
return None;
}
Some(sp)
}
/// Get the referent's semantic parent.
///
/// See documentation for `lexical_parent` for details on semantic vs
/// lexical parents.
pub(crate) fn semantic_parent(&self) -> Cursor {
self.fallible_semantic_parent().unwrap()
}
/// Return the number of template arguments used by this cursor's referent,
/// if the referent is either a template instantiation. Returns `None`
/// otherwise.
///
/// NOTE: This may not return `Some` for partial template specializations,
/// see #193 and #194.
pub(crate) fn num_template_args(&self) -> Option<u32> {
// XXX: `clang_Type_getNumTemplateArguments` is sort of reliable, while
// `clang_Cursor_getNumTemplateArguments` is totally unreliable.
// Therefore, try former first, and only fallback to the latter if we
// have to.
self.cur_type()
.num_template_args()
.or_else(|| {
let n: c_int =
unsafe { clang_Cursor_getNumTemplateArguments(self.x) };
if n >= 0 {
Some(n as u32)
} else {
debug_assert_eq!(n, -1);
None
}
})
.or_else(|| {
let canonical = self.canonical();
if canonical != *self {
canonical.num_template_args()
} else {
None
}
})
}
/// Get a cursor pointing to this referent's containing translation unit.
///
/// Note that we shouldn't create a `TranslationUnit` struct here, because
/// bindgen assumes there will only be one of them alive at a time, and
/// disposes it on drop. That can change if this would be required, but I
/// think we can survive fine without it.
pub(crate) fn translation_unit(&self) -> Cursor {
assert!(self.is_valid());
unsafe {
let tu = clang_Cursor_getTranslationUnit(self.x);
let cursor = Cursor {
x: clang_getTranslationUnitCursor(tu),
};
assert!(cursor.is_valid());
cursor
}
}
/// Is the referent a top level construct?
pub(crate) fn is_toplevel(&self) -> bool {
let mut semantic_parent = self.fallible_semantic_parent();
while semantic_parent.is_some() &&
(semantic_parent.unwrap().kind() == CXCursor_Namespace ||
semantic_parent.unwrap().kind() ==
CXCursor_NamespaceAlias ||
semantic_parent.unwrap().kind() == CXCursor_NamespaceRef)
{
semantic_parent =
semantic_parent.unwrap().fallible_semantic_parent();
}
let tu = self.translation_unit();
// Yes, this can happen with, e.g., macro definitions.
semantic_parent == tu.fallible_semantic_parent()
}
/// There are a few kinds of types that we need to treat specially, mainly
/// not tracking the type declaration but the location of the cursor, given
/// clang doesn't expose a proper declaration for these types.
pub(crate) fn is_template_like(&self) -> bool {
matches!(
self.kind(),
CXCursor_ClassTemplate |
CXCursor_ClassTemplatePartialSpecialization |
CXCursor_TypeAliasTemplateDecl
)
}
/// Is this Cursor pointing to a function-like macro definition?
pub(crate) fn is_macro_function_like(&self) -> bool {
unsafe { clang_Cursor_isMacroFunctionLike(self.x) != 0 }
}
/// Get the kind of referent this cursor is pointing to.
pub(crate) fn kind(&self) -> CXCursorKind {
self.x.kind
}
/// Returns true if the cursor is a definition
pub(crate) fn is_definition(&self) -> bool {
unsafe { clang_isCursorDefinition(self.x) != 0 }
}
/// Is the referent a template specialization?
pub(crate) fn is_template_specialization(&self) -> bool {
self.specialized().is_some()
}
/// Is the referent a fully specialized template specialization without any
/// remaining free template arguments?
pub(crate) fn is_fully_specialized_template(&self) -> bool {
self.is_template_specialization() &&
self.kind() != CXCursor_ClassTemplatePartialSpecialization &&
self.num_template_args().unwrap_or(0) > 0
}
/// Is the referent a template specialization that still has remaining free
/// template arguments?
pub(crate) fn is_in_non_fully_specialized_template(&self) -> bool {
if self.is_toplevel() {
return false;
}
let parent = self.semantic_parent();
if parent.is_fully_specialized_template() {
return false;
}
if !parent.is_template_like() {
return parent.is_in_non_fully_specialized_template();
}
true
}
/// Is the referent any kind of template parameter?
pub(crate) fn is_template_parameter(&self) -> bool {
matches!(
self.kind(),
CXCursor_TemplateTemplateParameter |
CXCursor_TemplateTypeParameter |
CXCursor_NonTypeTemplateParameter
)
}
/// Does the referent's type or value depend on a template parameter?
pub(crate) fn is_dependent_on_template_parameter(&self) -> bool {
fn visitor(
found_template_parameter: &mut bool,
cur: Cursor,
) -> CXChildVisitResult {
// If we found a template parameter, it is dependent.
if cur.is_template_parameter() {
*found_template_parameter = true;
return CXChildVisit_Break;
}
// Get the referent and traverse it as well.
if let Some(referenced) = cur.referenced() {
if referenced.is_template_parameter() {
*found_template_parameter = true;
return CXChildVisit_Break;
}
referenced
.visit(|next| visitor(found_template_parameter, next));
if *found_template_parameter {
return CXChildVisit_Break;
}
}
// Continue traversing the AST at the original cursor.
CXChildVisit_Recurse
}
if self.is_template_parameter() {
return true;
}
let mut found_template_parameter = false;
self.visit(|next| visitor(&mut found_template_parameter, next));
found_template_parameter
}
/// Is this cursor pointing a valid referent?
pub(crate) fn is_valid(&self) -> bool {
unsafe { clang_isInvalid(self.kind()) == 0 }
}
/// Get the source location for the referent.
pub(crate) fn location(&self) -> SourceLocation {
unsafe {
SourceLocation {
x: clang_getCursorLocation(self.x),
}
}
}
/// Get the source location range for the referent.
pub(crate) fn extent(&self) -> CXSourceRange {
unsafe { clang_getCursorExtent(self.x) }
}
/// Get the raw declaration comment for this referent, if one exists.
pub(crate) fn raw_comment(&self) -> Option<String> {
let s = unsafe {
cxstring_into_string(clang_Cursor_getRawCommentText(self.x))
};
if s.is_empty() {
None
} else {
Some(s)
}
}
/// Get the referent's parsed comment.
pub(crate) fn comment(&self) -> Comment {
unsafe {
Comment {
x: clang_Cursor_getParsedComment(self.x),
}
}
}
/// Get the referent's type.
pub(crate) fn cur_type(&self) -> Type {
unsafe {
Type {
x: clang_getCursorType(self.x),
}
}
}
/// Given that this cursor's referent is a reference to another type, or is
/// a declaration, get the cursor pointing to the referenced type or type of
/// the declared thing.
pub(crate) fn definition(&self) -> Option<Cursor> {
unsafe {
let ret = Cursor {
x: clang_getCursorDefinition(self.x),
};
if ret.is_valid() && ret.kind() != CXCursor_NoDeclFound {
Some(ret)
} else {
None
}
}
}
/// Given that this cursor's referent is reference type, get the cursor
/// pointing to the referenced type.
pub(crate) fn referenced(&self) -> Option<Cursor> {
unsafe {
let ret = Cursor {
x: clang_getCursorReferenced(self.x),
};
if ret.is_valid() {
Some(ret)
} else {
None
}
}
}
/// Get the canonical cursor for this referent.
///
/// Many types can be declared multiple times before finally being properly
/// defined. This method allows us to get the canonical cursor for the
/// referent type.
pub(crate) fn canonical(&self) -> Cursor {
unsafe {
Cursor {
x: clang_getCanonicalCursor(self.x),
}
}
}
/// Given that this cursor points to either a template specialization or a
/// template instantiation, get a cursor pointing to the template definition
/// that is being specialized.
pub(crate) fn specialized(&self) -> Option<Cursor> {
unsafe {
let ret = Cursor {
x: clang_getSpecializedCursorTemplate(self.x),
};
if ret.is_valid() {
Some(ret)
} else {
None
}
}
}
/// Assuming that this cursor's referent is a template declaration, get the
/// kind of cursor that would be generated for its specializations.
pub(crate) fn template_kind(&self) -> CXCursorKind {
unsafe { clang_getTemplateCursorKind(self.x) }
}
/// Traverse this cursor's referent and its children.
///
/// Call the given function on each AST node traversed.
pub(crate) fn visit<Visitor>(&self, mut visitor: Visitor)
where
Visitor: FnMut(Cursor) -> CXChildVisitResult,
{
let data = &mut visitor as *mut Visitor;
unsafe {
clang_visitChildren(self.x, visit_children::<Visitor>, data.cast());
}
}
/// Collect all of this cursor's children into a vec and return them.
pub(crate) fn collect_children(&self) -> Vec<Cursor> {
let mut children = vec![];
self.visit(|c| {
children.push(c);
CXChildVisit_Continue
});
children
}
/// Does this cursor have any children?
pub(crate) fn has_children(&self) -> bool {
let mut has_children = false;
self.visit(|_| {
has_children = true;
CXChildVisit_Break
});
has_children
}
/// Does this cursor have at least `n` children?
pub(crate) fn has_at_least_num_children(&self, n: usize) -> bool {
assert!(n > 0);
let mut num_left = n;
self.visit(|_| {
num_left -= 1;
if num_left == 0 {
CXChildVisit_Break
} else {
CXChildVisit_Continue
}
});
num_left == 0
}
/// Returns whether the given location contains a cursor with the given
/// kind in the first level of nesting underneath (doesn't look
/// recursively).
pub(crate) fn contains_cursor(&self, kind: CXCursorKind) -> bool {
let mut found = false;
self.visit(|c| {
if c.kind() == kind {
found = true;
CXChildVisit_Break
} else {
CXChildVisit_Continue
}
});
found
}
/// Is the referent an inlined function?
pub(crate) fn is_inlined_function(&self) -> bool {
unsafe { clang_Cursor_isFunctionInlined(self.x) != 0 }
}
/// Is the referent a defaulted function?
pub(crate) fn is_defaulted_function(&self) -> bool {
unsafe { clang_CXXMethod_isDefaulted(self.x) != 0 }
}
/// Is the referent a deleted function?
pub(crate) fn is_deleted_function(&self) -> bool {
// Unfortunately, libclang doesn't yet have an API for checking if a
// member function is deleted, but the following should be a good
// enough approximation.
// Deleted functions are implicitly inline according to paragraph 4 of
// [dcl.fct.def.delete] in the C++ standard. Normal inline functions
// have a definition in the same translation unit, so if this is an
// inline function without a definition, and it's not a defaulted
// function, we can reasonably safely conclude that it's a deleted
// function.
self.is_inlined_function() &&
self.definition().is_none() &&
!self.is_defaulted_function()
}
/// Is the referent a bit field declaration?
pub(crate) fn is_bit_field(&self) -> bool {
unsafe { clang_Cursor_isBitField(self.x) != 0 }
}
/// Get a cursor to the bit field's width expression, or `None` if it's not
/// a bit field.
pub(crate) fn bit_width_expr(&self) -> Option<Cursor> {
if !self.is_bit_field() {
return None;
}
let mut result = None;
self.visit(|cur| {
// The first child may or may not be a TypeRef, depending on whether
// the field's type is builtin. Skip it.
if cur.kind() == CXCursor_TypeRef {
return CXChildVisit_Continue;
}
// The next expression or literal is the bit width.
result = Some(cur);
CXChildVisit_Break
});
result
}
/// Get the width of this cursor's referent bit field, or `None` if the
/// referent is not a bit field or if the width could not be evaluated.
pub(crate) fn bit_width(&self) -> Option<u32> {
// It is not safe to check the bit width without ensuring it doesn't
// depend on a template parameter. See
// https://github.com/rust-lang/rust-bindgen/issues/2239
if self.bit_width_expr()?.is_dependent_on_template_parameter() {
return None;
}
unsafe {
let w = clang_getFieldDeclBitWidth(self.x);
if w == -1 {
None
} else {
Some(w as u32)
}
}
}
/// Get the integer representation type used to hold this cursor's referent
/// enum type.
pub(crate) fn enum_type(&self) -> Option<Type> {
unsafe {
let t = Type {
x: clang_getEnumDeclIntegerType(self.x),
};
if t.is_valid() {
Some(t)
} else {
None
}
}
}
/// Get the boolean constant value for this cursor's enum variant referent.
///
/// Returns None if the cursor's referent is not an enum variant.
pub(crate) fn enum_val_boolean(&self) -> Option<bool> {
unsafe {
if self.kind() == CXCursor_EnumConstantDecl {
Some(clang_getEnumConstantDeclValue(self.x) != 0)
} else {
None
}
}
}
/// Get the signed constant value for this cursor's enum variant referent.
///
/// Returns None if the cursor's referent is not an enum variant.
pub(crate) fn enum_val_signed(&self) -> Option<i64> {
unsafe {
if self.kind() == CXCursor_EnumConstantDecl {
#[allow(clippy::unnecessary_cast)]
Some(clang_getEnumConstantDeclValue(self.x) as i64)
} else {
None
}
}
}
/// Get the unsigned constant value for this cursor's enum variant referent.
///
/// Returns None if the cursor's referent is not an enum variant.
pub(crate) fn enum_val_unsigned(&self) -> Option<u64> {
unsafe {
if self.kind() == CXCursor_EnumConstantDecl {
#[allow(clippy::unnecessary_cast)]
Some(clang_getEnumConstantDeclUnsignedValue(self.x) as u64)
} else {
None
}
}
}
/// Does this cursor have the given attributes?
pub(crate) fn has_attrs<const N: usize>(
&self,
attrs: &[Attribute; N],
) -> [bool; N] {
let mut found_attrs = [false; N];
let mut found_count = 0;
self.visit(|cur| {
let kind = cur.kind();
for (idx, attr) in attrs.iter().enumerate() {
let found_attr = &mut found_attrs[idx];
if !*found_attr {
// `attr.name` and` attr.token_kind` are checked against unexposed attributes only.
if attr.kind.map_or(false, |k| k == kind) ||
(kind == CXCursor_UnexposedAttr &&
cur.tokens().iter().any(|t| {
t.kind == attr.token_kind &&
t.spelling() == attr.name
}))
{
*found_attr = true;
found_count += 1;
if found_count == N {
return CXChildVisit_Break;
}
}
}
}
CXChildVisit_Continue
});
found_attrs
}
/// Given that this cursor's referent is a `typedef`, get the `Type` that is
/// being aliased.
pub(crate) fn typedef_type(&self) -> Option<Type> {
let inner = Type {
x: unsafe { clang_getTypedefDeclUnderlyingType(self.x) },
};
if inner.is_valid() {
Some(inner)
} else {
None
}
}
/// Get the linkage kind for this cursor's referent.
///
/// This only applies to functions and variables.
pub(crate) fn linkage(&self) -> CXLinkageKind {
unsafe { clang_getCursorLinkage(self.x) }
}
/// Get the visibility of this cursor's referent.
pub(crate) fn visibility(&self) -> CXVisibilityKind {
unsafe { clang_getCursorVisibility(self.x) }
}
/// Given that this cursor's referent is a function, return cursors to its
/// parameters.
///
/// Returns None if the cursor's referent is not a function/method call or
/// declaration.
pub(crate) fn args(&self) -> Option<Vec<Cursor>> {
// match self.kind() {
// CXCursor_FunctionDecl |
// CXCursor_CXXMethod => {
self.num_args().ok().map(|num| {
(0..num)
.map(|i| Cursor {
x: unsafe { clang_Cursor_getArgument(self.x, i as c_uint) },
})
.collect()
})
}
/// Given that this cursor's referent is a function/method call or
/// declaration, return the number of arguments it takes.
///
/// Returns Err if the cursor's referent is not a function/method call or
/// declaration.
pub(crate) fn num_args(&self) -> Result<u32, ()> {
unsafe {
let w = clang_Cursor_getNumArguments(self.x);
if w == -1 {
Err(())
} else {
Ok(w as u32)
}
}
}
/// Get the access specifier for this cursor's referent.
pub(crate) fn access_specifier(&self) -> CX_CXXAccessSpecifier {
unsafe { clang_getCXXAccessSpecifier(self.x) }
}
/// Is the cursor's referrent publically accessible in C++?
///
/// Returns true if self.access_specifier() is `CX_CXXPublic` or
/// `CX_CXXInvalidAccessSpecifier`.
pub(crate) fn public_accessible(&self) -> bool {
let access = self.access_specifier();
access == CX_CXXPublic || access == CX_CXXInvalidAccessSpecifier
}
/// Is this cursor's referent a field declaration that is marked as
/// `mutable`?
pub(crate) fn is_mutable_field(&self) -> bool {
unsafe { clang_CXXField_isMutable(self.x) != 0 }
}
/// Get the offset of the field represented by the Cursor.
pub(crate) fn offset_of_field(&self) -> Result<usize, LayoutError> {
let offset = unsafe { clang_Cursor_getOffsetOfField(self.x) };
if offset < 0 {
Err(LayoutError::from(offset as i32))
} else {
Ok(offset as usize)
}
}
/// Is this cursor's referent a member function that is declared `static`?
pub(crate) fn method_is_static(&self) -> bool {
unsafe { clang_CXXMethod_isStatic(self.x) != 0 }
}
/// Is this cursor's referent a member function that is declared `const`?
pub(crate) fn method_is_const(&self) -> bool {
unsafe { clang_CXXMethod_isConst(self.x) != 0 }
}
/// Is this cursor's referent a member function that is virtual?
pub(crate) fn method_is_virtual(&self) -> bool {
unsafe { clang_CXXMethod_isVirtual(self.x) != 0 }
}
/// Is this cursor's referent a member function that is pure virtual?
pub(crate) fn method_is_pure_virtual(&self) -> bool {
unsafe { clang_CXXMethod_isPureVirtual(self.x) != 0 }
}
/// Is this cursor's referent a struct or class with virtual members?
pub(crate) fn is_virtual_base(&self) -> bool {
unsafe { clang_isVirtualBase(self.x) != 0 }
}
/// Try to evaluate this cursor.
pub(crate) fn evaluate(&self) -> Option<EvalResult> {
EvalResult::new(*self)
}
/// Return the result type for this cursor
pub(crate) fn ret_type(&self) -> Option<Type> {
let rt = Type {
x: unsafe { clang_getCursorResultType(self.x) },
};
if rt.is_valid() {
Some(rt)
} else {
None
}
}
/// Gets the tokens that correspond to that cursor.
pub(crate) fn tokens(&self) -> RawTokens {
RawTokens::new(self)
}
/// Gets the tokens that correspond to that cursor as `cexpr` tokens.
pub(crate) fn cexpr_tokens(self) -> Vec<cexpr::token::Token> {
self.tokens()
.iter()
.filter_map(|token| token.as_cexpr_token())
.collect()
}
/// Obtain the real path name of a cursor of InclusionDirective kind.
///
/// Returns None if the cursor does not include a file, otherwise the file's full name
pub(crate) fn get_included_file_name(&self) -> Option<String> {
let file = unsafe { clang_sys::clang_getIncludedFile(self.x) };
if file.is_null() {
None
} else {
Some(unsafe {
cxstring_into_string(clang_sys::clang_getFileName(file))
})
}
}
}
/// A struct that owns the tokenizer result from a given cursor.
pub(crate) struct RawTokens<'a> {
cursor: &'a Cursor,
tu: CXTranslationUnit,
tokens: *mut CXToken,
token_count: c_uint,
}
impl<'a> RawTokens<'a> {
fn new(cursor: &'a Cursor) -> Self {
let mut tokens = ptr::null_mut();
let mut token_count = 0;
let range = cursor.extent();
let tu = unsafe { clang_Cursor_getTranslationUnit(cursor.x) };
unsafe { clang_tokenize(tu, range, &mut tokens, &mut token_count) };
Self {
cursor,
tu,
tokens,
token_count,
}
}
fn as_slice(&self) -> &[CXToken] {
if self.tokens.is_null() {
return &[];
}
unsafe { slice::from_raw_parts(self.tokens, self.token_count as usize) }
}
/// Get an iterator over these tokens.
pub(crate) fn iter(&self) -> ClangTokenIterator {
ClangTokenIterator {
tu: self.tu,
raw: self.as_slice().iter(),
}
}
}
impl<'a> Drop for RawTokens<'a> {
fn drop(&mut self) {
if !self.tokens.is_null() {
unsafe {
clang_disposeTokens(
self.tu,
self.tokens,
self.token_count as c_uint,
);
}
}
}
}
/// A raw clang token, that exposes only kind, spelling, and extent. This is a
/// slightly more convenient version of `CXToken` which owns the spelling
/// string and extent.
#[derive(Debug)]
pub(crate) struct ClangToken {
spelling: CXString,
/// The extent of the token. This is the same as the relevant member from
/// `CXToken`.
pub(crate) extent: CXSourceRange,
/// The kind of the token. This is the same as the relevant member from
/// `CXToken`.
pub(crate) kind: CXTokenKind,
}
impl ClangToken {
/// Get the token spelling, without being converted to utf-8.
pub(crate) fn spelling(&self) -> &[u8] {
let c_str = unsafe {
CStr::from_ptr(clang_getCString(self.spelling) as *const _)
};
c_str.to_bytes()
}
/// Converts a ClangToken to a `cexpr` token if possible.
pub(crate) fn as_cexpr_token(&self) -> Option<cexpr::token::Token> {
use cexpr::token;
let kind = match self.kind {
CXToken_Punctuation => token::Kind::Punctuation,
CXToken_Literal => token::Kind::Literal,
CXToken_Identifier => token::Kind::Identifier,
CXToken_Keyword => token::Kind::Keyword,
// NB: cexpr is not too happy about comments inside
// expressions, so we strip them down here.
CXToken_Comment => return None,
_ => {
warn!("Found unexpected token kind: {:?}", self);
return None;
}
};
Some(token::Token {
kind,
raw: self.spelling().to_vec().into_boxed_slice(),
})
}
}
impl Drop for ClangToken {
fn drop(&mut self) {
unsafe { clang_disposeString(self.spelling) }
}
}
/// An iterator over a set of Tokens.
pub(crate) struct ClangTokenIterator<'a> {
tu: CXTranslationUnit,
raw: slice::Iter<'a, CXToken>,
}
impl<'a> Iterator for ClangTokenIterator<'a> {
type Item = ClangToken;
fn next(&mut self) -> Option<Self::Item> {
let raw = self.raw.next()?;
unsafe {
let kind = clang_getTokenKind(*raw);