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.
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.
14 use std::{iter, ops::Range};
16 use base_db::{fixture::WithFixture, SourceDatabase};
17 use expect_test::Expect;
18 use hir_expand::{db::AstDatabase, InFile, MacroFile};
21 ast::{self, edit::IndentLevel},
23 SyntaxKind::{self, IDENT, LIFETIME_IDENT},
28 db::DefDatabase, nameres::ModuleSource, resolver::HasResolver, test_db::TestDB, AsMacroCall,
31 fn check(ra_fixture: &str, mut 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!(),
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, ¯o_call);
47 let macro_call_id = macro_call
48 .as_call_id_with_errors(
51 |path| resolver.resolve_path_as_macro(&db, &path),
52 &mut |err| panic!("{}", err),
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));
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);
67 if let Some((parse, _token_map)) = exp.value {
69 parse.errors().is_empty(),
70 "parse errors in expansion: \n{:#?}",
73 let pp = pretty_print_macro_expansion(parse.syntax_node());
74 let indent = IndentLevel::from_node(call.syntax());
75 let pp = reindent(indent, pp);
76 format_to!(expn_text, "{}", pp);
77 if call.to_string().contains("// +tree") {
78 let tree = format!("{:#?}", parse.syntax_node())
79 .split_inclusive("\n")
80 .map(|line| format!("// {}", line))
82 format_to!(expn_text, "\n{}", tree)
85 let range = call.syntax().text_range();
86 let range: Range<usize> = range.into();
87 expanded_text.replace_range(range, &expn_text)
91 expect.assert_eq(&expanded_text);
94 fn reindent(indent: IndentLevel, pp: String) -> String {
95 if !pp.contains('\n') {
98 let mut lines = pp.split_inclusive('\n');
99 let mut res = lines.next().unwrap().to_string();
101 if line.trim().is_empty() {
104 format_to!(res, "{}{}", indent, line)
110 fn pretty_print_macro_expansion(expn: SyntaxNode) -> String {
111 let mut res = String::new();
112 let mut prev_kind = SyntaxKind::EOF;
113 let mut indent_level = 0;
114 for token in iter::successors(expn.first_token(), |t| t.next_token()) {
115 let curr_kind = token.kind();
116 let space = match (prev_kind, curr_kind) {
117 _ if prev_kind.is_trivia() || curr_kind.is_trivia() => "",
118 (T!['{'], T!['}']) => "",
119 (T![=], _) | (_, T![=]) => " ",
121 (T![;] | T!['{'] | T!['}'], _) => "\n",
122 (_, T!['}']) => "\n",
123 (IDENT | LIFETIME_IDENT, IDENT | LIFETIME_IDENT) => " ",
124 (IDENT, _) if curr_kind.is_keyword() => " ",
125 (_, IDENT) if prev_kind.is_keyword() => " ",
126 (T![>], IDENT) => " ",
127 (T![>], _) if curr_kind.is_keyword() => " ",
128 (T![->], _) | (_, T![->]) => " ",
129 (T![&&], _) | (_, T![&&]) => " ",
134 T!['{'] => indent_level += 1,
135 T!['}'] => indent_level -= 1,
141 let level = if curr_kind == T!['}'] { indent_level - 1 } else { indent_level };
142 res.push_str(&" ".repeat(level));
144 prev_kind = curr_kind;
145 format_to!(res, "{}", token)