]> git.lizzy.rs Git - rust.git/blob - crates/syntax/src/ast.rs
Merge #8051
[rust.git] / crates / syntax / src / ast.rs
1 //! Abstract Syntax Tree, layered on top of untyped `SyntaxNode`s
2
3 mod generated;
4 mod traits;
5 mod token_ext;
6 mod node_ext;
7 mod expr_ext;
8 pub mod edit;
9 pub mod edit_in_place;
10 pub mod make;
11
12 use std::marker::PhantomData;
13
14 use crate::{
15     syntax_node::{SyntaxNode, SyntaxNodeChildren, SyntaxToken},
16     SyntaxKind,
17 };
18
19 pub use self::{
20     expr_ext::{ArrayExprKind, BinOp, Effect, ElseBranch, LiteralKind, PrefixOp, RangeOp},
21     generated::{nodes::*, tokens::*},
22     node_ext::{
23         AttrKind, FieldKind, Macro, NameLike, NameOrNameRef, PathSegmentKind, SelfParamKind,
24         SlicePatComponents, StructKind, TypeBoundKind, VisibilityKind,
25     },
26     token_ext::*,
27     traits::*,
28 };
29
30 /// The main trait to go from untyped `SyntaxNode`  to a typed ast. The
31 /// conversion itself has zero runtime cost: ast and syntax nodes have exactly
32 /// the same representation: a pointer to the tree root and a pointer to the
33 /// node itself.
34 pub trait AstNode {
35     fn can_cast(kind: SyntaxKind) -> bool
36     where
37         Self: Sized;
38
39     fn cast(syntax: SyntaxNode) -> Option<Self>
40     where
41         Self: Sized;
42
43     fn syntax(&self) -> &SyntaxNode;
44     fn clone_for_update(&self) -> Self
45     where
46         Self: Sized,
47     {
48         Self::cast(self.syntax().clone_for_update()).unwrap()
49     }
50 }
51
52 /// Like `AstNode`, but wraps tokens rather than interior nodes.
53 pub trait AstToken {
54     fn can_cast(token: SyntaxKind) -> bool
55     where
56         Self: Sized;
57
58     fn cast(syntax: SyntaxToken) -> Option<Self>
59     where
60         Self: Sized;
61
62     fn syntax(&self) -> &SyntaxToken;
63
64     fn text(&self) -> &str {
65         self.syntax().text()
66     }
67 }
68
69 /// An iterator over `SyntaxNode` children of a particular AST type.
70 #[derive(Debug, Clone)]
71 pub struct AstChildren<N> {
72     inner: SyntaxNodeChildren,
73     ph: PhantomData<N>,
74 }
75
76 impl<N> AstChildren<N> {
77     fn new(parent: &SyntaxNode) -> Self {
78         AstChildren { inner: parent.children(), ph: PhantomData }
79     }
80 }
81
82 impl<N: AstNode> Iterator for AstChildren<N> {
83     type Item = N;
84     fn next(&mut self) -> Option<N> {
85         self.inner.find_map(N::cast)
86     }
87 }
88
89 mod support {
90     use super::{AstChildren, AstNode, SyntaxKind, SyntaxNode, SyntaxToken};
91
92     pub(super) fn child<N: AstNode>(parent: &SyntaxNode) -> Option<N> {
93         parent.children().find_map(N::cast)
94     }
95
96     pub(super) fn children<N: AstNode>(parent: &SyntaxNode) -> AstChildren<N> {
97         AstChildren::new(parent)
98     }
99
100     pub(super) fn token(parent: &SyntaxNode, kind: SyntaxKind) -> Option<SyntaxToken> {
101         parent.children_with_tokens().filter_map(|it| it.into_token()).find(|it| it.kind() == kind)
102     }
103 }
104
105 #[test]
106 fn assert_ast_is_object_safe() {
107     fn _f(_: &dyn AstNode, _: &dyn NameOwner) {}
108 }
109
110 #[test]
111 fn test_doc_comment_none() {
112     let file = SourceFile::parse(
113         r#"
114         // non-doc
115         mod foo {}
116         "#,
117     )
118     .ok()
119     .unwrap();
120     let module = file.syntax().descendants().find_map(Module::cast).unwrap();
121     assert!(module.doc_comment_text().is_none());
122 }
123
124 #[test]
125 fn test_outer_doc_comment_of_items() {
126     let file = SourceFile::parse(
127         r#"
128         /// doc
129         // non-doc
130         mod foo {}
131         "#,
132     )
133     .ok()
134     .unwrap();
135     let module = file.syntax().descendants().find_map(Module::cast).unwrap();
136     assert_eq!("doc", module.doc_comment_text().unwrap());
137 }
138
139 #[test]
140 fn test_inner_doc_comment_of_items() {
141     let file = SourceFile::parse(
142         r#"
143         //! doc
144         // non-doc
145         mod foo {}
146         "#,
147     )
148     .ok()
149     .unwrap();
150     let module = file.syntax().descendants().find_map(Module::cast).unwrap();
151     assert!(module.doc_comment_text().is_none());
152 }
153
154 #[test]
155 fn test_doc_comment_of_statics() {
156     let file = SourceFile::parse(
157         r#"
158         /// Number of levels
159         static LEVELS: i32 = 0;
160         "#,
161     )
162     .ok()
163     .unwrap();
164     let st = file.syntax().descendants().find_map(Static::cast).unwrap();
165     assert_eq!("Number of levels", st.doc_comment_text().unwrap());
166 }
167
168 #[test]
169 fn test_doc_comment_preserves_indents() {
170     let file = SourceFile::parse(
171         r#"
172         /// doc1
173         /// ```
174         /// fn foo() {
175         ///     // ...
176         /// }
177         /// ```
178         mod foo {}
179         "#,
180     )
181     .ok()
182     .unwrap();
183     let module = file.syntax().descendants().find_map(Module::cast).unwrap();
184     assert_eq!("doc1\n```\nfn foo() {\n    // ...\n}\n```", module.doc_comment_text().unwrap());
185 }
186
187 #[test]
188 fn test_doc_comment_preserves_newlines() {
189     let file = SourceFile::parse(
190         r#"
191         /// this
192         /// is
193         /// mod
194         /// foo
195         mod foo {}
196         "#,
197     )
198     .ok()
199     .unwrap();
200     let module = file.syntax().descendants().find_map(Module::cast).unwrap();
201     assert_eq!("this\nis\nmod\nfoo", module.doc_comment_text().unwrap());
202 }
203
204 #[test]
205 fn test_doc_comment_single_line_block_strips_suffix() {
206     let file = SourceFile::parse(
207         r#"
208         /** this is mod foo*/
209         mod foo {}
210         "#,
211     )
212     .ok()
213     .unwrap();
214     let module = file.syntax().descendants().find_map(Module::cast).unwrap();
215     assert_eq!("this is mod foo", module.doc_comment_text().unwrap());
216 }
217
218 #[test]
219 fn test_doc_comment_single_line_block_strips_suffix_whitespace() {
220     let file = SourceFile::parse(
221         r#"
222         /** this is mod foo */
223         mod foo {}
224         "#,
225     )
226     .ok()
227     .unwrap();
228     let module = file.syntax().descendants().find_map(Module::cast).unwrap();
229     assert_eq!("this is mod foo ", module.doc_comment_text().unwrap());
230 }
231
232 #[test]
233 fn test_doc_comment_multi_line_block_strips_suffix() {
234     let file = SourceFile::parse(
235         r#"
236         /**
237         this
238         is
239         mod foo
240         */
241         mod foo {}
242         "#,
243     )
244     .ok()
245     .unwrap();
246     let module = file.syntax().descendants().find_map(Module::cast).unwrap();
247     assert_eq!(
248         "        this\n        is\n        mod foo\n        ",
249         module.doc_comment_text().unwrap()
250     );
251 }
252
253 #[test]
254 fn test_comments_preserve_trailing_whitespace() {
255     let file = SourceFile::parse(
256         "\n/// Representation of a Realm.   \n/// In the specification these are called Realm Records.\nstruct Realm {}",
257     )
258     .ok()
259     .unwrap();
260     let def = file.syntax().descendants().find_map(Struct::cast).unwrap();
261     assert_eq!(
262         "Representation of a Realm.   \nIn the specification these are called Realm Records.",
263         def.doc_comment_text().unwrap()
264     );
265 }
266
267 #[test]
268 fn test_four_slash_line_comment() {
269     let file = SourceFile::parse(
270         r#"
271         //// too many slashes to be a doc comment
272         /// doc comment
273         mod foo {}
274         "#,
275     )
276     .ok()
277     .unwrap();
278     let module = file.syntax().descendants().find_map(Module::cast).unwrap();
279     assert_eq!("doc comment", module.doc_comment_text().unwrap());
280 }
281
282 #[test]
283 fn test_where_predicates() {
284     fn assert_bound(text: &str, bound: Option<TypeBound>) {
285         assert_eq!(text, bound.unwrap().syntax().text().to_string());
286     }
287
288     let file = SourceFile::parse(
289         r#"
290 fn foo()
291 where
292    T: Clone + Copy + Debug + 'static,
293    'a: 'b + 'c,
294    Iterator::Item: 'a + Debug,
295    Iterator::Item: Debug + 'a,
296    <T as Iterator>::Item: Debug + 'a,
297    for<'a> F: Fn(&'a str)
298 {}
299         "#,
300     )
301     .ok()
302     .unwrap();
303     let where_clause = file.syntax().descendants().find_map(WhereClause::cast).unwrap();
304
305     let mut predicates = where_clause.predicates();
306
307     let pred = predicates.next().unwrap();
308     let mut bounds = pred.type_bound_list().unwrap().bounds();
309
310     assert!(pred.for_token().is_none());
311     assert!(pred.generic_param_list().is_none());
312     assert_eq!("T", pred.ty().unwrap().syntax().text().to_string());
313     assert_bound("Clone", bounds.next());
314     assert_bound("Copy", bounds.next());
315     assert_bound("Debug", bounds.next());
316     assert_bound("'static", bounds.next());
317
318     let pred = predicates.next().unwrap();
319     let mut bounds = pred.type_bound_list().unwrap().bounds();
320
321     assert_eq!("'a", pred.lifetime().unwrap().lifetime_ident_token().unwrap().text());
322
323     assert_bound("'b", bounds.next());
324     assert_bound("'c", bounds.next());
325
326     let pred = predicates.next().unwrap();
327     let mut bounds = pred.type_bound_list().unwrap().bounds();
328
329     assert_eq!("Iterator::Item", pred.ty().unwrap().syntax().text().to_string());
330     assert_bound("'a", bounds.next());
331
332     let pred = predicates.next().unwrap();
333     let mut bounds = pred.type_bound_list().unwrap().bounds();
334
335     assert_eq!("Iterator::Item", pred.ty().unwrap().syntax().text().to_string());
336     assert_bound("Debug", bounds.next());
337     assert_bound("'a", bounds.next());
338
339     let pred = predicates.next().unwrap();
340     let mut bounds = pred.type_bound_list().unwrap().bounds();
341
342     assert_eq!("<T as Iterator>::Item", pred.ty().unwrap().syntax().text().to_string());
343     assert_bound("Debug", bounds.next());
344     assert_bound("'a", bounds.next());
345
346     let pred = predicates.next().unwrap();
347     let mut bounds = pred.type_bound_list().unwrap().bounds();
348
349     assert!(pred.for_token().is_some());
350     assert_eq!("<'a>", pred.generic_param_list().unwrap().syntax().text().to_string());
351     assert_eq!("F", pred.ty().unwrap().syntax().text().to_string());
352     assert_bound("Fn(&'a str)", bounds.next());
353 }