]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/macro_expansion_tests.rs
move test
[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::{self, 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 fn check(ra_fixture: &str, expect: Expect) {
32     let db = TestDB::with_files(ra_fixture);
33     let krate = db.crate_graph().iter().next().unwrap();
34     let def_map = db.crate_def_map(krate);
35     let local_id = def_map.root();
36     let module = def_map.module_id(local_id);
37     let resolver = module.resolver(&db);
38     let source = def_map[local_id].definition_source(&db);
39     let source_file = match source.value {
40         ModuleSource::SourceFile(it) => it,
41         ModuleSource::Module(_) | ModuleSource::BlockExpr(_) => panic!(),
42     };
43
44     let mut expansions = Vec::new();
45     for macro_call in source_file.syntax().descendants().filter_map(ast::MacroCall::cast) {
46         let macro_call = InFile::new(source.file_id, &macro_call);
47         let macro_call_id = macro_call
48             .as_call_id_with_errors(
49                 &db,
50                 krate,
51                 |path| resolver.resolve_path_as_macro(&db, &path),
52                 &mut |err| panic!("{}", err),
53             )
54             .unwrap()
55             .unwrap();
56         let macro_file = MacroFile { macro_call_id };
57         let expansion_result = db.parse_macro_expansion(macro_file);
58         expansions.push((macro_call.value.clone(), expansion_result));
59     }
60
61     let mut expanded_text = source_file.to_string();
62     for (call, exp) in expansions.into_iter().rev() {
63         let mut expn_text = String::new();
64         if let Some(err) = exp.err {
65             format_to!(expn_text, "/* error: {} */", err);
66         }
67         if let Some((parse, _token_map)) = exp.value {
68             let pp = pretty_print_macro_expansion(parse.syntax_node());
69             let indent = IndentLevel::from_node(call.syntax());
70             let pp = reindent(indent, pp);
71             format_to!(expn_text, "{}", pp);
72         }
73         let range = call.syntax().text_range();
74         let range: Range<usize> = range.into();
75         expanded_text.replace_range(range, &expn_text)
76     }
77
78     expect.assert_eq(&expanded_text);
79 }
80
81 fn reindent(indent: IndentLevel, pp: String) -> String {
82     if !pp.contains('\n') {
83         return pp;
84     }
85     let mut lines = pp.split_inclusive('\n');
86     let mut res = lines.next().unwrap().to_string();
87     for line in lines {
88         if line.trim().is_empty() {
89             res.push_str(&line)
90         } else {
91             format_to!(res, "{}{}", indent, line)
92         }
93     }
94     res
95 }
96
97 fn pretty_print_macro_expansion(expn: SyntaxNode) -> String {
98     let mut res = String::new();
99     let mut prev_kind = SyntaxKind::EOF;
100     for token in iter::successors(expn.first_token(), |t| t.next_token()) {
101         let curr_kind = token.kind();
102         let space = match (prev_kind, curr_kind) {
103             _ if prev_kind.is_trivia() || curr_kind.is_trivia() => "",
104             (T![=], _) | (_, T![=]) => " ",
105             (_, T!['{']) => " ",
106             (T![;], _) => "\n",
107             (IDENT | LIFETIME_IDENT, IDENT | LIFETIME_IDENT) => " ",
108             (IDENT, _) if curr_kind.is_keyword() => " ",
109             (_, IDENT) if prev_kind.is_keyword() => " ",
110             _ => "",
111         };
112
113         res.push_str(space);
114         prev_kind = curr_kind;
115         format_to!(res, "{}", token)
116     }
117     res
118 }