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.
15 use std::{iter, ops::Range};
17 use base_db::{fixture::WithFixture, SourceDatabase};
18 use expect_test::Expect;
19 use hir_expand::{db::AstDatabase, InFile, MacroFile};
22 ast::{self, edit::IndentLevel},
24 SyntaxKind::{COMMENT, EOF, IDENT, LIFETIME_IDENT},
29 db::DefDatabase, nameres::ModuleSource, resolver::HasResolver, test_db::TestDB, AsMacroCall,
33 fn check(ra_fixture: &str, mut expect: Expect) {
34 let db = TestDB::with_files(ra_fixture);
35 let krate = db.crate_graph().iter().next().unwrap();
36 let def_map = db.crate_def_map(krate);
37 let local_id = def_map.root();
38 let module = def_map.module_id(local_id);
39 let resolver = module.resolver(&db);
40 let source = def_map[local_id].definition_source(&db);
41 let source_file = match source.value {
42 ModuleSource::SourceFile(it) => it,
43 ModuleSource::Module(_) | ModuleSource::BlockExpr(_) => panic!(),
46 let mut expansions = Vec::new();
47 for macro_call in source_file.syntax().descendants().filter_map(ast::MacroCall::cast) {
48 let macro_call = InFile::new(source.file_id, ¯o_call);
50 let macro_call_id = macro_call
51 .as_call_id_with_errors(
54 |path| resolver.resolve_path_as_macro(&db, &path),
55 &mut |err| error = Some(err),
59 let macro_file = MacroFile { macro_call_id };
60 let mut expansion_result = db.parse_macro_expansion(macro_file);
61 expansion_result.err = expansion_result.err.or(error);
62 expansions.push((macro_call.value.clone(), expansion_result));
65 let mut expanded_text = source_file.to_string();
66 for (call, exp) in expansions.into_iter().rev() {
68 let mut expect_errors = false;
69 for comment in call.syntax().children_with_tokens().filter(|it| it.kind() == COMMENT) {
70 tree |= comment.to_string().contains("+tree");
71 expect_errors |= comment.to_string().contains("+errors");
74 let mut expn_text = String::new();
75 if let Some(err) = exp.err {
76 format_to!(expn_text, "/* error: {} */", err);
78 if let Some((parse, _token_map)) = exp.value {
80 assert!(!parse.errors().is_empty(), "no parse errors in expansion");
81 for e in parse.errors() {
82 format_to!(expn_text, "/* parse error: {} */\n", e);
86 parse.errors().is_empty(),
87 "parse errors in expansion: \n{:#?}",
91 let pp = pretty_print_macro_expansion(parse.syntax_node());
92 let indent = IndentLevel::from_node(call.syntax());
93 let pp = reindent(indent, pp);
94 format_to!(expn_text, "{}", pp);
97 let tree = format!("{:#?}", parse.syntax_node())
98 .split_inclusive("\n")
99 .map(|line| format!("// {}", line))
100 .collect::<String>();
101 format_to!(expn_text, "\n{}", tree)
104 let range = call.syntax().text_range();
105 let range: Range<usize> = range.into();
106 expanded_text.replace_range(range, &expn_text)
109 expect.indent(false);
110 expect.assert_eq(&expanded_text);
113 fn reindent(indent: IndentLevel, pp: String) -> String {
114 if !pp.contains('\n') {
117 let mut lines = pp.split_inclusive('\n');
118 let mut res = lines.next().unwrap().to_string();
120 if line.trim().is_empty() {
123 format_to!(res, "{}{}", indent, line)
129 fn pretty_print_macro_expansion(expn: SyntaxNode) -> String {
130 let mut res = String::new();
131 let mut prev_kind = EOF;
132 let mut indent_level = 0;
133 for token in iter::successors(expn.first_token(), |t| t.next_token()) {
134 let curr_kind = token.kind();
135 let space = match (prev_kind, curr_kind) {
136 _ if prev_kind.is_trivia() || curr_kind.is_trivia() => "",
137 (T!['{'], T!['}']) => "",
138 (T![=], _) | (_, T![=]) => " ",
140 (T![;] | T!['{'] | T!['}'], _) => "\n",
141 (_, T!['}']) => "\n",
142 (IDENT | LIFETIME_IDENT, IDENT | LIFETIME_IDENT) => " ",
143 _ if prev_kind.is_keyword() && curr_kind.is_keyword() => " ",
144 (IDENT, _) if curr_kind.is_keyword() => " ",
145 (_, IDENT) if prev_kind.is_keyword() => " ",
146 (T![>], IDENT) => " ",
147 (T![>], _) if curr_kind.is_keyword() => " ",
148 (T![->], _) | (_, T![->]) => " ",
149 (T![&&], _) | (_, T![&&]) => " ",
151 (T![:], IDENT | T!['(']) => " ",
152 (T![:], _) if curr_kind.is_keyword() => " ",
153 (T![fn], T!['(']) => "",
154 (T![']'], _) if curr_kind.is_keyword() => " ",
155 (T![']'], T![#]) => "\n",
156 _ if prev_kind.is_keyword() => " ",
161 T!['{'] => indent_level += 1,
162 T!['}'] => indent_level -= 1,
168 let level = if curr_kind == T!['}'] { indent_level - 1 } else { indent_level };
169 res.push_str(&" ".repeat(level));
171 prev_kind = curr_kind;
172 format_to!(res, "{}", token)