From 5c9f31d4c28478b4373e6cf5ec155745c840ee3f Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Sun, 23 May 2021 23:31:59 +0300 Subject: internal: move diagnostics to hir The idea here is to eventually get rid of `dyn Diagnostic` and `DiagnosticSink` infrastructure altogether, and just have a `enum hir::Diagnostic` instead. The problem with `dyn Diagnostic` is that it is defined in the lowest level of the stack (hir_expand), but is used by the highest level (ide). As a first step, we free hir_expand and hir_def from `dyn Diagnostic` and kick the can up to `hir_ty`, as an intermediate state. The plan is then to move DiagnosticSink similarly to the hir crate, and, as final third step, remove its usage from the ide. One currently unsolved problem is testing. You can notice that the test which checks precise diagnostic ranges, unresolved_import_in_use_tree, was moved to the ide layer. Logically, only IDE should have the infra to render a specific range. At the same time, the range is determined with the data produced in hir_def and hir crates, so this layering is rather unfortunate. Working on hir_def shouldn't require compiling `ide` for testing. --- crates/hir/src/diagnostics.rs | 232 ++++++++++++++++++++++++++++++++++++++++-- crates/hir/src/lib.rs | 176 +++++++++++++++++++++++++++++++- 2 files changed, 395 insertions(+), 13 deletions(-) (limited to 'crates/hir/src') diff --git a/crates/hir/src/diagnostics.rs b/crates/hir/src/diagnostics.rs index 414c3f35e..22ec7c6ac 100644 --- a/crates/hir/src/diagnostics.rs +++ b/crates/hir/src/diagnostics.rs @@ -3,13 +3,227 @@ //! //! This probably isn't the best way to do this -- ideally, diagnistics should //! be expressed in terms of hir types themselves. -pub use hir_def::diagnostics::{ - InactiveCode, UnresolvedMacroCall, UnresolvedModule, UnresolvedProcMacro, -}; -pub use hir_expand::diagnostics::{ - Diagnostic, DiagnosticCode, DiagnosticSink, DiagnosticSinkBuilder, -}; -pub use hir_ty::diagnostics::{ - IncorrectCase, MismatchedArgCount, MissingFields, MissingMatchArms, MissingOkOrSomeInTailExpr, - NoSuchField, RemoveThisSemicolon, ReplaceFilterMapNextWithFindMap, +use std::any::Any; + +use cfg::{CfgExpr, CfgOptions, DnfExpr}; +use hir_def::path::ModPath; +use hir_expand::{HirFileId, InFile}; +use stdx::format_to; +use syntax::{ast, AstPtr, SyntaxNodePtr, TextRange}; + +pub use hir_ty::{ + diagnostics::{ + IncorrectCase, MismatchedArgCount, MissingFields, MissingMatchArms, + MissingOkOrSomeInTailExpr, NoSuchField, RemoveThisSemicolon, + ReplaceFilterMapNextWithFindMap, + }, + diagnostics_sink::{Diagnostic, DiagnosticCode, DiagnosticSink, DiagnosticSinkBuilder}, }; + +// Diagnostic: unresolved-module +// +// This diagnostic is triggered if rust-analyzer is unable to discover referred module. +#[derive(Debug)] +pub struct UnresolvedModule { + pub file: HirFileId, + pub decl: AstPtr, + pub candidate: String, +} + +impl Diagnostic for UnresolvedModule { + fn code(&self) -> DiagnosticCode { + DiagnosticCode("unresolved-module") + } + fn message(&self) -> String { + "unresolved module".to_string() + } + fn display_source(&self) -> InFile { + InFile::new(self.file, self.decl.clone().into()) + } + fn as_any(&self) -> &(dyn Any + Send + 'static) { + self + } +} + +// Diagnostic: unresolved-extern-crate +// +// This diagnostic is triggered if rust-analyzer is unable to discover referred extern crate. +#[derive(Debug)] +pub struct UnresolvedExternCrate { + pub file: HirFileId, + pub item: AstPtr, +} + +impl Diagnostic for UnresolvedExternCrate { + fn code(&self) -> DiagnosticCode { + DiagnosticCode("unresolved-extern-crate") + } + fn message(&self) -> String { + "unresolved extern crate".to_string() + } + fn display_source(&self) -> InFile { + InFile::new(self.file, self.item.clone().into()) + } + fn as_any(&self) -> &(dyn Any + Send + 'static) { + self + } +} + +#[derive(Debug)] +pub struct UnresolvedImport { + pub file: HirFileId, + pub node: AstPtr, +} + +impl Diagnostic for UnresolvedImport { + fn code(&self) -> DiagnosticCode { + DiagnosticCode("unresolved-import") + } + fn message(&self) -> String { + "unresolved import".to_string() + } + fn display_source(&self) -> InFile { + InFile::new(self.file, self.node.clone().into()) + } + fn as_any(&self) -> &(dyn Any + Send + 'static) { + self + } + fn is_experimental(&self) -> bool { + // This currently results in false positives in the following cases: + // - `cfg_if!`-generated code in libstd (we don't load the sysroot correctly) + // - `core::arch` (we don't handle `#[path = "../"]` correctly) + // - proc macros and/or proc macro generated code + true + } +} + +// Diagnostic: unresolved-macro-call +// +// This diagnostic is triggered if rust-analyzer is unable to resolve the path to a +// macro in a macro invocation. +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct UnresolvedMacroCall { + pub file: HirFileId, + pub node: AstPtr, + pub path: ModPath, +} + +impl Diagnostic for UnresolvedMacroCall { + fn code(&self) -> DiagnosticCode { + DiagnosticCode("unresolved-macro-call") + } + fn message(&self) -> String { + format!("unresolved macro `{}!`", self.path) + } + fn display_source(&self) -> InFile { + InFile::new(self.file, self.node.clone().into()) + } + fn as_any(&self) -> &(dyn Any + Send + 'static) { + self + } + fn is_experimental(&self) -> bool { + true + } +} + +// Diagnostic: inactive-code +// +// This diagnostic is shown for code with inactive `#[cfg]` attributes. +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct InactiveCode { + pub file: HirFileId, + pub node: SyntaxNodePtr, + pub cfg: CfgExpr, + pub opts: CfgOptions, +} + +impl Diagnostic for InactiveCode { + fn code(&self) -> DiagnosticCode { + DiagnosticCode("inactive-code") + } + fn message(&self) -> String { + let inactive = DnfExpr::new(self.cfg.clone()).why_inactive(&self.opts); + let mut buf = "code is inactive due to #[cfg] directives".to_string(); + + if let Some(inactive) = inactive { + format_to!(buf, ": {}", inactive); + } + + buf + } + fn display_source(&self) -> InFile { + InFile::new(self.file, self.node.clone()) + } + fn as_any(&self) -> &(dyn Any + Send + 'static) { + self + } +} + +// Diagnostic: unresolved-proc-macro +// +// This diagnostic is shown when a procedural macro can not be found. This usually means that +// procedural macro support is simply disabled (and hence is only a weak hint instead of an error), +// but can also indicate project setup problems. +// +// If you are seeing a lot of "proc macro not expanded" warnings, you can add this option to the +// `rust-analyzer.diagnostics.disabled` list to prevent them from showing. Alternatively you can +// enable support for procedural macros (see `rust-analyzer.procMacro.enable`). +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct UnresolvedProcMacro { + pub file: HirFileId, + pub node: SyntaxNodePtr, + /// If the diagnostic can be pinpointed more accurately than via `node`, this is the `TextRange` + /// to use instead. + pub precise_location: Option, + pub macro_name: Option, +} + +impl Diagnostic for UnresolvedProcMacro { + fn code(&self) -> DiagnosticCode { + DiagnosticCode("unresolved-proc-macro") + } + + fn message(&self) -> String { + match &self.macro_name { + Some(name) => format!("proc macro `{}` not expanded", name), + None => "proc macro not expanded".to_string(), + } + } + + fn display_source(&self) -> InFile { + InFile::new(self.file, self.node.clone()) + } + + fn as_any(&self) -> &(dyn Any + Send + 'static) { + self + } +} + +// Diagnostic: macro-error +// +// This diagnostic is shown for macro expansion errors. +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct MacroError { + pub file: HirFileId, + pub node: SyntaxNodePtr, + pub message: String, +} + +impl Diagnostic for MacroError { + fn code(&self) -> DiagnosticCode { + DiagnosticCode("macro-error") + } + fn message(&self) -> String { + self.message.clone() + } + fn display_source(&self) -> InFile { + InFile::new(self.file, self.node.clone()) + } + fn as_any(&self) -> &(dyn Any + Send + 'static) { + self + } + fn is_experimental(&self) -> bool { + // Newly added and not very well-tested, might contain false positives. + true + } +} diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index cdf65a044..1ecd2391b 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -35,12 +35,18 @@ use std::{iter, sync::Arc}; use arrayvec::ArrayVec; use base_db::{CrateDisplayName, CrateId, Edition, FileId}; +use diagnostics::{ + InactiveCode, MacroError, UnresolvedExternCrate, UnresolvedImport, UnresolvedMacroCall, + UnresolvedModule, UnresolvedProcMacro, +}; use either::Either; use hir_def::{ adt::{ReprKind, VariantData}, + body::BodyDiagnostic, expr::{BindingAnnotation, LabelId, Pat, PatId}, item_tree::ItemTreeNode, lang_item::LangItemTarget, + nameres, per_ns::PerNs, resolver::{HasResolver, Resolver}, src::HasSource as _, @@ -50,11 +56,12 @@ use hir_def::{ LocalEnumVariantId, LocalFieldId, Lookup, ModuleId, StaticId, StructId, TraitId, TypeAliasId, TypeParamId, UnionId, }; -use hir_expand::{diagnostics::DiagnosticSink, name::name, MacroDefKind}; +use hir_expand::{name::name, MacroCallKind, MacroDefKind}; use hir_ty::{ autoderef, consteval::ConstExt, could_unify, + diagnostics_sink::DiagnosticSink, method_resolution::{self, def_crates, TyFingerprint}, primitive::UintTy, subst_prefix, @@ -65,11 +72,12 @@ use hir_ty::{ WhereClause, }; use itertools::Itertools; +use nameres::diagnostics::DefDiagnosticKind; use rustc_hash::FxHashSet; use stdx::{format_to, impl_from}; use syntax::{ ast::{self, AttrsOwner, NameOwner}, - AstNode, SmolStr, + AstNode, AstPtr, SmolStr, SyntaxKind, SyntaxNodePtr, }; use tt::{Ident, Leaf, Literal, TokenTree}; @@ -442,7 +450,137 @@ impl Module { format!("{:?}", self.name(db).map_or("".into(), |name| name.to_string())) }); let def_map = self.id.def_map(db.upcast()); - def_map.add_diagnostics(db.upcast(), self.id.local_id, sink); + for diag in def_map.diagnostics() { + if diag.in_module != self.id.local_id { + // FIXME: This is accidentally quadratic. + continue; + } + match &diag.kind { + DefDiagnosticKind::UnresolvedModule { ast: declaration, candidate } => { + let decl = declaration.to_node(db.upcast()); + sink.push(UnresolvedModule { + file: declaration.file_id, + decl: AstPtr::new(&decl), + candidate: candidate.clone(), + }) + } + DefDiagnosticKind::UnresolvedExternCrate { ast } => { + let item = ast.to_node(db.upcast()); + sink.push(UnresolvedExternCrate { + file: ast.file_id, + item: AstPtr::new(&item), + }); + } + + DefDiagnosticKind::UnresolvedImport { ast, index } => { + let use_item = ast.to_node(db.upcast()); + let hygiene = Hygiene::new(db.upcast(), ast.file_id); + let mut cur = 0; + let mut tree = None; + ModPath::expand_use_item( + db.upcast(), + InFile::new(ast.file_id, use_item), + &hygiene, + |_mod_path, use_tree, _is_glob, _alias| { + if cur == *index { + tree = Some(use_tree.clone()); + } + + cur += 1; + }, + ); + + if let Some(tree) = tree { + sink.push(UnresolvedImport { file: ast.file_id, node: AstPtr::new(&tree) }); + } + } + + DefDiagnosticKind::UnconfiguredCode { ast, cfg, opts } => { + let item = ast.to_node(db.upcast()); + sink.push(InactiveCode { + file: ast.file_id, + node: AstPtr::new(&item).into(), + cfg: cfg.clone(), + opts: opts.clone(), + }); + } + + DefDiagnosticKind::UnresolvedProcMacro { ast } => { + let mut precise_location = None; + let (file, ast, name) = match ast { + MacroCallKind::FnLike { ast_id, .. } => { + let node = ast_id.to_node(db.upcast()); + (ast_id.file_id, SyntaxNodePtr::from(AstPtr::new(&node)), None) + } + MacroCallKind::Derive { ast_id, derive_name, .. } => { + let node = ast_id.to_node(db.upcast()); + + // Compute the precise location of the macro name's token in the derive + // list. + // FIXME: This does not handle paths to the macro, but neither does the + // rest of r-a. + let derive_attrs = + node.attrs().filter_map(|attr| match attr.as_simple_call() { + Some((name, args)) if name == "derive" => Some(args), + _ => None, + }); + 'outer: for attr in derive_attrs { + let tokens = + attr.syntax().children_with_tokens().filter_map(|elem| { + match elem { + syntax::NodeOrToken::Node(_) => None, + syntax::NodeOrToken::Token(tok) => Some(tok), + } + }); + for token in tokens { + if token.kind() == SyntaxKind::IDENT + && token.text() == derive_name.as_str() + { + precise_location = Some(token.text_range()); + break 'outer; + } + } + } + + ( + ast_id.file_id, + SyntaxNodePtr::from(AstPtr::new(&node)), + Some(derive_name.clone()), + ) + } + }; + sink.push(UnresolvedProcMacro { + file, + node: ast, + precise_location, + macro_name: name, + }); + } + + DefDiagnosticKind::UnresolvedMacroCall { ast, path } => { + let node = ast.to_node(db.upcast()); + sink.push(UnresolvedMacroCall { + file: ast.file_id, + node: AstPtr::new(&node), + path: path.clone(), + }); + } + + DefDiagnosticKind::MacroError { ast, message } => { + let (file, ast) = match ast { + MacroCallKind::FnLike { ast_id, .. } => { + let node = ast_id.to_node(db.upcast()); + (ast_id.file_id, SyntaxNodePtr::from(AstPtr::new(&node))) + } + MacroCallKind::Derive { ast_id, .. } => { + let node = ast_id.to_node(db.upcast()); + (ast_id.file_id, SyntaxNodePtr::from(AstPtr::new(&node))) + } + }; + sink.push(MacroError { file, node: ast, message: message.clone() }); + } + } + } for decl in self.declarations(db) { match decl { crate::ModuleDef::Function(f) => f.diagnostics(db, sink), @@ -865,7 +1003,37 @@ impl Function { pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) { let krate = self.module(db).id.krate(); - hir_def::diagnostics::validate_body(db.upcast(), self.id.into(), sink); + + let source_map = db.body_with_source_map(self.id.into()).1; + for diag in source_map.diagnostics() { + match diag { + BodyDiagnostic::InactiveCode { node, cfg, opts } => sink.push(InactiveCode { + file: node.file_id, + node: node.value.clone(), + cfg: cfg.clone(), + opts: opts.clone(), + }), + BodyDiagnostic::MacroError { node, message } => sink.push(MacroError { + file: node.file_id, + node: node.value.clone().into(), + message: message.to_string(), + }), + BodyDiagnostic::UnresolvedProcMacro { node } => sink.push(UnresolvedProcMacro { + file: node.file_id, + node: node.value.clone().into(), + precise_location: None, + macro_name: None, + }), + BodyDiagnostic::UnresolvedMacroCall { node, path } => { + sink.push(UnresolvedMacroCall { + file: node.file_id, + node: node.value.clone(), + path: path.clone(), + }) + } + } + } + hir_ty::diagnostics::validate_module_item(db, krate, self.id.into(), sink); hir_ty::diagnostics::validate_body(db, self.id.into(), sink); } -- cgit v1.2.3