]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/macro_expansion_tests.rs
internal: move derived tests to the unified macro infra
[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 mod builtin_derive_macro;
15
16 use std::{iter, ops::Range};
17
18 use base_db::{fixture::WithFixture, SourceDatabase};
19 use expect_test::Expect;
20 use hir_expand::{db::AstDatabase, InFile, MacroFile};
21 use stdx::format_to;
22 use syntax::{
23     ast::{self, edit::IndentLevel},
24     AstNode,
25     SyntaxKind::{COMMENT, EOF, IDENT, LIFETIME_IDENT},
26     SyntaxNode, T,
27 };
28
29 use crate::{
30     db::DefDatabase, nameres::ModuleSource, resolver::HasResolver, src::HasSource, test_db::TestDB,
31     AsMacroCall, Lookup,
32 };
33
34 #[track_caller]
35 fn check(ra_fixture: &str, mut expect: Expect) {
36     let db = TestDB::with_files(ra_fixture);
37     let krate = db.crate_graph().iter().next().unwrap();
38     let def_map = db.crate_def_map(krate);
39     let local_id = def_map.root();
40     let module = def_map.module_id(local_id);
41     let resolver = module.resolver(&db);
42     let source = def_map[local_id].definition_source(&db);
43     let source_file = match source.value {
44         ModuleSource::SourceFile(it) => it,
45         ModuleSource::Module(_) | ModuleSource::BlockExpr(_) => panic!(),
46     };
47
48     // What we want to do is to replace all macros (fn-like, derive, attr) with
49     // their expansions. Turns out, we don't actually store enough information
50     // to do this precisely though! Specifically, if a macro expands to nothing,
51     // it leaves zero traces in def-map, so we can't get its expansion after the
52     // fact.
53     //
54     // This is the usual
55     // <https://github.com/rust-analyzer/rust-analyzer/issues/3407>
56     // resolve/record tension!
57     //
58     // So here we try to do a resolve, which is necessary a heuristic. For macro
59     // calls, we use `as_call_id_with_errors`. For derives, we look at the impls
60     // in the module and assume that, if impls's source is a different
61     // `HirFileId`, than it came from macro expansion.
62
63     let mut expansions = Vec::new();
64     for macro_call in source_file.syntax().descendants().filter_map(ast::MacroCall::cast) {
65         let macro_call = InFile::new(source.file_id, &macro_call);
66         let mut error = None;
67         let macro_call_id = macro_call
68             .as_call_id_with_errors(
69                 &db,
70                 krate,
71                 |path| resolver.resolve_path_as_macro(&db, &path),
72                 &mut |err| error = Some(err),
73             )
74             .unwrap()
75             .unwrap();
76         let macro_file = MacroFile { macro_call_id };
77         let mut expansion_result = db.parse_macro_expansion(macro_file);
78         expansion_result.err = expansion_result.err.or(error);
79         expansions.push((macro_call.value.clone(), expansion_result));
80     }
81
82     let mut expanded_text = source_file.to_string();
83
84     for (call, exp) in expansions.into_iter().rev() {
85         let mut tree = false;
86         let mut expect_errors = false;
87         for comment in call.syntax().children_with_tokens().filter(|it| it.kind() == COMMENT) {
88             tree |= comment.to_string().contains("+tree");
89             expect_errors |= comment.to_string().contains("+errors");
90         }
91
92         let mut expn_text = String::new();
93         if let Some(err) = exp.err {
94             format_to!(expn_text, "/* error: {} */", err);
95         }
96         if let Some((parse, _token_map)) = exp.value {
97             if expect_errors {
98                 assert!(!parse.errors().is_empty(), "no parse errors in expansion");
99                 for e in parse.errors() {
100                     format_to!(expn_text, "/* parse error: {} */\n", e);
101                 }
102             } else {
103                 assert!(
104                     parse.errors().is_empty(),
105                     "parse errors in expansion: \n{:#?}",
106                     parse.errors()
107                 );
108             }
109             let pp = pretty_print_macro_expansion(parse.syntax_node());
110             let indent = IndentLevel::from_node(call.syntax());
111             let pp = reindent(indent, pp);
112             format_to!(expn_text, "{}", pp);
113
114             if tree {
115                 let tree = format!("{:#?}", parse.syntax_node())
116                     .split_inclusive("\n")
117                     .map(|line| format!("// {}", line))
118                     .collect::<String>();
119                 format_to!(expn_text, "\n{}", tree)
120             }
121         }
122         let range = call.syntax().text_range();
123         let range: Range<usize> = range.into();
124         expanded_text.replace_range(range, &expn_text)
125     }
126
127     for impl_id in def_map[local_id].scope.impls() {
128         let src = impl_id.lookup(&db).source(&db);
129         if src.file_id.is_builtin_derive(&db).is_some() {
130             let pp = pretty_print_macro_expansion(src.value.syntax().clone());
131             format_to!(expanded_text, "\n{}", pp)
132         }
133     }
134
135     expect.indent(false);
136     expect.assert_eq(&expanded_text);
137 }
138
139 fn reindent(indent: IndentLevel, pp: String) -> String {
140     if !pp.contains('\n') {
141         return pp;
142     }
143     let mut lines = pp.split_inclusive('\n');
144     let mut res = lines.next().unwrap().to_string();
145     for line in lines {
146         if line.trim().is_empty() {
147             res.push_str(&line)
148         } else {
149             format_to!(res, "{}{}", indent, line)
150         }
151     }
152     res
153 }
154
155 fn pretty_print_macro_expansion(expn: SyntaxNode) -> String {
156     let mut res = String::new();
157     let mut prev_kind = EOF;
158     let mut indent_level = 0;
159     for token in iter::successors(expn.first_token(), |t| t.next_token()) {
160         let curr_kind = token.kind();
161         let space = match (prev_kind, curr_kind) {
162             _ if prev_kind.is_trivia() || curr_kind.is_trivia() => "",
163             (T!['{'], T!['}']) => "",
164             (T![=], _) | (_, T![=]) => " ",
165             (_, T!['{']) => " ",
166             (T![;] | T!['{'] | T!['}'], _) => "\n",
167             (_, T!['}']) => "\n",
168             (IDENT | LIFETIME_IDENT, IDENT | LIFETIME_IDENT) => " ",
169             _ if prev_kind.is_keyword() && curr_kind.is_keyword() => " ",
170             (IDENT, _) if curr_kind.is_keyword() => " ",
171             (_, IDENT) if prev_kind.is_keyword() => " ",
172             (T![>], IDENT) => " ",
173             (T![>], _) if curr_kind.is_keyword() => " ",
174             (T![->], _) | (_, T![->]) => " ",
175             (T![&&], _) | (_, T![&&]) => " ",
176             (T![,], _) => " ",
177             (T![:], IDENT | T!['(']) => " ",
178             (T![:], _) if curr_kind.is_keyword() => " ",
179             (T![fn], T!['(']) => "",
180             (T![']'], _) if curr_kind.is_keyword() => " ",
181             (T![']'], T![#]) => "\n",
182             _ if prev_kind.is_keyword() => " ",
183             _ => "",
184         };
185
186         match prev_kind {
187             T!['{'] => indent_level += 1,
188             T!['}'] => indent_level -= 1,
189             _ => (),
190         }
191
192         res.push_str(space);
193         if space == "\n" {
194             let level = if curr_kind == T!['}'] { indent_level - 1 } else { indent_level };
195             res.push_str(&"    ".repeat(level));
196         }
197         prev_kind = curr_kind;
198         format_to!(res, "{}", token)
199     }
200     res
201 }