]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/macro_expansion_tests.rs
internal: 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 use std::{iter, ops::Range};
13
14 use base_db::{fixture::WithFixture, SourceDatabase};
15 use expect_test::{expect, Expect};
16 use hir_expand::{db::AstDatabase, InFile, MacroFile};
17 use stdx::format_to;
18 use syntax::{
19     ast, AstNode,
20     SyntaxKind::{self, IDENT},
21     SyntaxNode, T,
22 };
23
24 use crate::{
25     db::DefDatabase, nameres::ModuleSource, resolver::HasResolver, test_db::TestDB, AsMacroCall,
26 };
27
28 fn check(ra_fixture: &str, expect: Expect) {
29     let db = TestDB::with_files(ra_fixture);
30     let krate = db.crate_graph().iter().next().unwrap();
31     let def_map = db.crate_def_map(krate);
32     let local_id = def_map.root();
33     let module = def_map.module_id(local_id);
34     let resolver = module.resolver(&db);
35     let source = def_map[local_id].definition_source(&db);
36     let source_file = match source.value {
37         ModuleSource::SourceFile(it) => it,
38         ModuleSource::Module(_) | ModuleSource::BlockExpr(_) => panic!(),
39     };
40
41     let mut expansions = Vec::new();
42     for macro_call in source_file.syntax().descendants().filter_map(ast::MacroCall::cast) {
43         let macro_call = InFile::new(source.file_id, &macro_call);
44         let macro_call_id = macro_call
45             .as_call_id_with_errors(
46                 &db,
47                 krate,
48                 |path| resolver.resolve_path_as_macro(&db, &path),
49                 &mut |err| panic!("{}", err),
50             )
51             .unwrap()
52             .unwrap();
53         let macro_file = MacroFile { macro_call_id };
54         let expansion_result = db.parse_macro_expansion(macro_file);
55         expansions.push((macro_call.value.clone(), expansion_result));
56     }
57
58     let mut expanded_text = source_file.to_string();
59     for (call, exp) in expansions.into_iter().rev() {
60         let mut expn_text = String::new();
61         if let Some(err) = exp.err {
62             format_to!(expn_text, "/* error: {} */", err);
63         }
64         if let Some((parse, _token_map)) = exp.value {
65             let pp = pretty_print_macro_expansion(parse.syntax_node());
66             format_to!(expn_text, "{}", pp);
67         }
68         let range = call.syntax().text_range();
69         let range: Range<usize> = range.into();
70         expanded_text.replace_range(range, &expn_text)
71     }
72
73     expect.assert_eq(&expanded_text);
74 }
75
76 fn pretty_print_macro_expansion(expn: SyntaxNode) -> String {
77     let mut res = String::new();
78     let mut prev_kind = SyntaxKind::EOF;
79     for token in iter::successors(expn.first_token(), |t| t.next_token()) {
80         let curr_kind = token.kind();
81         let needs_space = match (prev_kind, curr_kind) {
82             _ if prev_kind.is_trivia() || curr_kind.is_trivia() => false,
83             (T![=], _) | (_, T![=]) => true,
84             (IDENT, IDENT) => true,
85             (IDENT, _) => curr_kind.is_keyword(),
86             (_, IDENT) => prev_kind.is_keyword(),
87             _ => false,
88         };
89
90         if needs_space {
91             res.push(' ')
92         }
93         prev_kind = curr_kind;
94         format_to!(res, "{}", token)
95     }
96     res
97 }
98
99 #[test]
100 fn wrong_nesting_level() {
101     check(
102         r#"
103 macro_rules! m {
104     ($($i:ident);*) => ($i)
105 }
106 m!{a}
107 "#,
108         expect![[r#"
109 macro_rules! m {
110     ($($i:ident);*) => ($i)
111 }
112 /* error: expected simple binding, found nested binding `i` */
113 "#]],
114     );
115 }
116
117 #[test]
118 fn expansion_does_not_parse_as_expression() {
119     check(
120         r#"
121 macro_rules! stmts {
122     () => { let _ = 0; }
123 }
124
125 fn f() { let _ = stmts!(); }
126 "#,
127         expect![[r#"
128 macro_rules! stmts {
129     () => { let _ = 0; }
130 }
131
132 fn f() { let _ = /* error: could not convert tokens */; }
133 "#]],
134     )
135 }
136
137 #[test]
138 fn round_trips_compound_tokens() {
139     check(
140         r#"
141 macro_rules! m {
142     () => { type qual: ::T = qual::T; }
143 }
144 m!();
145 "#,
146         expect![[r#"
147 macro_rules! m {
148     () => { type qual: ::T = qual::T; }
149 }
150 type qual: ::T = qual::T;
151         "#]],
152     )
153 }