1 //! Abstract Syntax Tree, layered on top of untyped `SyntaxNode`s
10 pub mod edit_in_place;
13 use std::marker::PhantomData;
16 syntax_node::{SyntaxNode, SyntaxNodeChildren, SyntaxToken},
21 expr_ext::{ArrayExprKind, BinOp, Effect, ElseBranch, LiteralKind},
22 generated::{nodes::*, tokens::*},
24 AttrKind, AttrsOwnerNode, FieldKind, Macro, NameLike, NameOrNameRef, PathSegmentKind,
25 SelfParamKind, SlicePatComponents, StructKind, TypeBoundKind, VisibilityKind,
27 operators::{ArithOp, BinaryOp, CmpOp, LogicOp, RangeOp, UnaryOp, Ordering},
29 CommentKind, CommentPlacement, CommentShape, FormatSpecifier, HasFormatSpecifier, IsString,
33 ArgListOwner, AttrsOwner, CommentIter, DocCommentsOwner, GenericParamsOwner, LoopBodyOwner,
34 ModuleItemOwner, NameOwner, TypeBoundsOwner, VisibilityOwner,
38 /// The main trait to go from untyped `SyntaxNode` to a typed ast. The
39 /// conversion itself has zero runtime cost: ast and syntax nodes have exactly
40 /// the same representation: a pointer to the tree root and a pointer to the
43 fn can_cast(kind: SyntaxKind) -> bool
47 fn cast(syntax: SyntaxNode) -> Option<Self>
51 fn syntax(&self) -> &SyntaxNode;
52 fn clone_for_update(&self) -> Self
56 Self::cast(self.syntax().clone_for_update()).unwrap()
58 fn clone_subtree(&self) -> Self
62 Self::cast(self.syntax().clone_subtree()).unwrap()
66 /// Like `AstNode`, but wraps tokens rather than interior nodes.
68 fn can_cast(token: SyntaxKind) -> bool
72 fn cast(syntax: SyntaxToken) -> Option<Self>
76 fn syntax(&self) -> &SyntaxToken;
78 fn text(&self) -> &str {
83 /// An iterator over `SyntaxNode` children of a particular AST type.
84 #[derive(Debug, Clone)]
85 pub struct AstChildren<N> {
86 inner: SyntaxNodeChildren,
90 impl<N> AstChildren<N> {
91 fn new(parent: &SyntaxNode) -> Self {
92 AstChildren { inner: parent.children(), ph: PhantomData }
96 impl<N: AstNode> Iterator for AstChildren<N> {
98 fn next(&mut self) -> Option<N> {
99 self.inner.find_map(N::cast)
104 use super::{AstChildren, AstNode, SyntaxKind, SyntaxNode, SyntaxToken};
106 pub(super) fn child<N: AstNode>(parent: &SyntaxNode) -> Option<N> {
107 parent.children().find_map(N::cast)
110 pub(super) fn children<N: AstNode>(parent: &SyntaxNode) -> AstChildren<N> {
111 AstChildren::new(parent)
114 pub(super) fn token(parent: &SyntaxNode, kind: SyntaxKind) -> Option<SyntaxToken> {
115 parent.children_with_tokens().filter_map(|it| it.into_token()).find(|it| it.kind() == kind)
120 fn assert_ast_is_object_safe() {
121 fn _f(_: &dyn AstNode, _: &dyn NameOwner) {}
125 fn test_doc_comment_none() {
126 let file = SourceFile::parse(
134 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
135 assert!(module.doc_comments().doc_comment_text().is_none());
139 fn test_outer_doc_comment_of_items() {
140 let file = SourceFile::parse(
149 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
150 assert_eq!(" doc", module.doc_comments().doc_comment_text().unwrap());
154 fn test_inner_doc_comment_of_items() {
155 let file = SourceFile::parse(
164 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
165 assert!(module.doc_comments().doc_comment_text().is_none());
169 fn test_doc_comment_of_statics() {
170 let file = SourceFile::parse(
173 static LEVELS: i32 = 0;
178 let st = file.syntax().descendants().find_map(Static::cast).unwrap();
179 assert_eq!(" Number of levels", st.doc_comments().doc_comment_text().unwrap());
183 fn test_doc_comment_preserves_indents() {
184 let file = SourceFile::parse(
197 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
199 " doc1\n ```\n fn foo() {\n // ...\n }\n ```",
200 module.doc_comments().doc_comment_text().unwrap()
205 fn test_doc_comment_preserves_newlines() {
206 let file = SourceFile::parse(
217 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
218 assert_eq!(" this\n is\n mod\n foo", module.doc_comments().doc_comment_text().unwrap());
222 fn test_doc_comment_single_line_block_strips_suffix() {
223 let file = SourceFile::parse(
225 /** this is mod foo*/
231 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
232 assert_eq!(" this is mod foo", module.doc_comments().doc_comment_text().unwrap());
236 fn test_doc_comment_single_line_block_strips_suffix_whitespace() {
237 let file = SourceFile::parse(
239 /** this is mod foo */
245 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
246 assert_eq!(" this is mod foo ", module.doc_comments().doc_comment_text().unwrap());
250 fn test_doc_comment_multi_line_block_strips_suffix() {
251 let file = SourceFile::parse(
263 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
265 "\n this\n is\n mod foo\n ",
266 module.doc_comments().doc_comment_text().unwrap()
271 fn test_comments_preserve_trailing_whitespace() {
272 let file = SourceFile::parse(
273 "\n/// Representation of a Realm. \n/// In the specification these are called Realm Records.\nstruct Realm {}",
277 let def = file.syntax().descendants().find_map(Struct::cast).unwrap();
279 " Representation of a Realm. \n In the specification these are called Realm Records.",
280 def.doc_comments().doc_comment_text().unwrap()
285 fn test_four_slash_line_comment() {
286 let file = SourceFile::parse(
288 //// too many slashes to be a doc comment
295 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
296 assert_eq!(" doc comment", module.doc_comments().doc_comment_text().unwrap());
300 fn test_where_predicates() {
301 fn assert_bound(text: &str, bound: Option<TypeBound>) {
302 assert_eq!(text, bound.unwrap().syntax().text().to_string());
305 let file = SourceFile::parse(
309 T: Clone + Copy + Debug + 'static,
311 Iterator::Item: 'a + Debug,
312 Iterator::Item: Debug + 'a,
313 <T as Iterator>::Item: Debug + 'a,
314 for<'a> F: Fn(&'a str)
320 let where_clause = file.syntax().descendants().find_map(WhereClause::cast).unwrap();
322 let mut predicates = where_clause.predicates();
324 let pred = predicates.next().unwrap();
325 let mut bounds = pred.type_bound_list().unwrap().bounds();
327 assert!(pred.for_token().is_none());
328 assert!(pred.generic_param_list().is_none());
329 assert_eq!("T", pred.ty().unwrap().syntax().text().to_string());
330 assert_bound("Clone", bounds.next());
331 assert_bound("Copy", bounds.next());
332 assert_bound("Debug", bounds.next());
333 assert_bound("'static", bounds.next());
335 let pred = predicates.next().unwrap();
336 let mut bounds = pred.type_bound_list().unwrap().bounds();
338 assert_eq!("'a", pred.lifetime().unwrap().lifetime_ident_token().unwrap().text());
340 assert_bound("'b", bounds.next());
341 assert_bound("'c", bounds.next());
343 let pred = predicates.next().unwrap();
344 let mut bounds = pred.type_bound_list().unwrap().bounds();
346 assert_eq!("Iterator::Item", pred.ty().unwrap().syntax().text().to_string());
347 assert_bound("'a", bounds.next());
349 let pred = predicates.next().unwrap();
350 let mut bounds = pred.type_bound_list().unwrap().bounds();
352 assert_eq!("Iterator::Item", pred.ty().unwrap().syntax().text().to_string());
353 assert_bound("Debug", bounds.next());
354 assert_bound("'a", bounds.next());
356 let pred = predicates.next().unwrap();
357 let mut bounds = pred.type_bound_list().unwrap().bounds();
359 assert_eq!("<T as Iterator>::Item", pred.ty().unwrap().syntax().text().to_string());
360 assert_bound("Debug", bounds.next());
361 assert_bound("'a", bounds.next());
363 let pred = predicates.next().unwrap();
364 let mut bounds = pred.type_bound_list().unwrap().bounds();
366 assert!(pred.for_token().is_some());
367 assert_eq!("<'a>", pred.generic_param_list().unwrap().syntax().text().to_string());
368 assert_eq!("F", pred.ty().unwrap().syntax().text().to_string());
369 assert_bound("Fn(&'a str)", bounds.next());