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::{COMMENT, EOF, IDENT, LIFETIME_IDENT},
28 db::DefDatabase, nameres::ModuleSource, resolver::HasResolver, test_db::TestDB, AsMacroCall,
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!(),
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, ¯o_call);
48 let macro_call_id = macro_call
49 .as_call_id_with_errors(
52 |path| resolver.resolve_path_as_macro(&db, &path),
53 &mut |err| panic!("{}", err),
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));
62 let mut expanded_text = source_file.to_string();
63 for (call, exp) in expansions.into_iter().rev() {
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");
71 let mut expn_text = String::new();
72 if let Some(err) = exp.err {
73 format_to!(expn_text, "/* error: {} */", err);
75 if let Some((parse, _token_map)) = exp.value {
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);
83 parse.errors().is_empty(),
84 "parse errors in expansion: \n{:#?}",
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);
94 let tree = format!("{:#?}", parse.syntax_node())
95 .split_inclusive("\n")
96 .map(|line| format!("// {}", line))
98 format_to!(expn_text, "\n{}", tree)
101 let range = call.syntax().text_range();
102 let range: Range<usize> = range.into();
103 expanded_text.replace_range(range, &expn_text)
106 expect.indent(false);
107 expect.assert_eq(&expanded_text);
110 fn reindent(indent: IndentLevel, pp: String) -> String {
111 if !pp.contains('\n') {
114 let mut lines = pp.split_inclusive('\n');
115 let mut res = lines.next().unwrap().to_string();
117 if line.trim().is_empty() {
120 format_to!(res, "{}{}", indent, line)
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![=]) => " ",
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![&&]) => " ",
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() => " ",
158 T!['{'] => indent_level += 1,
159 T!['}'] => indent_level -= 1,
165 let level = if curr_kind == T!['}'] { indent_level - 1 } else { indent_level };
166 res.push_str(&" ".repeat(level));
168 prev_kind = curr_kind;
169 format_to!(res, "{}", token)