aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_syntax/src/ast
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_syntax/src/ast')
-rw-r--r--crates/ra_syntax/src/ast/expr_extensions.rs250
-rw-r--r--crates/ra_syntax/src/ast/extensions.rs300
2 files changed, 550 insertions, 0 deletions
diff --git a/crates/ra_syntax/src/ast/expr_extensions.rs b/crates/ra_syntax/src/ast/expr_extensions.rs
new file mode 100644
index 000000000..ddc26206f
--- /dev/null
+++ b/crates/ra_syntax/src/ast/expr_extensions.rs
@@ -0,0 +1,250 @@
1use crate::{
2 SyntaxToken, SyntaxElement, SmolStr,
3 ast::{self, AstNode, AstChildren, children, child_opt},
4 SyntaxKind::*
5};
6
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum ElseBranch<'a> {
9 Block(&'a ast::Block),
10 IfExpr(&'a ast::IfExpr),
11}
12
13impl ast::IfExpr {
14 pub fn then_branch(&self) -> Option<&ast::Block> {
15 self.blocks().nth(0)
16 }
17 pub fn else_branch(&self) -> Option<ElseBranch> {
18 let res = match self.blocks().nth(1) {
19 Some(block) => ElseBranch::Block(block),
20 None => {
21 let elif: &ast::IfExpr = child_opt(self)?;
22 ElseBranch::IfExpr(elif)
23 }
24 };
25 Some(res)
26 }
27
28 fn blocks(&self) -> AstChildren<ast::Block> {
29 children(self)
30 }
31}
32
33impl ast::RefExpr {
34 pub fn is_mut(&self) -> bool {
35 self.syntax().children_with_tokens().any(|n| n.kind() == MUT_KW)
36 }
37}
38
39#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
40pub enum PrefixOp {
41 /// The `*` operator for dereferencing
42 Deref,
43 /// The `!` operator for logical inversion
44 Not,
45 /// The `-` operator for negation
46 Neg,
47}
48
49impl ast::PrefixExpr {
50 pub fn op_kind(&self) -> Option<PrefixOp> {
51 match self.op_token()?.kind() {
52 STAR => Some(PrefixOp::Deref),
53 EXCL => Some(PrefixOp::Not),
54 MINUS => Some(PrefixOp::Neg),
55 _ => None,
56 }
57 }
58
59 pub fn op_token(&self) -> Option<SyntaxToken> {
60 self.syntax().first_child_or_token()?.as_token()
61 }
62}
63
64#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
65pub enum BinOp {
66 /// The `||` operator for boolean OR
67 BooleanOr,
68 /// The `&&` operator for boolean AND
69 BooleanAnd,
70 /// The `==` operator for equality testing
71 EqualityTest,
72 /// The `!=` operator for equality testing
73 NegatedEqualityTest,
74 /// The `<=` operator for lesser-equal testing
75 LesserEqualTest,
76 /// The `>=` operator for greater-equal testing
77 GreaterEqualTest,
78 /// The `<` operator for comparison
79 LesserTest,
80 /// The `>` operator for comparison
81 GreaterTest,
82 /// The `+` operator for addition
83 Addition,
84 /// The `*` operator for multiplication
85 Multiplication,
86 /// The `-` operator for subtraction
87 Subtraction,
88 /// The `/` operator for division
89 Division,
90 /// The `%` operator for remainder after division
91 Remainder,
92 /// The `<<` operator for left shift
93 LeftShift,
94 /// The `>>` operator for right shift
95 RightShift,
96 /// The `^` operator for bitwise XOR
97 BitwiseXor,
98 /// The `|` operator for bitwise OR
99 BitwiseOr,
100 /// The `&` operator for bitwise AND
101 BitwiseAnd,
102 /// The `..` operator for right-open ranges
103 RangeRightOpen,
104 /// The `..=` operator for right-closed ranges
105 RangeRightClosed,
106 /// The `=` operator for assignment
107 Assignment,
108 /// The `+=` operator for assignment after addition
109 AddAssign,
110 /// The `/=` operator for assignment after division
111 DivAssign,
112 /// The `*=` operator for assignment after multiplication
113 MulAssign,
114 /// The `%=` operator for assignment after remainders
115 RemAssign,
116 /// The `>>=` operator for assignment after shifting right
117 ShrAssign,
118 /// The `<<=` operator for assignment after shifting left
119 ShlAssign,
120 /// The `-=` operator for assignment after subtraction
121 SubAssign,
122 /// The `|=` operator for assignment after bitwise OR
123 BitOrAssign,
124 /// The `&=` operator for assignment after bitwise AND
125 BitAndAssign,
126 /// The `^=` operator for assignment after bitwise XOR
127 BitXorAssign,
128}
129
130impl ast::BinExpr {
131 fn op_details(&self) -> Option<(SyntaxToken, BinOp)> {
132 self.syntax().children_with_tokens().filter_map(|it| it.as_token()).find_map(|c| {
133 match c.kind() {
134 PIPEPIPE => Some((c, BinOp::BooleanOr)),
135 AMPAMP => Some((c, BinOp::BooleanAnd)),
136 EQEQ => Some((c, BinOp::EqualityTest)),
137 NEQ => Some((c, BinOp::NegatedEqualityTest)),
138 LTEQ => Some((c, BinOp::LesserEqualTest)),
139 GTEQ => Some((c, BinOp::GreaterEqualTest)),
140 L_ANGLE => Some((c, BinOp::LesserTest)),
141 R_ANGLE => Some((c, BinOp::GreaterTest)),
142 PLUS => Some((c, BinOp::Addition)),
143 STAR => Some((c, BinOp::Multiplication)),
144 MINUS => Some((c, BinOp::Subtraction)),
145 SLASH => Some((c, BinOp::Division)),
146 PERCENT => Some((c, BinOp::Remainder)),
147 SHL => Some((c, BinOp::LeftShift)),
148 SHR => Some((c, BinOp::RightShift)),
149 CARET => Some((c, BinOp::BitwiseXor)),
150 PIPE => Some((c, BinOp::BitwiseOr)),
151 AMP => Some((c, BinOp::BitwiseAnd)),
152 DOTDOT => Some((c, BinOp::RangeRightOpen)),
153 DOTDOTEQ => Some((c, BinOp::RangeRightClosed)),
154 EQ => Some((c, BinOp::Assignment)),
155 PLUSEQ => Some((c, BinOp::AddAssign)),
156 SLASHEQ => Some((c, BinOp::DivAssign)),
157 STAREQ => Some((c, BinOp::MulAssign)),
158 PERCENTEQ => Some((c, BinOp::RemAssign)),
159 SHREQ => Some((c, BinOp::ShrAssign)),
160 SHLEQ => Some((c, BinOp::ShlAssign)),
161 MINUSEQ => Some((c, BinOp::SubAssign)),
162 PIPEEQ => Some((c, BinOp::BitOrAssign)),
163 AMPEQ => Some((c, BinOp::BitAndAssign)),
164 CARETEQ => Some((c, BinOp::BitXorAssign)),
165 _ => None,
166 }
167 })
168 }
169
170 pub fn op_kind(&self) -> Option<BinOp> {
171 self.op_details().map(|t| t.1)
172 }
173
174 pub fn op_token(&self) -> Option<SyntaxToken> {
175 self.op_details().map(|t| t.0)
176 }
177
178 pub fn lhs(&self) -> Option<&ast::Expr> {
179 children(self).nth(0)
180 }
181
182 pub fn rhs(&self) -> Option<&ast::Expr> {
183 children(self).nth(1)
184 }
185
186 pub fn sub_exprs(&self) -> (Option<&ast::Expr>, Option<&ast::Expr>) {
187 let mut children = children(self);
188 let first = children.next();
189 let second = children.next();
190 (first, second)
191 }
192}
193
194#[derive(Clone, Debug, PartialEq, Eq, Hash)]
195pub enum LiteralFlavor {
196 String,
197 ByteString,
198 Char,
199 Byte,
200 IntNumber { suffix: Option<SmolStr> },
201 FloatNumber { suffix: Option<SmolStr> },
202 Bool,
203}
204
205impl ast::Literal {
206 pub fn token(&self) -> SyntaxToken {
207 match self.syntax().first_child_or_token().unwrap() {
208 SyntaxElement::Token(token) => token,
209 _ => unreachable!(),
210 }
211 }
212
213 pub fn flavor(&self) -> LiteralFlavor {
214 match self.token().kind() {
215 INT_NUMBER => {
216 let allowed_suffix_list = [
217 "isize", "i128", "i64", "i32", "i16", "i8", "usize", "u128", "u64", "u32",
218 "u16", "u8",
219 ];
220 let text = self.token().text().to_string();
221 let suffix = allowed_suffix_list
222 .iter()
223 .find(|&s| text.ends_with(s))
224 .map(|&suf| SmolStr::new(suf));
225 LiteralFlavor::IntNumber { suffix }
226 }
227 FLOAT_NUMBER => {
228 let allowed_suffix_list = ["f64", "f32"];
229 let text = self.token().text().to_string();
230 let suffix = allowed_suffix_list
231 .iter()
232 .find(|&s| text.ends_with(s))
233 .map(|&suf| SmolStr::new(suf));
234 LiteralFlavor::FloatNumber { suffix: suffix }
235 }
236 STRING | RAW_STRING => LiteralFlavor::String,
237 TRUE_KW | FALSE_KW => LiteralFlavor::Bool,
238 BYTE_STRING | RAW_BYTE_STRING => LiteralFlavor::ByteString,
239 CHAR => LiteralFlavor::Char,
240 BYTE => LiteralFlavor::Byte,
241 _ => unreachable!(),
242 }
243 }
244}
245
246impl ast::NamedField {
247 pub fn parent_struct_lit(&self) -> &ast::StructLit {
248 self.syntax().ancestors().find_map(ast::StructLit::cast).unwrap()
249 }
250}
diff --git a/crates/ra_syntax/src/ast/extensions.rs b/crates/ra_syntax/src/ast/extensions.rs
new file mode 100644
index 000000000..87592bfd8
--- /dev/null
+++ b/crates/ra_syntax/src/ast/extensions.rs
@@ -0,0 +1,300 @@
1use itertools::Itertools;
2
3use crate::{
4 SmolStr, SyntaxToken,
5 ast::{self, AstNode, children, child_opt},
6 SyntaxKind::*,
7};
8
9impl ast::Name {
10 pub fn text(&self) -> &SmolStr {
11 let ident = self.syntax().first_child_or_token().unwrap().as_token().unwrap();
12 ident.text()
13 }
14}
15
16impl ast::NameRef {
17 pub fn text(&self) -> &SmolStr {
18 let ident = self.syntax().first_child_or_token().unwrap().as_token().unwrap();
19 ident.text()
20 }
21}
22
23impl ast::Attr {
24 pub fn is_inner(&self) -> bool {
25 let tt = match self.value() {
26 None => return false,
27 Some(tt) => tt,
28 };
29
30 let prev = match tt.syntax().prev_sibling() {
31 None => return false,
32 Some(prev) => prev,
33 };
34
35 prev.kind() == EXCL
36 }
37
38 pub fn as_atom(&self) -> Option<SmolStr> {
39 let tt = self.value()?;
40 let (_bra, attr, _ket) = tt.syntax().children_with_tokens().collect_tuple()?;
41 if attr.kind() == IDENT {
42 Some(attr.as_token()?.text().clone())
43 } else {
44 None
45 }
46 }
47
48 pub fn as_call(&self) -> Option<(SmolStr, &ast::TokenTree)> {
49 let tt = self.value()?;
50 let (_bra, attr, args, _ket) = tt.syntax().children_with_tokens().collect_tuple()?;
51 let args = ast::TokenTree::cast(args.as_node()?)?;
52 if attr.kind() == IDENT {
53 Some((attr.as_token()?.text().clone(), args))
54 } else {
55 None
56 }
57 }
58
59 pub fn as_named(&self) -> Option<SmolStr> {
60 let tt = self.value()?;
61 let attr = tt.syntax().children_with_tokens().nth(1)?;
62 if attr.kind() == IDENT {
63 Some(attr.as_token()?.text().clone())
64 } else {
65 None
66 }
67 }
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum PathSegmentKind<'a> {
72 Name(&'a ast::NameRef),
73 SelfKw,
74 SuperKw,
75 CrateKw,
76}
77
78impl ast::PathSegment {
79 pub fn parent_path(&self) -> &ast::Path {
80 self.syntax()
81 .parent()
82 .and_then(ast::Path::cast)
83 .expect("segments are always nested in paths")
84 }
85
86 pub fn kind(&self) -> Option<PathSegmentKind> {
87 let res = if let Some(name_ref) = self.name_ref() {
88 PathSegmentKind::Name(name_ref)
89 } else {
90 match self.syntax().first_child_or_token()?.kind() {
91 SELF_KW => PathSegmentKind::SelfKw,
92 SUPER_KW => PathSegmentKind::SuperKw,
93 CRATE_KW => PathSegmentKind::CrateKw,
94 _ => return None,
95 }
96 };
97 Some(res)
98 }
99
100 pub fn has_colon_colon(&self) -> bool {
101 match self.syntax.first_child_or_token().map(|s| s.kind()) {
102 Some(COLONCOLON) => true,
103 _ => false,
104 }
105 }
106}
107
108impl ast::Path {
109 pub fn parent_path(&self) -> Option<&ast::Path> {
110 self.syntax().parent().and_then(ast::Path::cast)
111 }
112}
113
114impl ast::Module {
115 pub fn has_semi(&self) -> bool {
116 match self.syntax().last_child_or_token() {
117 None => false,
118 Some(node) => node.kind() == SEMI,
119 }
120 }
121}
122
123impl ast::UseTree {
124 pub fn has_star(&self) -> bool {
125 self.syntax().children_with_tokens().any(|it| it.kind() == STAR)
126 }
127}
128
129impl ast::UseTreeList {
130 pub fn parent_use_tree(&self) -> &ast::UseTree {
131 self.syntax()
132 .parent()
133 .and_then(ast::UseTree::cast)
134 .expect("UseTreeLists are always nested in UseTrees")
135 }
136}
137
138impl ast::ImplBlock {
139 pub fn target_type(&self) -> Option<&ast::TypeRef> {
140 match self.target() {
141 (Some(t), None) | (_, Some(t)) => Some(t),
142 _ => None,
143 }
144 }
145
146 pub fn target_trait(&self) -> Option<&ast::TypeRef> {
147 match self.target() {
148 (Some(t), Some(_)) => Some(t),
149 _ => None,
150 }
151 }
152
153 fn target(&self) -> (Option<&ast::TypeRef>, Option<&ast::TypeRef>) {
154 let mut types = children(self);
155 let first = types.next();
156 let second = types.next();
157 (first, second)
158 }
159}
160
161#[derive(Debug, Clone, PartialEq, Eq)]
162pub enum StructFlavor<'a> {
163 Tuple(&'a ast::PosFieldDefList),
164 Named(&'a ast::NamedFieldDefList),
165 Unit,
166}
167
168impl StructFlavor<'_> {
169 fn from_node<N: AstNode>(node: &N) -> StructFlavor {
170 if let Some(nfdl) = child_opt::<_, ast::NamedFieldDefList>(node) {
171 StructFlavor::Named(nfdl)
172 } else if let Some(pfl) = child_opt::<_, ast::PosFieldDefList>(node) {
173 StructFlavor::Tuple(pfl)
174 } else {
175 StructFlavor::Unit
176 }
177 }
178}
179
180impl ast::StructDef {
181 pub fn flavor(&self) -> StructFlavor {
182 StructFlavor::from_node(self)
183 }
184}
185
186impl ast::EnumVariant {
187 pub fn parent_enum(&self) -> &ast::EnumDef {
188 self.syntax()
189 .parent()
190 .and_then(|it| it.parent())
191 .and_then(ast::EnumDef::cast)
192 .expect("EnumVariants are always nested in Enums")
193 }
194 pub fn flavor(&self) -> StructFlavor {
195 StructFlavor::from_node(self)
196 }
197}
198
199impl ast::LetStmt {
200 pub fn has_semi(&self) -> bool {
201 match self.syntax().last_child_or_token() {
202 None => false,
203 Some(node) => node.kind() == SEMI,
204 }
205 }
206}
207
208impl ast::ExprStmt {
209 pub fn has_semi(&self) -> bool {
210 match self.syntax().last_child_or_token() {
211 None => false,
212 Some(node) => node.kind() == SEMI,
213 }
214 }
215}
216
217impl ast::RefPat {
218 pub fn is_mut(&self) -> bool {
219 self.syntax().children_with_tokens().any(|n| n.kind() == MUT_KW)
220 }
221}
222
223impl ast::BindPat {
224 pub fn is_mutable(&self) -> bool {
225 self.syntax().children_with_tokens().any(|n| n.kind() == MUT_KW)
226 }
227
228 pub fn is_ref(&self) -> bool {
229 self.syntax().children_with_tokens().any(|n| n.kind() == REF_KW)
230 }
231}
232
233impl ast::PointerType {
234 pub fn is_mut(&self) -> bool {
235 self.syntax().children_with_tokens().any(|n| n.kind() == MUT_KW)
236 }
237}
238
239impl ast::ReferenceType {
240 pub fn is_mut(&self) -> bool {
241 self.syntax().children_with_tokens().any(|n| n.kind() == MUT_KW)
242 }
243}
244
245#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
246pub enum SelfParamFlavor {
247 /// self
248 Owned,
249 /// &self
250 Ref,
251 /// &mut self
252 MutRef,
253}
254
255impl ast::SelfParam {
256 pub fn self_kw_token(&self) -> SyntaxToken {
257 self.syntax()
258 .children_with_tokens()
259 .filter_map(|it| it.as_token())
260 .find(|it| it.kind() == SELF_KW)
261 .expect("invalid tree: self param must have self")
262 }
263
264 pub fn flavor(&self) -> SelfParamFlavor {
265 let borrowed = self.syntax().children_with_tokens().any(|n| n.kind() == AMP);
266 if borrowed {
267 // check for a `mut` coming after the & -- `mut &self` != `&mut self`
268 if self
269 .syntax()
270 .children_with_tokens()
271 .skip_while(|n| n.kind() != AMP)
272 .any(|n| n.kind() == MUT_KW)
273 {
274 SelfParamFlavor::MutRef
275 } else {
276 SelfParamFlavor::Ref
277 }
278 } else {
279 SelfParamFlavor::Owned
280 }
281 }
282}
283
284impl ast::LifetimeParam {
285 pub fn lifetime_token(&self) -> Option<SyntaxToken> {
286 self.syntax()
287 .children_with_tokens()
288 .filter_map(|it| it.as_token())
289 .find(|it| it.kind() == LIFETIME)
290 }
291}
292
293impl ast::WherePred {
294 pub fn lifetime_token(&self) -> Option<SyntaxToken> {
295 self.syntax()
296 .children_with_tokens()
297 .filter_map(|it| it.as_token())
298 .find(|it| it.kind() == LIFETIME)
299 }
300}