]> git.lizzy.rs Git - rust.git/blobdiff - crates/hir_def/src/macro_expansion_tests.rs
Merge #10417
[rust.git] / crates / hir_def / src / macro_expansion_tests.rs
index 66874a674d821841fa6c8dbdcbbe14c82669d66c..036d9147a08bdd9a115028014832f4b0ede2ae7c 100644 (file)
@@ -10,6 +10,9 @@
 //! and harder to understand.
 
 mod mbe;
+mod builtin_fn_macro;
+mod builtin_derive_macro;
+mod proc_macros;
 
 use std::{iter, ops::Range};
 
 use syntax::{
     ast::{self, edit::IndentLevel},
     AstNode,
-    SyntaxKind::{EOF, IDENT, LIFETIME_IDENT},
+    SyntaxKind::{COMMENT, EOF, IDENT, LIFETIME_IDENT},
     SyntaxNode, T,
 };
 
 use crate::{
-    db::DefDatabase, nameres::ModuleSource, resolver::HasResolver, test_db::TestDB, AsMacroCall,
+    db::DefDatabase, nameres::ModuleSource, resolver::HasResolver, src::HasSource, test_db::TestDB,
+    AdtId, AsMacroCall, Lookup, ModuleDefId,
 };
 
+#[track_caller]
 fn check(ra_fixture: &str, mut expect: Expect) {
     let db = TestDB::with_files(ra_fixture);
     let krate = db.crate_graph().iter().next().unwrap();
@@ -41,40 +46,73 @@ fn check(ra_fixture: &str, mut expect: Expect) {
         ModuleSource::Module(_) | ModuleSource::BlockExpr(_) => panic!(),
     };
 
+    // What we want to do is to replace all macros (fn-like, derive, attr) with
+    // their expansions. Turns out, we don't actually store enough information
+    // to do this precisely though! Specifically, if a macro expands to nothing,
+    // it leaves zero traces in def-map, so we can't get its expansion after the
+    // fact.
+    //
+    // This is the usual
+    // <https://github.com/rust-analyzer/rust-analyzer/issues/3407>
+    // resolve/record tension!
+    //
+    // So here we try to do a resolve, which is necessary a heuristic. For macro
+    // calls, we use `as_call_id_with_errors`. For derives, we look at the impls
+    // in the module and assume that, if impls's source is a different
+    // `HirFileId`, than it came from macro expansion.
+
     let mut expansions = Vec::new();
     for macro_call in source_file.syntax().descendants().filter_map(ast::MacroCall::cast) {
         let macro_call = InFile::new(source.file_id, &macro_call);
+        let mut error = None;
         let macro_call_id = macro_call
             .as_call_id_with_errors(
                 &db,
                 krate,
                 |path| resolver.resolve_path_as_macro(&db, &path),
-                &mut |err| panic!("{}", err),
+                &mut |err| error = Some(err),
             )
             .unwrap()
             .unwrap();
         let macro_file = MacroFile { macro_call_id };
-        let expansion_result = db.parse_macro_expansion(macro_file);
+        let mut expansion_result = db.parse_macro_expansion(macro_file);
+        expansion_result.err = expansion_result.err.or(error);
         expansions.push((macro_call.value.clone(), expansion_result));
     }
 
     let mut expanded_text = source_file.to_string();
+
     for (call, exp) in expansions.into_iter().rev() {
+        let mut tree = false;
+        let mut expect_errors = false;
+        for comment in call.syntax().children_with_tokens().filter(|it| it.kind() == COMMENT) {
+            tree |= comment.to_string().contains("+tree");
+            expect_errors |= comment.to_string().contains("+errors");
+        }
+
         let mut expn_text = String::new();
         if let Some(err) = exp.err {
             format_to!(expn_text, "/* error: {} */", err);
         }
         if let Some((parse, _token_map)) = exp.value {
-            assert!(
-                parse.errors().is_empty(),
-                "parse errors in expansion: \n{:#?}",
-                parse.errors()
-            );
+            if expect_errors {
+                assert!(!parse.errors().is_empty(), "no parse errors in expansion");
+                for e in parse.errors() {
+                    format_to!(expn_text, "/* parse error: {} */\n", e);
+                }
+            } else {
+                assert!(
+                    parse.errors().is_empty(),
+                    "parse errors in expansion: \n{:#?}",
+                    parse.errors()
+                );
+            }
             let pp = pretty_print_macro_expansion(parse.syntax_node());
             let indent = IndentLevel::from_node(call.syntax());
             let pp = reindent(indent, pp);
             format_to!(expn_text, "{}", pp);
-            if call.to_string().contains("// +tree") {
+
+            if tree {
                 let tree = format!("{:#?}", parse.syntax_node())
                     .split_inclusive("\n")
                     .map(|line| format!("// {}", line))
@@ -87,6 +125,24 @@ fn check(ra_fixture: &str, mut expect: Expect) {
         expanded_text.replace_range(range, &expn_text)
     }
 
+    for decl_id in def_map[local_id].scope.declarations() {
+        if let ModuleDefId::AdtId(AdtId::StructId(struct_id)) = decl_id {
+            let src = struct_id.lookup(&db).source(&db);
+            if src.file_id.is_attr_macro(&db) || src.file_id.is_custom_derive(&db) {
+                let pp = pretty_print_macro_expansion(src.value.syntax().clone());
+                format_to!(expanded_text, "\n{}", pp)
+            }
+        }
+    }
+
+    for impl_id in def_map[local_id].scope.impls() {
+        let src = impl_id.lookup(&db).source(&db);
+        if src.file_id.is_builtin_derive(&db).is_some() {
+            let pp = pretty_print_macro_expansion(src.value.syntax().clone());
+            format_to!(expanded_text, "\n{}", pp)
+        }
+    }
+
     expect.indent(false);
     expect.assert_eq(&expanded_text);
 }
@@ -129,6 +185,8 @@ fn pretty_print_macro_expansion(expn: SyntaxNode) -> String {
             (T![->], _) | (_, T![->]) => " ",
             (T![&&], _) | (_, T![&&]) => " ",
             (T![,], _) => " ",
+            (T![:], IDENT | T!['(']) => " ",
+            (T![:], _) if curr_kind.is_keyword() => " ",
             (T![fn], T!['(']) => "",
             (T![']'], _) if curr_kind.is_keyword() => " ",
             (T![']'], T![#]) => "\n",