Skip to content

Emit diagnostics for unresolved imports and extern crates #6016

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Sep 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions crates/hir_def/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,45 @@ impl Diagnostic for UnresolvedModule {
self
}
}

#[derive(Debug)]
pub struct UnresolvedExternCrate {
pub file: HirFileId,
pub item: AstPtr<ast::ExternCrate>,
}

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<SyntaxNodePtr> {
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<ast::UseTree>,
}

impl Diagnostic for UnresolvedImport {
fn code(&self) -> DiagnosticCode {
DiagnosticCode("unresolved-import")
}
fn message(&self) -> String {
"unresolved import".to_string()
}
fn display_source(&self) -> InFile<SyntaxNodePtr> {
InFile::new(self.file, self.node.clone().into())
}
fn as_any(&self) -> &(dyn Any + Send + 'static) {
self
}
}
6 changes: 5 additions & 1 deletion crates/hir_def/src/item_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,6 @@ pub enum AttrOwner {

Variant(Idx<Variant>),
Field(Idx<Field>),
// FIXME: Store variant and field attrs, and stop reparsing them in `attrs_query`.
}

macro_rules! from_attrs {
Expand Down Expand Up @@ -483,6 +482,11 @@ pub struct Import {
/// AST ID of the `use` or `extern crate` item this import was derived from. Note that many
/// `Import`s can map to the same `use` item.
pub ast_id: FileAstId<ast::Use>,
/// Index of this `Import` when the containing `Use` is visited via `ModPath::expand_use_item`.
///
/// This can be used to get the `UseTree` this `Import` corresponds to and allows emitting
/// precise diagnostics.
pub index: usize,
}

#[derive(Debug, Clone, Eq, PartialEq)]
Expand Down
3 changes: 2 additions & 1 deletion crates/hir_def/src/item_tree/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -482,14 +482,15 @@ impl Ctx {
ModPath::expand_use_item(
InFile::new(self.file, use_item.clone()),
&self.hygiene,
|path, _tree, is_glob, alias| {
|path, _use_tree, is_glob, alias| {
imports.push(id(tree.imports.alloc(Import {
path,
alias,
visibility,
is_glob,
is_prelude,
ast_id,
index: imports.len(),
})));
},
);
Expand Down
4 changes: 2 additions & 2 deletions crates/hir_def/src/item_tree/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,9 +228,9 @@ fn smoke() {

top-level items:
#[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("attr_on_use"))] }, input: None }]) }]
Import { path: ModPath { kind: Plain, segments: [Name(Text("a"))] }, alias: None, visibility: RawVisibilityId("pub(self)"), is_glob: false, is_prelude: false, ast_id: FileAstId::<syntax::ast::generated::nodes::Use>(0) }
Import { path: ModPath { kind: Plain, segments: [Name(Text("a"))] }, alias: None, visibility: RawVisibilityId("pub(self)"), is_glob: false, is_prelude: false, ast_id: FileAstId::<syntax::ast::generated::nodes::Use>(0), index: 0 }
#[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("attr_on_use"))] }, input: None }]) }]
Import { path: ModPath { kind: Plain, segments: [Name(Text("b"))] }, alias: None, visibility: RawVisibilityId("pub(self)"), is_glob: true, is_prelude: false, ast_id: FileAstId::<syntax::ast::generated::nodes::Use>(0) }
Import { path: ModPath { kind: Plain, segments: [Name(Text("b"))] }, alias: None, visibility: RawVisibilityId("pub(self)"), is_glob: true, is_prelude: false, ast_id: FileAstId::<syntax::ast::generated::nodes::Use>(0), index: 1 }
#[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("ext_crate"))] }, input: None }]) }]
ExternCrate { path: ModPath { kind: Plain, segments: [Name(Text("krate"))] }, alias: None, visibility: RawVisibilityId("pub(self)"), is_macro_use: false, ast_id: FileAstId::<syntax::ast::generated::nodes::ExternCrate>(1) }
#[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("on_trait"))] }, input: None }]) }]
Expand Down
93 changes: 81 additions & 12 deletions crates/hir_def/src/nameres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,38 +288,107 @@ pub enum ModuleSource {

mod diagnostics {
use hir_expand::diagnostics::DiagnosticSink;
use hir_expand::hygiene::Hygiene;
use hir_expand::InFile;
use syntax::{ast, AstPtr};

use crate::{db::DefDatabase, diagnostics::UnresolvedModule, nameres::LocalModuleId, AstId};
use crate::path::ModPath;
use crate::{db::DefDatabase, diagnostics::*, nameres::LocalModuleId, AstId};

#[derive(Debug, PartialEq, Eq)]
pub(super) enum DefDiagnostic {
UnresolvedModule {
module: LocalModuleId,
declaration: AstId<ast::Module>,
candidate: String,
},
enum DiagnosticKind {
UnresolvedModule { declaration: AstId<ast::Module>, candidate: String },

UnresolvedExternCrate { ast: AstId<ast::ExternCrate> },

UnresolvedImport { ast: AstId<ast::Use>, index: usize },
}

#[derive(Debug, PartialEq, Eq)]
pub(super) struct DefDiagnostic {
in_module: LocalModuleId,
kind: DiagnosticKind,
}

impl DefDiagnostic {
pub(super) fn unresolved_module(
container: LocalModuleId,
declaration: AstId<ast::Module>,
candidate: String,
) -> Self {
Self {
in_module: container,
kind: DiagnosticKind::UnresolvedModule { declaration, candidate },
}
}

pub(super) fn unresolved_extern_crate(
container: LocalModuleId,
declaration: AstId<ast::ExternCrate>,
) -> Self {
Self {
in_module: container,
kind: DiagnosticKind::UnresolvedExternCrate { ast: declaration },
}
}

pub(super) fn unresolved_import(
container: LocalModuleId,
ast: AstId<ast::Use>,
index: usize,
) -> Self {
Self { in_module: container, kind: DiagnosticKind::UnresolvedImport { ast, index } }
}

pub(super) fn add_to(
&self,
db: &dyn DefDatabase,
target_module: LocalModuleId,
sink: &mut DiagnosticSink,
) {
match self {
DefDiagnostic::UnresolvedModule { module, declaration, candidate } => {
if *module != target_module {
return;
}
if self.in_module != target_module {
return;
}

match &self.kind {
DiagnosticKind::UnresolvedModule { declaration, candidate } => {
let decl = declaration.to_node(db.upcast());
sink.push(UnresolvedModule {
file: declaration.file_id,
decl: AstPtr::new(&decl),
candidate: candidate.clone(),
})
}

DiagnosticKind::UnresolvedExternCrate { ast } => {
let item = ast.to_node(db.upcast());
sink.push(UnresolvedExternCrate {
file: ast.file_id,
item: AstPtr::new(&item),
});
}

DiagnosticKind::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(
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) });
}
}
}
}
}
Expand Down
Loading