aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_syntax/src/ast.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_syntax/src/ast.rs')
-rw-r--r--crates/ra_syntax/src/ast.rs565
1 files changed, 16 insertions, 549 deletions
diff --git a/crates/ra_syntax/src/ast.rs b/crates/ra_syntax/src/ast.rs
index b0e0f8bf9..74a415bdd 100644
--- a/crates/ra_syntax/src/ast.rs
+++ b/crates/ra_syntax/src/ast.rs
@@ -2,21 +2,22 @@
2mod generated; 2mod generated;
3mod traits; 3mod traits;
4mod tokens; 4mod tokens;
5mod extensions;
6mod expr_extensions;
5 7
6use std::marker::PhantomData; 8use std::marker::PhantomData;
7 9
8use itertools::Itertools;
9
10use crate::{ 10use crate::{
11 syntax_node::{SyntaxNode, SyntaxNodeChildren, TreeArc, RaTypes, SyntaxToken, SyntaxElement}, 11 syntax_node::{SyntaxNode, SyntaxNodeChildren, TreeArc, RaTypes, SyntaxToken},
12 SmolStr, 12 SmolStr,
13 SyntaxKind::*,
14}; 13};
15 14
16pub use self::{ 15pub use self::{
17 generated::*, 16 generated::*,
18 traits::*, 17 traits::*,
19 tokens::*, 18 tokens::*,
19 extensions::{PathSegmentKind, StructFlavor, SelfParamFlavor},
20 expr_extensions::{ElseBranch, PrefixOp, BinOp, LiteralFlavor},
20}; 21};
21 22
22/// The main trait to go from untyped `SyntaxNode` to a typed ast. The 23/// The main trait to go from untyped `SyntaxNode` to a typed ast. The
@@ -32,6 +33,17 @@ pub trait AstNode:
32 fn syntax(&self) -> &SyntaxNode; 33 fn syntax(&self) -> &SyntaxNode;
33} 34}
34 35
36/// Like `AstNode`, but wraps tokens rather than interior nodes.
37pub trait AstToken<'a> {
38 fn cast(token: SyntaxToken<'a>) -> Option<Self>
39 where
40 Self: Sized;
41 fn syntax(&self) -> SyntaxToken<'a>;
42 fn text(&self) -> &'a SmolStr {
43 self.syntax().text()
44 }
45}
46
35#[derive(Debug)] 47#[derive(Debug)]
36pub struct AstChildren<'a, N> { 48pub struct AstChildren<'a, N> {
37 inner: SyntaxNodeChildren<'a>, 49 inner: SyntaxNodeChildren<'a>,
@@ -51,215 +63,6 @@ impl<'a, N: AstNode + 'a> Iterator for AstChildren<'a, N> {
51 } 63 }
52} 64}
53 65
54pub trait AstToken<'a> {
55 fn cast(token: SyntaxToken<'a>) -> Option<Self>
56 where
57 Self: Sized;
58 fn syntax(&self) -> SyntaxToken<'a>;
59 fn text(&self) -> &'a SmolStr {
60 self.syntax().text()
61 }
62}
63
64impl Attr {
65 pub fn is_inner(&self) -> bool {
66 let tt = match self.value() {
67 None => return false,
68 Some(tt) => tt,
69 };
70
71 let prev = match tt.syntax().prev_sibling() {
72 None => return false,
73 Some(prev) => prev,
74 };
75
76 prev.kind() == EXCL
77 }
78
79 pub fn as_atom(&self) -> Option<SmolStr> {
80 let tt = self.value()?;
81 let (_bra, attr, _ket) = tt.syntax().children_with_tokens().collect_tuple()?;
82 if attr.kind() == IDENT {
83 Some(attr.as_token()?.text().clone())
84 } else {
85 None
86 }
87 }
88
89 pub fn as_call(&self) -> Option<(SmolStr, &TokenTree)> {
90 let tt = self.value()?;
91 let (_bra, attr, args, _ket) = tt.syntax().children_with_tokens().collect_tuple()?;
92 let args = TokenTree::cast(args.as_node()?)?;
93 if attr.kind() == IDENT {
94 Some((attr.as_token()?.text().clone(), args))
95 } else {
96 None
97 }
98 }
99
100 pub fn as_named(&self) -> Option<SmolStr> {
101 let tt = self.value()?;
102 let attr = tt.syntax().children_with_tokens().nth(1)?;
103 if attr.kind() == IDENT {
104 Some(attr.as_token()?.text().clone())
105 } else {
106 None
107 }
108 }
109}
110
111impl Name {
112 pub fn text(&self) -> &SmolStr {
113 let ident = self.syntax().first_child_or_token().unwrap().as_token().unwrap();
114 ident.text()
115 }
116}
117
118impl NameRef {
119 pub fn text(&self) -> &SmolStr {
120 let ident = self.syntax().first_child_or_token().unwrap().as_token().unwrap();
121 ident.text()
122 }
123}
124
125impl ImplBlock {
126 pub fn target_type(&self) -> Option<&TypeRef> {
127 match self.target() {
128 (Some(t), None) | (_, Some(t)) => Some(t),
129 _ => None,
130 }
131 }
132
133 pub fn target_trait(&self) -> Option<&TypeRef> {
134 match self.target() {
135 (Some(t), Some(_)) => Some(t),
136 _ => None,
137 }
138 }
139
140 fn target(&self) -> (Option<&TypeRef>, Option<&TypeRef>) {
141 let mut types = children(self);
142 let first = types.next();
143 let second = types.next();
144 (first, second)
145 }
146}
147
148impl Module {
149 pub fn has_semi(&self) -> bool {
150 match self.syntax().last_child_or_token() {
151 None => false,
152 Some(node) => node.kind() == SEMI,
153 }
154 }
155}
156
157impl LetStmt {
158 pub fn has_semi(&self) -> bool {
159 match self.syntax().last_child_or_token() {
160 None => false,
161 Some(node) => node.kind() == SEMI,
162 }
163 }
164}
165
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub enum ElseBranch<'a> {
168 Block(&'a Block),
169 IfExpr(&'a IfExpr),
170}
171
172impl IfExpr {
173 pub fn then_branch(&self) -> Option<&Block> {
174 self.blocks().nth(0)
175 }
176 pub fn else_branch(&self) -> Option<ElseBranch> {
177 let res = match self.blocks().nth(1) {
178 Some(block) => ElseBranch::Block(block),
179 None => {
180 let elif: &IfExpr = child_opt(self)?;
181 ElseBranch::IfExpr(elif)
182 }
183 };
184 Some(res)
185 }
186
187 fn blocks(&self) -> AstChildren<Block> {
188 children(self)
189 }
190}
191
192impl ExprStmt {
193 pub fn has_semi(&self) -> bool {
194 match self.syntax().last_child_or_token() {
195 None => false,
196 Some(node) => node.kind() == SEMI,
197 }
198 }
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub enum PathSegmentKind<'a> {
203 Name(&'a NameRef),
204 SelfKw,
205 SuperKw,
206 CrateKw,
207}
208
209impl PathSegment {
210 pub fn parent_path(&self) -> &Path {
211 self.syntax().parent().and_then(Path::cast).expect("segments are always nested in paths")
212 }
213
214 pub fn kind(&self) -> Option<PathSegmentKind> {
215 let res = if let Some(name_ref) = self.name_ref() {
216 PathSegmentKind::Name(name_ref)
217 } else {
218 match self.syntax().first_child_or_token()?.kind() {
219 SELF_KW => PathSegmentKind::SelfKw,
220 SUPER_KW => PathSegmentKind::SuperKw,
221 CRATE_KW => PathSegmentKind::CrateKw,
222 _ => return None,
223 }
224 };
225 Some(res)
226 }
227
228 pub fn has_colon_colon(&self) -> bool {
229 match self.syntax.first_child_or_token().map(|s| s.kind()) {
230 Some(COLONCOLON) => true,
231 _ => false,
232 }
233 }
234}
235
236impl Path {
237 pub fn parent_path(&self) -> Option<&Path> {
238 self.syntax().parent().and_then(Path::cast)
239 }
240}
241
242impl UseTree {
243 pub fn has_star(&self) -> bool {
244 self.syntax().children_with_tokens().any(|it| it.kind() == STAR)
245 }
246}
247
248impl UseTreeList {
249 pub fn parent_use_tree(&self) -> &UseTree {
250 self.syntax()
251 .parent()
252 .and_then(UseTree::cast)
253 .expect("UseTreeLists are always nested in UseTrees")
254 }
255}
256
257impl RefPat {
258 pub fn is_mut(&self) -> bool {
259 self.syntax().children_with_tokens().any(|n| n.kind() == MUT_KW)
260 }
261}
262
263fn child_opt<P: AstNode, C: AstNode>(parent: &P) -> Option<&C> { 66fn child_opt<P: AstNode, C: AstNode>(parent: &P) -> Option<&C> {
264 children(parent).next() 67 children(parent).next()
265} 68}
@@ -268,342 +71,6 @@ fn children<P: AstNode, C: AstNode>(parent: &P) -> AstChildren<C> {
268 AstChildren::new(parent.syntax()) 71 AstChildren::new(parent.syntax())
269} 72}
270 73
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub enum StructFlavor<'a> {
273 Tuple(&'a PosFieldDefList),
274 Named(&'a NamedFieldDefList),
275 Unit,
276}
277
278impl StructFlavor<'_> {
279 fn from_node<N: AstNode>(node: &N) -> StructFlavor {
280 if let Some(nfdl) = child_opt::<_, NamedFieldDefList>(node) {
281 StructFlavor::Named(nfdl)
282 } else if let Some(pfl) = child_opt::<_, PosFieldDefList>(node) {
283 StructFlavor::Tuple(pfl)
284 } else {
285 StructFlavor::Unit
286 }
287 }
288}
289
290impl StructDef {
291 pub fn flavor(&self) -> StructFlavor {
292 StructFlavor::from_node(self)
293 }
294}
295
296impl EnumVariant {
297 pub fn parent_enum(&self) -> &EnumDef {
298 self.syntax()
299 .parent()
300 .and_then(|it| it.parent())
301 .and_then(EnumDef::cast)
302 .expect("EnumVariants are always nested in Enums")
303 }
304 pub fn flavor(&self) -> StructFlavor {
305 StructFlavor::from_node(self)
306 }
307}
308
309impl PointerType {
310 pub fn is_mut(&self) -> bool {
311 self.syntax().children_with_tokens().any(|n| n.kind() == MUT_KW)
312 }
313}
314
315impl ReferenceType {
316 pub fn is_mut(&self) -> bool {
317 self.syntax().children_with_tokens().any(|n| n.kind() == MUT_KW)
318 }
319}
320
321impl RefExpr {
322 pub fn is_mut(&self) -> bool {
323 self.syntax().children_with_tokens().any(|n| n.kind() == MUT_KW)
324 }
325}
326
327#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
328pub enum PrefixOp {
329 /// The `*` operator for dereferencing
330 Deref,
331 /// The `!` operator for logical inversion
332 Not,
333 /// The `-` operator for negation
334 Neg,
335}
336
337impl PrefixExpr {
338 pub fn op_kind(&self) -> Option<PrefixOp> {
339 match self.op_token()?.kind() {
340 STAR => Some(PrefixOp::Deref),
341 EXCL => Some(PrefixOp::Not),
342 MINUS => Some(PrefixOp::Neg),
343 _ => None,
344 }
345 }
346
347 pub fn op_token(&self) -> Option<SyntaxToken> {
348 self.syntax().first_child_or_token()?.as_token()
349 }
350}
351
352#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
353pub enum BinOp {
354 /// The `||` operator for boolean OR
355 BooleanOr,
356 /// The `&&` operator for boolean AND
357 BooleanAnd,
358 /// The `==` operator for equality testing
359 EqualityTest,
360 /// The `!=` operator for equality testing
361 NegatedEqualityTest,
362 /// The `<=` operator for lesser-equal testing
363 LesserEqualTest,
364 /// The `>=` operator for greater-equal testing
365 GreaterEqualTest,
366 /// The `<` operator for comparison
367 LesserTest,
368 /// The `>` operator for comparison
369 GreaterTest,
370 /// The `+` operator for addition
371 Addition,
372 /// The `*` operator for multiplication
373 Multiplication,
374 /// The `-` operator for subtraction
375 Subtraction,
376 /// The `/` operator for division
377 Division,
378 /// The `%` operator for remainder after division
379 Remainder,
380 /// The `<<` operator for left shift
381 LeftShift,
382 /// The `>>` operator for right shift
383 RightShift,
384 /// The `^` operator for bitwise XOR
385 BitwiseXor,
386 /// The `|` operator for bitwise OR
387 BitwiseOr,
388 /// The `&` operator for bitwise AND
389 BitwiseAnd,
390 /// The `..` operator for right-open ranges
391 RangeRightOpen,
392 /// The `..=` operator for right-closed ranges
393 RangeRightClosed,
394 /// The `=` operator for assignment
395 Assignment,
396 /// The `+=` operator for assignment after addition
397 AddAssign,
398 /// The `/=` operator for assignment after division
399 DivAssign,
400 /// The `*=` operator for assignment after multiplication
401 MulAssign,
402 /// The `%=` operator for assignment after remainders
403 RemAssign,
404 /// The `>>=` operator for assignment after shifting right
405 ShrAssign,
406 /// The `<<=` operator for assignment after shifting left
407 ShlAssign,
408 /// The `-=` operator for assignment after subtraction
409 SubAssign,
410 /// The `|=` operator for assignment after bitwise OR
411 BitOrAssign,
412 /// The `&=` operator for assignment after bitwise AND
413 BitAndAssign,
414 /// The `^=` operator for assignment after bitwise XOR
415 BitXorAssign,
416}
417
418impl BinExpr {
419 fn op_details(&self) -> Option<(SyntaxToken, BinOp)> {
420 self.syntax().children_with_tokens().filter_map(|it| it.as_token()).find_map(|c| {
421 match c.kind() {
422 PIPEPIPE => Some((c, BinOp::BooleanOr)),
423 AMPAMP => Some((c, BinOp::BooleanAnd)),
424 EQEQ => Some((c, BinOp::EqualityTest)),
425 NEQ => Some((c, BinOp::NegatedEqualityTest)),
426 LTEQ => Some((c, BinOp::LesserEqualTest)),
427 GTEQ => Some((c, BinOp::GreaterEqualTest)),
428 L_ANGLE => Some((c, BinOp::LesserTest)),
429 R_ANGLE => Some((c, BinOp::GreaterTest)),
430 PLUS => Some((c, BinOp::Addition)),
431 STAR => Some((c, BinOp::Multiplication)),
432 MINUS => Some((c, BinOp::Subtraction)),
433 SLASH => Some((c, BinOp::Division)),
434 PERCENT => Some((c, BinOp::Remainder)),
435 SHL => Some((c, BinOp::LeftShift)),
436 SHR => Some((c, BinOp::RightShift)),
437 CARET => Some((c, BinOp::BitwiseXor)),
438 PIPE => Some((c, BinOp::BitwiseOr)),
439 AMP => Some((c, BinOp::BitwiseAnd)),
440 DOTDOT => Some((c, BinOp::RangeRightOpen)),
441 DOTDOTEQ => Some((c, BinOp::RangeRightClosed)),
442 EQ => Some((c, BinOp::Assignment)),
443 PLUSEQ => Some((c, BinOp::AddAssign)),
444 SLASHEQ => Some((c, BinOp::DivAssign)),
445 STAREQ => Some((c, BinOp::MulAssign)),
446 PERCENTEQ => Some((c, BinOp::RemAssign)),
447 SHREQ => Some((c, BinOp::ShrAssign)),
448 SHLEQ => Some((c, BinOp::ShlAssign)),
449 MINUSEQ => Some((c, BinOp::SubAssign)),
450 PIPEEQ => Some((c, BinOp::BitOrAssign)),
451 AMPEQ => Some((c, BinOp::BitAndAssign)),
452 CARETEQ => Some((c, BinOp::BitXorAssign)),
453 _ => None,
454 }
455 })
456 }
457
458 pub fn op_kind(&self) -> Option<BinOp> {
459 self.op_details().map(|t| t.1)
460 }
461
462 pub fn op_token(&self) -> Option<SyntaxToken> {
463 self.op_details().map(|t| t.0)
464 }
465
466 pub fn lhs(&self) -> Option<&Expr> {
467 children(self).nth(0)
468 }
469
470 pub fn rhs(&self) -> Option<&Expr> {
471 children(self).nth(1)
472 }
473
474 pub fn sub_exprs(&self) -> (Option<&Expr>, Option<&Expr>) {
475 let mut children = children(self);
476 let first = children.next();
477 let second = children.next();
478 (first, second)
479 }
480}
481
482#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
483pub enum SelfParamFlavor {
484 /// self
485 Owned,
486 /// &self
487 Ref,
488 /// &mut self
489 MutRef,
490}
491
492impl SelfParam {
493 pub fn self_kw_token(&self) -> SyntaxToken {
494 self.syntax()
495 .children_with_tokens()
496 .filter_map(|it| it.as_token())
497 .find(|it| it.kind() == SELF_KW)
498 .expect("invalid tree: self param must have self")
499 }
500
501 pub fn flavor(&self) -> SelfParamFlavor {
502 let borrowed = self.syntax().children_with_tokens().any(|n| n.kind() == AMP);
503 if borrowed {
504 // check for a `mut` coming after the & -- `mut &self` != `&mut self`
505 if self
506 .syntax()
507 .children_with_tokens()
508 .skip_while(|n| n.kind() != AMP)
509 .any(|n| n.kind() == MUT_KW)
510 {
511 SelfParamFlavor::MutRef
512 } else {
513 SelfParamFlavor::Ref
514 }
515 } else {
516 SelfParamFlavor::Owned
517 }
518 }
519}
520
521#[derive(Clone, Debug, PartialEq, Eq, Hash)]
522pub enum LiteralFlavor {
523 String,
524 ByteString,
525 Char,
526 Byte,
527 IntNumber { suffix: Option<SmolStr> },
528 FloatNumber { suffix: Option<SmolStr> },
529 Bool,
530}
531
532impl Literal {
533 pub fn token(&self) -> SyntaxToken {
534 match self.syntax().first_child_or_token().unwrap() {
535 SyntaxElement::Token(token) => token,
536 _ => unreachable!(),
537 }
538 }
539
540 pub fn flavor(&self) -> LiteralFlavor {
541 match self.token().kind() {
542 INT_NUMBER => {
543 let allowed_suffix_list = [
544 "isize", "i128", "i64", "i32", "i16", "i8", "usize", "u128", "u64", "u32",
545 "u16", "u8",
546 ];
547 let text = self.token().text().to_string();
548 let suffix = allowed_suffix_list
549 .iter()
550 .find(|&s| text.ends_with(s))
551 .map(|&suf| SmolStr::new(suf));
552 LiteralFlavor::IntNumber { suffix }
553 }
554 FLOAT_NUMBER => {
555 let allowed_suffix_list = ["f64", "f32"];
556 let text = self.token().text().to_string();
557 let suffix = allowed_suffix_list
558 .iter()
559 .find(|&s| text.ends_with(s))
560 .map(|&suf| SmolStr::new(suf));
561 LiteralFlavor::FloatNumber { suffix: suffix }
562 }
563 STRING | RAW_STRING => LiteralFlavor::String,
564 TRUE_KW | FALSE_KW => LiteralFlavor::Bool,
565 BYTE_STRING | RAW_BYTE_STRING => LiteralFlavor::ByteString,
566 CHAR => LiteralFlavor::Char,
567 BYTE => LiteralFlavor::Byte,
568 _ => unreachable!(),
569 }
570 }
571}
572
573impl NamedField {
574 pub fn parent_struct_lit(&self) -> &StructLit {
575 self.syntax().ancestors().find_map(StructLit::cast).unwrap()
576 }
577}
578
579impl BindPat {
580 pub fn is_mutable(&self) -> bool {
581 self.syntax().children_with_tokens().any(|n| n.kind() == MUT_KW)
582 }
583
584 pub fn is_ref(&self) -> bool {
585 self.syntax().children_with_tokens().any(|n| n.kind() == REF_KW)
586 }
587}
588
589impl LifetimeParam {
590 pub fn lifetime_token(&self) -> Option<SyntaxToken> {
591 self.syntax()
592 .children_with_tokens()
593 .filter_map(|it| it.as_token())
594 .find(|it| it.kind() == LIFETIME)
595 }
596}
597
598impl WherePred {
599 pub fn lifetime_token(&self) -> Option<SyntaxToken> {
600 self.syntax()
601 .children_with_tokens()
602 .filter_map(|it| it.as_token())
603 .find(|it| it.kind() == LIFETIME)
604 }
605}
606
607#[test] 74#[test]
608fn test_doc_comment_none() { 75fn test_doc_comment_none() {
609 let file = SourceFile::parse( 76 let file = SourceFile::parse(