]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/macro_expansion_tests.rs
f29d1443b921596852c39d5d9fdeea4dfec5a449
[rust.git] / crates / hir_def / src / macro_expansion_tests.rs
1 //! This module contains tests for macro expansion. Effectively, it covers `tt`,
2 //! `mbe`, `proc_macro_api` and `hir_expand` crates. This might seem like a
3 //! wrong architecture at the first glance, but is intentional.
4 //!
5 //! Physically, macro expansion process is intertwined with name resolution. You
6 //! can not expand *just* the syntax. So, to be able to write integration tests
7 //! of the "expand this code please" form, we have to do it after name
8 //! resolution. That is, in this crate. We *could* fake some dependencies and
9 //! write unit-tests (in fact, we used to do that), but that makes tests brittle
10 //! and harder to understand.
11
12 mod mbe;
13 mod builtin_fn_macro;
14
15 use std::{iter, ops::Range};
16
17 use base_db::{fixture::WithFixture, SourceDatabase};
18 use expect_test::Expect;
19 use hir_expand::{db::AstDatabase, InFile, MacroFile};
20 use stdx::format_to;
21 use syntax::{
22     ast::{self, edit::IndentLevel},
23     AstNode,
24     SyntaxKind::{COMMENT, EOF, IDENT, LIFETIME_IDENT},
25     SyntaxNode, T,
26 };
27
28 use crate::{
29     db::DefDatabase, nameres::ModuleSource, resolver::HasResolver, test_db::TestDB, AsMacroCall,
30 };
31
32 #[track_caller]
33 fn check(ra_fixture: &str, mut expect: Expect) {
34     let db = TestDB::with_files(ra_fixture);
35     let krate = db.crate_graph().iter().next().unwrap();
36     let def_map = db.crate_def_map(krate);
37     let local_id = def_map.root();
38     let module = def_map.module_id(local_id);
39     let resolver = module.resolver(&db);
40     let source = def_map[local_id].definition_source(&db);
41     let source_file = match source.value {
42         ModuleSource::SourceFile(it) => it,
43         ModuleSource::Module(_) | ModuleSource::BlockExpr(_) => panic!(),
44     };
45
46     let mut expansions = Vec::new();
47     for macro_call in source_file.syntax().descendants().filter_map(ast::MacroCall::cast) {
48         let macro_call = InFile::new(source.file_id, &macro_call);
49         let mut error = None;
50         let macro_call_id = macro_call
51             .as_call_id_with_errors(
52                 &db,
53                 krate,
54                 |path| resolver.resolve_path_as_macro(&db, &path),
55                 &mut |err| error = Some(err),
56             )
57             .unwrap()
58             .unwrap();
59         let macro_file = MacroFile { macro_call_id };
60         let mut expansion_result = db.parse_macro_expansion(macro_file);
61         expansion_result.err = expansion_result.err.or(error);
62         expansions.push((macro_call.value.clone(), expansion_result));
63     }
64
65     let mut expanded_text = source_file.to_string();
66     for (call, exp) in expansions.into_iter().rev() {
67         let mut tree = false;
68         let mut expect_errors = false;
69         for comment in call.syntax().children_with_tokens().filter(|it| it.kind() == COMMENT) {
70             tree |= comment.to_string().contains("+tree");
71             expect_errors |= comment.to_string().contains("+errors");
72         }
73
74         let mut expn_text = String::new();
75         if let Some(err) = exp.err {
76             format_to!(expn_text, "/* error: {} */", err);
77         }
78         if let Some((parse, _token_map)) = exp.value {
79             if expect_errors {
80                 assert!(!parse.errors().is_empty(), "no parse errors in expansion");
81                 for e in parse.errors() {
82                     format_to!(expn_text, "/* parse error: {} */\n", e);
83                 }
84             } else {
85                 assert!(
86                     parse.errors().is_empty(),
87                     "parse errors in expansion: \n{:#?}",
88                     parse.errors()
89                 );
90             }
91             let pp = pretty_print_macro_expansion(parse.syntax_node());
92             let indent = IndentLevel::from_node(call.syntax());
93             let pp = reindent(indent, pp);
94             format_to!(expn_text, "{}", pp);
95
96             if tree {
97                 let tree = format!("{:#?}", parse.syntax_node())
98                     .split_inclusive("\n")
99                     .map(|line| format!("// {}", line))
100                     .collect::<String>();
101                 format_to!(expn_text, "\n{}", tree)
102             }
103         }
104         let range = call.syntax().text_range();
105         let range: Range<usize> = range.into();
106         expanded_text.replace_range(range, &expn_text)
107     }
108
109     expect.indent(false);
110     expect.assert_eq(&expanded_text);
111 }
112
113 fn reindent(indent: IndentLevel, pp: String) -> String {
114     if !pp.contains('\n') {
115         return pp;
116     }
117     let mut lines = pp.split_inclusive('\n');
118     let mut res = lines.next().unwrap().to_string();
119     for line in lines {
120         if line.trim().is_empty() {
121             res.push_str(&line)
122         } else {
123             format_to!(res, "{}{}", indent, line)
124         }
125     }
126     res
127 }
128
129 fn pretty_print_macro_expansion(expn: SyntaxNode) -> String {
130     let mut res = String::new();
131     let mut prev_kind = EOF;
132     let mut indent_level = 0;
133     for token in iter::successors(expn.first_token(), |t| t.next_token()) {
134         let curr_kind = token.kind();
135         let space = match (prev_kind, curr_kind) {
136             _ if prev_kind.is_trivia() || curr_kind.is_trivia() => "",
137             (T!['{'], T!['}']) => "",
138             (T![=], _) | (_, T![=]) => " ",
139             (_, T!['{']) => " ",
140             (T![;] | T!['{'] | T!['}'], _) => "\n",
141             (_, T!['}']) => "\n",
142             (IDENT | LIFETIME_IDENT, IDENT | LIFETIME_IDENT) => " ",
143             _ if prev_kind.is_keyword() && curr_kind.is_keyword() => " ",
144             (IDENT, _) if curr_kind.is_keyword() => " ",
145             (_, IDENT) if prev_kind.is_keyword() => " ",
146             (T![>], IDENT) => " ",
147             (T![>], _) if curr_kind.is_keyword() => " ",
148             (T![->], _) | (_, T![->]) => " ",
149             (T![&&], _) | (_, T![&&]) => " ",
150             (T![,], _) => " ",
151             (T![:], IDENT | T!['(']) => " ",
152             (T![:], _) if curr_kind.is_keyword() => " ",
153             (T![fn], T!['(']) => "",
154             (T![']'], _) if curr_kind.is_keyword() => " ",
155             (T![']'], T![#]) => "\n",
156             _ if prev_kind.is_keyword() => " ",
157             _ => "",
158         };
159
160         match prev_kind {
161             T!['{'] => indent_level += 1,
162             T!['}'] => indent_level -= 1,
163             _ => (),
164         }
165
166         res.push_str(space);
167         if space == "\n" {
168             let level = if curr_kind == T!['}'] { indent_level - 1 } else { indent_level };
169             res.push_str(&"    ".repeat(level));
170         }
171         prev_kind = curr_kind;
172         format_to!(res, "{}", token)
173     }
174     res
175 }