1 //! Abstract Syntax Tree, layered on top of untyped `SyntaxNode`s
12 use std::marker::PhantomData;
15 syntax_node::{SyntaxNode, SyntaxNodeChildren, SyntaxToken},
20 expr_ext::{ArrayExprKind, BinOp, Effect, ElseBranch, LiteralKind, PrefixOp, RangeOp},
21 generated::{nodes::*, tokens::*},
23 AttrKind, FieldKind, Macro, NameLike, NameOrNameRef, PathSegmentKind, SelfParamKind,
24 SlicePatComponents, StructKind, TypeBoundKind, VisibilityKind,
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
35 fn can_cast(kind: SyntaxKind) -> bool
39 fn cast(syntax: SyntaxNode) -> Option<Self>
43 fn syntax(&self) -> &SyntaxNode;
44 fn clone_for_update(&self) -> Self
48 Self::cast(self.syntax().clone_for_update()).unwrap()
52 /// Like `AstNode`, but wraps tokens rather than interior nodes.
54 fn can_cast(token: SyntaxKind) -> bool
58 fn cast(syntax: SyntaxToken) -> Option<Self>
62 fn syntax(&self) -> &SyntaxToken;
64 fn text(&self) -> &str {
69 /// An iterator over `SyntaxNode` children of a particular AST type.
70 #[derive(Debug, Clone)]
71 pub struct AstChildren<N> {
72 inner: SyntaxNodeChildren,
76 impl<N> AstChildren<N> {
77 fn new(parent: &SyntaxNode) -> Self {
78 AstChildren { inner: parent.children(), ph: PhantomData }
82 impl<N: AstNode> Iterator for AstChildren<N> {
84 fn next(&mut self) -> Option<N> {
85 self.inner.find_map(N::cast)
90 use super::{AstChildren, AstNode, SyntaxKind, SyntaxNode, SyntaxToken};
92 pub(super) fn child<N: AstNode>(parent: &SyntaxNode) -> Option<N> {
93 parent.children().find_map(N::cast)
96 pub(super) fn children<N: AstNode>(parent: &SyntaxNode) -> AstChildren<N> {
97 AstChildren::new(parent)
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)
106 fn assert_ast_is_object_safe() {
107 fn _f(_: &dyn AstNode, _: &dyn NameOwner) {}
111 fn test_doc_comment_none() {
112 let file = SourceFile::parse(
120 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
121 assert!(module.doc_comment_text().is_none());
125 fn test_outer_doc_comment_of_items() {
126 let file = SourceFile::parse(
135 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
136 assert_eq!("doc", module.doc_comment_text().unwrap());
140 fn test_inner_doc_comment_of_items() {
141 let file = SourceFile::parse(
150 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
151 assert!(module.doc_comment_text().is_none());
155 fn test_doc_comment_of_statics() {
156 let file = SourceFile::parse(
159 static LEVELS: i32 = 0;
164 let st = file.syntax().descendants().find_map(Static::cast).unwrap();
165 assert_eq!("Number of levels", st.doc_comment_text().unwrap());
169 fn test_doc_comment_preserves_indents() {
170 let file = SourceFile::parse(
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());
188 fn test_doc_comment_preserves_newlines() {
189 let file = SourceFile::parse(
200 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
201 assert_eq!("this\nis\nmod\nfoo", module.doc_comment_text().unwrap());
205 fn test_doc_comment_single_line_block_strips_suffix() {
206 let file = SourceFile::parse(
208 /** this is mod foo*/
214 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
215 assert_eq!("this is mod foo", module.doc_comment_text().unwrap());
219 fn test_doc_comment_single_line_block_strips_suffix_whitespace() {
220 let file = SourceFile::parse(
222 /** this is mod foo */
228 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
229 assert_eq!("this is mod foo ", module.doc_comment_text().unwrap());
233 fn test_doc_comment_multi_line_block_strips_suffix() {
234 let file = SourceFile::parse(
246 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
248 " this\n is\n mod foo\n ",
249 module.doc_comment_text().unwrap()
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 {}",
260 let def = file.syntax().descendants().find_map(Struct::cast).unwrap();
262 "Representation of a Realm. \nIn the specification these are called Realm Records.",
263 def.doc_comment_text().unwrap()
268 fn test_four_slash_line_comment() {
269 let file = SourceFile::parse(
271 //// too many slashes to be a doc comment
278 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
279 assert_eq!("doc comment", module.doc_comment_text().unwrap());
283 fn test_where_predicates() {
284 fn assert_bound(text: &str, bound: Option<TypeBound>) {
285 assert_eq!(text, bound.unwrap().syntax().text().to_string());
288 let file = SourceFile::parse(
292 T: Clone + Copy + Debug + 'static,
294 Iterator::Item: 'a + Debug,
295 Iterator::Item: Debug + 'a,
296 <T as Iterator>::Item: Debug + 'a,
297 for<'a> F: Fn(&'a str)
303 let where_clause = file.syntax().descendants().find_map(WhereClause::cast).unwrap();
305 let mut predicates = where_clause.predicates();
307 let pred = predicates.next().unwrap();
308 let mut bounds = pred.type_bound_list().unwrap().bounds();
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());
318 let pred = predicates.next().unwrap();
319 let mut bounds = pred.type_bound_list().unwrap().bounds();
321 assert_eq!("'a", pred.lifetime().unwrap().lifetime_ident_token().unwrap().text());
323 assert_bound("'b", bounds.next());
324 assert_bound("'c", bounds.next());
326 let pred = predicates.next().unwrap();
327 let mut bounds = pred.type_bound_list().unwrap().bounds();
329 assert_eq!("Iterator::Item", pred.ty().unwrap().syntax().text().to_string());
330 assert_bound("'a", bounds.next());
332 let pred = predicates.next().unwrap();
333 let mut bounds = pred.type_bound_list().unwrap().bounds();
335 assert_eq!("Iterator::Item", pred.ty().unwrap().syntax().text().to_string());
336 assert_bound("Debug", bounds.next());
337 assert_bound("'a", bounds.next());
339 let pred = predicates.next().unwrap();
340 let mut bounds = pred.type_bound_list().unwrap().bounds();
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());
346 let pred = predicates.next().unwrap();
347 let mut bounds = pred.type_bound_list().unwrap().bounds();
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());