]> git.lizzy.rs Git - rust.git/commitdiff
Merge #8063
authorbors[bot] <26634292+bors[bot]@users.noreply.github.com>
Wed, 17 Mar 2021 08:12:34 +0000 (08:12 +0000)
committerGitHub <noreply@github.com>
Wed, 17 Mar 2021 08:12:34 +0000 (08:12 +0000)
8063: couple clippy::complexity fixes r=matklad a=matthiaskrgr

avoid redundant `.into()` calls to convert T into identical T (`let x: String = String::from("hello").into();`)
use `if let Some(x)` instead of `.is_some()` + `.unwrap()`
don't clone Copy types
remove redundant wrapped ?s:  `Some(Some(3)?)` can just be `Some(3)`
use `.map(|x| y)` instead of `and_then(|x| Some(y)` on `Option`s

Co-authored-by: Matthias Krüger <matthias.krueger@famsik.de>
crates/hir_def/src/body.rs
crates/hir_def/src/body/diagnostics.rs
crates/hir_def/src/body/lower.rs
crates/hir_def/src/body/tests.rs
crates/hir_def/src/data.rs
crates/hir_def/src/diagnostics.rs
crates/hir_def/src/lib.rs
crates/hir_expand/src/eager.rs

index 8bcc350ce5e38c67ec16ce0841112ea8cc031e33..1080d9c2c37eec862c0ef5844fbba5498bc3425c 100644 (file)
@@ -32,6 +32,7 @@
     path::{ModPath, Path},
     src::HasSource,
     AsMacroCall, BlockId, DefWithBodyId, HasModule, LocalModuleId, Lookup, ModuleId,
+    UnresolvedMacro,
 };
 
 /// A subset of Expander that only deals with cfg attributes. We only need it to
@@ -101,10 +102,12 @@ pub(crate) fn enter_expand<T: ast::AstNode>(
         &mut self,
         db: &dyn DefDatabase,
         macro_call: ast::MacroCall,
-    ) -> ExpandResult<Option<(Mark, T)>> {
+    ) -> Result<ExpandResult<Option<(Mark, T)>>, UnresolvedMacro> {
         if self.recursion_limit + 1 > EXPANSION_RECURSION_LIMIT {
             cov_mark::hit!(your_stack_belongs_to_me);
-            return ExpandResult::str_err("reached recursion limit during macro expansion".into());
+            return Ok(ExpandResult::str_err(
+                "reached recursion limit during macro expansion".into(),
+            ));
         }
 
         let macro_call = InFile::new(self.current_file_id, &macro_call);
@@ -116,14 +119,11 @@ pub(crate) fn enter_expand<T: ast::AstNode>(
         let call_id =
             macro_call.as_call_id_with_errors(db, self.def_map.krate(), resolver, &mut |e| {
                 err.get_or_insert(e);
-            });
+            })?;
         let call_id = match call_id {
-            Some(it) => it,
-            None => {
-                if err.is_none() {
-                    log::warn!("no error despite `as_call_id_with_errors` returning `None`");
-                }
-                return ExpandResult { value: None, err };
+            Ok(it) => it,
+            Err(_) => {
+                return Ok(ExpandResult { value: None, err });
             }
         };
 
@@ -141,9 +141,9 @@ pub(crate) fn enter_expand<T: ast::AstNode>(
                     log::warn!("no error despite `parse_or_expand` failing");
                 }
 
-                return ExpandResult::only_err(err.unwrap_or_else(|| {
+                return Ok(ExpandResult::only_err(err.unwrap_or_else(|| {
                     mbe::ExpandError::Other("failed to parse macro invocation".into())
-                }));
+                })));
             }
         };
 
@@ -151,7 +151,7 @@ pub(crate) fn enter_expand<T: ast::AstNode>(
             Some(it) => it,
             None => {
                 // This can happen without being an error, so only forward previous errors.
-                return ExpandResult { value: None, err };
+                return Ok(ExpandResult { value: None, err });
             }
         };
 
@@ -167,7 +167,7 @@ pub(crate) fn enter_expand<T: ast::AstNode>(
         self.current_file_id = file_id;
         self.ast_id_map = db.ast_id_map(file_id);
 
-        ExpandResult { value: Some((mark, node)), err }
+        Ok(ExpandResult { value: Some((mark, node)), err })
     }
 
     pub(crate) fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
index 1de7d30e200e87c12edf2046ed2e7ccdaef25023..f6992c9a8a946c9a03e3c551aa4de492020f8b8d 100644 (file)
@@ -2,13 +2,14 @@
 
 use hir_expand::diagnostics::DiagnosticSink;
 
-use crate::diagnostics::{InactiveCode, MacroError, UnresolvedProcMacro};
+use crate::diagnostics::{InactiveCode, MacroError, UnresolvedMacroCall, UnresolvedProcMacro};
 
 #[derive(Debug, Eq, PartialEq)]
 pub(crate) enum BodyDiagnostic {
     InactiveCode(InactiveCode),
     MacroError(MacroError),
     UnresolvedProcMacro(UnresolvedProcMacro),
+    UnresolvedMacroCall(UnresolvedMacroCall),
 }
 
 impl BodyDiagnostic {
@@ -23,6 +24,9 @@ pub(crate) fn add_to(&self, sink: &mut DiagnosticSink<'_>) {
             BodyDiagnostic::UnresolvedProcMacro(diag) => {
                 sink.push(diag.clone());
             }
+            BodyDiagnostic::UnresolvedMacroCall(diag) => {
+                sink.push(diag.clone());
+            }
         }
     }
 }
index 7052058f2a1507a300160c953540b8234b2612bd..60b25db5632cb9b895ab442fdb641bbc5e64139f 100644 (file)
@@ -24,7 +24,7 @@
     body::{Body, BodySourceMap, Expander, LabelSource, PatPtr, SyntheticSyntax},
     builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint},
     db::DefDatabase,
-    diagnostics::{InactiveCode, MacroError, UnresolvedProcMacro},
+    diagnostics::{InactiveCode, MacroError, UnresolvedMacroCall, UnresolvedProcMacro},
     expr::{
         dummy_expr_id, ArithOp, Array, BinaryOp, BindingAnnotation, CmpOp, Expr, ExprId, Label,
         LabelId, Literal, LogicOp, MatchArm, Ordering, Pat, PatId, RecordFieldPat, RecordLitField,
@@ -33,7 +33,7 @@
     item_scope::BuiltinShadowMode,
     path::{GenericArgs, Path},
     type_ref::{Mutability, Rawness, TypeRef},
-    AdtId, BlockLoc, ModuleDefId,
+    AdtId, BlockLoc, ModuleDefId, UnresolvedMacro,
 };
 
 use super::{diagnostics::BodyDiagnostic, ExprSource, PatSource};
@@ -554,6 +554,17 @@ fn collect_macro_call<F: FnMut(&mut Self, Option<T>), T: ast::AstNode>(
         let macro_call = self.expander.to_source(AstPtr::new(&e));
         let res = self.expander.enter_expand(self.db, e);
 
+        let res = match res {
+            Ok(res) => res,
+            Err(UnresolvedMacro) => {
+                self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall(
+                    UnresolvedMacroCall { file: outer_file, node: syntax_ptr.cast().unwrap() },
+                ));
+                collector(self, None);
+                return;
+            }
+        };
+
         match &res.err {
             Some(ExpandError::UnresolvedProcMacro) => {
                 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedProcMacro(
index 991a32b150dbdaf6f5eab27f7cd07f3d1ffddc2e..f8e6f70e87b24894817cb6df84e849c6ceb7d7d6 100644 (file)
@@ -174,6 +174,18 @@ fn f() {
     );
 }
 
+#[test]
+fn unresolved_macro_diag() {
+    check_diagnostics(
+        r#"
+fn f() {
+    m!();
+  //^^^^ unresolved macro call
+}
+      "#,
+    );
+}
+
 #[test]
 fn dollar_crate_in_builtin_macro() {
     check_diagnostics(
index 74a2194e5e7bf339b7ea216464262b185238c22f..1a27f7bf21b2c0abb6371368dc1ab8a091c84105 100644 (file)
@@ -267,23 +267,26 @@ fn collect_items(
                 let ast_id_map = db.ast_id_map(file_id);
                 let root = db.parse_or_expand(file_id).unwrap();
                 let call = ast_id_map.get(call.ast_id).to_node(&root);
-
-                if let Some((mark, mac)) = expander.enter_expand(db, call).value {
-                    let src: InFile<ast::MacroItems> = expander.to_source(mac);
-                    let item_tree = db.item_tree(src.file_id);
-                    let iter =
-                        item_tree.top_level_items().iter().filter_map(ModItem::as_assoc_item);
-                    items.extend(collect_items(
-                        db,
-                        module,
-                        expander,
-                        iter,
-                        src.file_id,
-                        container,
-                        limit - 1,
-                    ));
-
-                    expander.exit(db, mark);
+                let res = expander.enter_expand(db, call);
+
+                if let Ok(res) = res {
+                    if let Some((mark, mac)) = res.value {
+                        let src: InFile<ast::MacroItems> = expander.to_source(mac);
+                        let item_tree = db.item_tree(src.file_id);
+                        let iter =
+                            item_tree.top_level_items().iter().filter_map(ModItem::as_assoc_item);
+                        items.extend(collect_items(
+                            db,
+                            module,
+                            expander,
+                            iter,
+                            src.file_id,
+                            container,
+                            limit - 1,
+                        ));
+
+                        expander.exit(db, mark);
+                    }
                 }
             }
         }
index 7188bb299d2b78bf8c1cc60bdbb64caed9a1cff0..97abf865345ffe4b601919dcb8561784dc5f77c8 100644 (file)
@@ -99,7 +99,7 @@ fn is_experimental(&self) -> bool {
 //
 // This diagnostic is triggered if rust-analyzer is unable to resolve the path to a
 // macro in a macro invocation.
-#[derive(Debug)]
+#[derive(Debug, Clone, Eq, PartialEq)]
 pub struct UnresolvedMacroCall {
     pub file: HirFileId,
     pub node: AstPtr<ast::MacroCall>,
index c6655c5fbf323731bcbaaeeadc6be4dd84e1aa9b..6758411a0c1ab22184e6a60ef761e6abd6ec7519 100644 (file)
@@ -58,7 +58,7 @@ macro_rules! eprintln {
 use base_db::{impl_intern_key, salsa, CrateId};
 use hir_expand::{
     ast_id_map::FileAstId,
-    eager::{expand_eager_macro, ErrorEmitted},
+    eager::{expand_eager_macro, ErrorEmitted, ErrorSink},
     hygiene::Hygiene,
     AstId, HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
 };
@@ -583,7 +583,7 @@ fn as_call_id(
         krate: CrateId,
         resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
     ) -> Option<MacroCallId> {
-        self.as_call_id_with_errors(db, krate, resolver, &mut |_| ())
+        self.as_call_id_with_errors(db, krate, resolver, &mut |_| ()).ok()?.ok()
     }
 
     fn as_call_id_with_errors(
@@ -592,7 +592,7 @@ fn as_call_id_with_errors(
         krate: CrateId,
         resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
         error_sink: &mut dyn FnMut(mbe::ExpandError),
-    ) -> Option<MacroCallId>;
+    ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro>;
 }
 
 impl AsMacroCall for InFile<&ast::MacroCall> {
@@ -601,25 +601,28 @@ fn as_call_id_with_errors(
         db: &dyn db::DefDatabase,
         krate: CrateId,
         resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
-        error_sink: &mut dyn FnMut(mbe::ExpandError),
-    ) -> Option<MacroCallId> {
+        mut error_sink: &mut dyn FnMut(mbe::ExpandError),
+    ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> {
         let ast_id = AstId::new(self.file_id, db.ast_id_map(self.file_id).ast_id(self.value));
         let h = Hygiene::new(db.upcast(), self.file_id);
         let path = self.value.path().and_then(|path| path::ModPath::from_src(path, &h));
 
-        if path.is_none() {
-            error_sink(mbe::ExpandError::Other("malformed macro invocation".into()));
-        }
+        let path = match error_sink
+            .option(path, || mbe::ExpandError::Other("malformed macro invocation".into()))
+        {
+            Ok(path) => path,
+            Err(error) => {
+                return Ok(Err(error));
+            }
+        };
 
         macro_call_as_call_id(
-            &AstIdWithPath::new(ast_id.file_id, ast_id.value, path?),
+            &AstIdWithPath::new(ast_id.file_id, ast_id.value, path),
             db,
             krate,
             resolver,
             error_sink,
         )
-        .ok()?
-        .ok()
     }
 }
 
@@ -636,7 +639,7 @@ fn new(file_id: HirFileId, ast_id: FileAstId<T>, path: path::ModPath) -> AstIdWi
     }
 }
 
-struct UnresolvedMacro;
+pub struct UnresolvedMacro;
 
 fn macro_call_as_call_id(
     call: &AstIdWithPath<ast::MacroCall>,
index ae7b51a088167813c2f5f9d97879d6e74e2429b6..dc618a9ee1f5354ede4c1f75aaec77a33290b43a 100644 (file)
@@ -35,7 +35,7 @@ pub struct ErrorEmitted {
     _private: (),
 }
 
-trait ErrorSink {
+pub trait ErrorSink {
     fn emit(&mut self, err: mbe::ExpandError);
 
     fn option<T>(