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