1 //! Abstract Syntax Tree, layered on top of untyped `SyntaxNode`s
11 use std::marker::PhantomData;
14 syntax_node::{SyntaxNode, SyntaxNodeChildren, SyntaxToken},
19 expr_ext::{ArrayExprKind, BinOp, Effect, ElseBranch, LiteralKind, PrefixOp, RangeOp},
20 generated::{nodes::*, tokens::*},
22 AttrKind, FieldKind, Macro, NameLike, NameOrNameRef, PathSegmentKind, SelfParamKind,
23 SlicePatComponents, StructKind, TypeBoundKind, VisibilityKind,
29 /// The main trait to go from untyped `SyntaxNode` to a typed ast. The
30 /// conversion itself has zero runtime cost: ast and syntax nodes have exactly
31 /// the same representation: a pointer to the tree root and a pointer to the
34 fn can_cast(kind: SyntaxKind) -> bool
38 fn cast(syntax: SyntaxNode) -> Option<Self>
42 fn syntax(&self) -> &SyntaxNode;
45 /// Like `AstNode`, but wraps tokens rather than interior nodes.
47 fn can_cast(token: SyntaxKind) -> bool
51 fn cast(syntax: SyntaxToken) -> Option<Self>
55 fn syntax(&self) -> &SyntaxToken;
57 fn text(&self) -> &str {
62 /// An iterator over `SyntaxNode` children of a particular AST type.
63 #[derive(Debug, Clone)]
64 pub struct AstChildren<N> {
65 inner: SyntaxNodeChildren,
69 impl<N> AstChildren<N> {
70 fn new(parent: &SyntaxNode) -> Self {
71 AstChildren { inner: parent.children(), ph: PhantomData }
75 impl<N: AstNode> Iterator for AstChildren<N> {
77 fn next(&mut self) -> Option<N> {
78 self.inner.find_map(N::cast)
83 use super::{AstChildren, AstNode, SyntaxKind, SyntaxNode, SyntaxToken};
85 pub(super) fn child<N: AstNode>(parent: &SyntaxNode) -> Option<N> {
86 parent.children().find_map(N::cast)
89 pub(super) fn children<N: AstNode>(parent: &SyntaxNode) -> AstChildren<N> {
90 AstChildren::new(parent)
93 pub(super) fn token(parent: &SyntaxNode, kind: SyntaxKind) -> Option<SyntaxToken> {
94 parent.children_with_tokens().filter_map(|it| it.into_token()).find(|it| it.kind() == kind)
99 fn assert_ast_is_object_safe() {
100 fn _f(_: &dyn AstNode, _: &dyn NameOwner) {}
104 fn test_doc_comment_none() {
105 let file = SourceFile::parse(
113 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
114 assert!(module.doc_comment_text().is_none());
118 fn test_outer_doc_comment_of_items() {
119 let file = SourceFile::parse(
128 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
129 assert_eq!("doc", module.doc_comment_text().unwrap());
133 fn test_inner_doc_comment_of_items() {
134 let file = SourceFile::parse(
143 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
144 assert!(module.doc_comment_text().is_none());
148 fn test_doc_comment_of_statics() {
149 let file = SourceFile::parse(
152 static LEVELS: i32 = 0;
157 let st = file.syntax().descendants().find_map(Static::cast).unwrap();
158 assert_eq!("Number of levels", st.doc_comment_text().unwrap());
162 fn test_doc_comment_preserves_indents() {
163 let file = SourceFile::parse(
176 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
177 assert_eq!("doc1\n```\nfn foo() {\n // ...\n}\n```", module.doc_comment_text().unwrap());
181 fn test_doc_comment_preserves_newlines() {
182 let file = SourceFile::parse(
193 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
194 assert_eq!("this\nis\nmod\nfoo", module.doc_comment_text().unwrap());
198 fn test_doc_comment_single_line_block_strips_suffix() {
199 let file = SourceFile::parse(
201 /** this is mod foo*/
207 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
208 assert_eq!("this is mod foo", module.doc_comment_text().unwrap());
212 fn test_doc_comment_single_line_block_strips_suffix_whitespace() {
213 let file = SourceFile::parse(
215 /** this is mod foo */
221 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
222 assert_eq!("this is mod foo ", module.doc_comment_text().unwrap());
226 fn test_doc_comment_multi_line_block_strips_suffix() {
227 let file = SourceFile::parse(
239 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
241 " this\n is\n mod foo\n ",
242 module.doc_comment_text().unwrap()
247 fn test_comments_preserve_trailing_whitespace() {
248 let file = SourceFile::parse(
249 "\n/// Representation of a Realm. \n/// In the specification these are called Realm Records.\nstruct Realm {}",
253 let def = file.syntax().descendants().find_map(Struct::cast).unwrap();
255 "Representation of a Realm. \nIn the specification these are called Realm Records.",
256 def.doc_comment_text().unwrap()
261 fn test_four_slash_line_comment() {
262 let file = SourceFile::parse(
264 //// too many slashes to be a doc comment
271 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
272 assert_eq!("doc comment", module.doc_comment_text().unwrap());
276 fn test_where_predicates() {
277 fn assert_bound(text: &str, bound: Option<TypeBound>) {
278 assert_eq!(text, bound.unwrap().syntax().text().to_string());
281 let file = SourceFile::parse(
285 T: Clone + Copy + Debug + 'static,
287 Iterator::Item: 'a + Debug,
288 Iterator::Item: Debug + 'a,
289 <T as Iterator>::Item: Debug + 'a,
290 for<'a> F: Fn(&'a str)
296 let where_clause = file.syntax().descendants().find_map(WhereClause::cast).unwrap();
298 let mut predicates = where_clause.predicates();
300 let pred = predicates.next().unwrap();
301 let mut bounds = pred.type_bound_list().unwrap().bounds();
303 assert!(pred.for_token().is_none());
304 assert!(pred.generic_param_list().is_none());
305 assert_eq!("T", pred.ty().unwrap().syntax().text().to_string());
306 assert_bound("Clone", bounds.next());
307 assert_bound("Copy", bounds.next());
308 assert_bound("Debug", bounds.next());
309 assert_bound("'static", bounds.next());
311 let pred = predicates.next().unwrap();
312 let mut bounds = pred.type_bound_list().unwrap().bounds();
314 assert_eq!("'a", pred.lifetime().unwrap().lifetime_ident_token().unwrap().text());
316 assert_bound("'b", bounds.next());
317 assert_bound("'c", bounds.next());
319 let pred = predicates.next().unwrap();
320 let mut bounds = pred.type_bound_list().unwrap().bounds();
322 assert_eq!("Iterator::Item", pred.ty().unwrap().syntax().text().to_string());
323 assert_bound("'a", bounds.next());
325 let pred = predicates.next().unwrap();
326 let mut bounds = pred.type_bound_list().unwrap().bounds();
328 assert_eq!("Iterator::Item", pred.ty().unwrap().syntax().text().to_string());
329 assert_bound("Debug", bounds.next());
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!("<T as 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!(pred.for_token().is_some());
343 assert_eq!("<'a>", pred.generic_param_list().unwrap().syntax().text().to_string());
344 assert_eq!("F", pred.ty().unwrap().syntax().text().to_string());
345 assert_bound("Fn(&'a str)", bounds.next());