blob: e2cf5b07897dc2903134d8b98f8f4b13d3949248 [file] [log] [blame]
//! HIR (previously known as descriptors) provides a high-level object-oriented
//! access to Rust code.
//!
//! The principal difference between HIR and syntax trees is that HIR is bound
//! to a particular crate instance. That is, it has cfg flags and features
//! applied. So, the relation between syntax and HIR is many-to-one.
//!
//! HIR is the public API of the all of the compiler logic above syntax trees.
//! It is written in "OO" style. Each type is self contained (as in, it knows its
//! parents and full context). It should be "clean code".
//!
//! `hir_*` crates are the implementation of the compiler logic.
//! They are written in "ECS" style, with relatively little abstractions.
//! Many types are not self-contained, and explicitly use local indexes, arenas, etc.
//!
//! `hir` is what insulates the "we don't know how to actually write an incremental compiler"
//! from the ide with completions, hovers, etc. It is a (soft, internal) boundary:
//! <https://www.tedinski.com/2018/02/06/system-boundaries.html>.
#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
#![recursion_limit = "512"]
mod semantics;
mod source_analyzer;
mod attrs;
mod from_id;
mod has_source;
pub mod db;
pub mod diagnostics;
pub mod symbols;
pub mod term_search;
mod display;
use std::{mem::discriminant, ops::ControlFlow};
use arrayvec::ArrayVec;
use base_db::{CrateDisplayName, CrateId, CrateOrigin};
use either::Either;
use hir_def::{
body::{BodyDiagnostic, SyntheticSyntax},
data::adt::VariantData,
generics::{LifetimeParamData, TypeOrConstParamData, TypeParamProvenance},
hir::{BindingAnnotation, BindingId, ExprId, ExprOrPatId, LabelId, Pat},
item_tree::{AttrOwner, FieldParent, ItemTreeFieldId, ItemTreeNode},
lang_item::LangItemTarget,
layout::{self, ReprOptions, TargetDataLayout},
nameres::{self, diagnostics::DefDiagnostic},
path::ImportAlias,
per_ns::PerNs,
resolver::{HasResolver, Resolver},
AssocItemId, AssocItemLoc, AttrDefId, CallableDefId, ConstId, ConstParamId, CrateRootModuleId,
DefWithBodyId, EnumId, EnumVariantId, ExternCrateId, FunctionId, GenericDefId, GenericParamId,
HasModule, ImplId, InTypeConstId, ItemContainerId, LifetimeParamId, LocalFieldId, Lookup,
MacroExpander, ModuleId, StaticId, StructId, TraitAliasId, TraitId, TupleId, TypeAliasId,
TypeOrConstParamId, TypeParamId, UnionId,
};
use hir_expand::{
attrs::collect_attrs, proc_macro::ProcMacroKind, AstId, MacroCallKind, ValueResult,
};
use hir_ty::{
all_super_traits, autoderef, check_orphan_rules,
consteval::{try_const_usize, unknown_const_as_generic, ConstExt},
diagnostics::BodyValidationDiagnostic,
error_lifetime, known_const_to_ast,
layout::{Layout as TyLayout, RustcEnumVariantIdx, RustcFieldIdx, TagEncoding},
method_resolution,
mir::{interpret_mir, MutBorrowKind},
primitive::UintTy,
traits::FnTrait,
AliasTy, CallableSig, Canonical, CanonicalVarKinds, Cast, ClosureId, GenericArg,
GenericArgData, Interner, ParamKind, QuantifiedWhereClause, Scalar, Substitution,
TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyDefId, TyExt, TyKind, ValueTyDefId,
WhereClause,
};
use itertools::Itertools;
use nameres::diagnostics::DefDiagnosticKind;
use rustc_hash::FxHashSet;
use smallvec::SmallVec;
use span::{Edition, EditionedFileId, FileId, MacroCallId, SyntaxContextId};
use stdx::{format_to, impl_from, never};
use syntax::{
ast::{self, HasAttrs as _, HasGenericParams, HasName},
format_smolstr, AstNode, AstPtr, SmolStr, SyntaxNode, SyntaxNodePtr, TextRange, ToSmolStr, T,
};
use triomphe::Arc;
use crate::db::{DefDatabase, HirDatabase};
pub use crate::{
attrs::{resolve_doc_path_on, HasAttrs},
diagnostics::*,
has_source::HasSource,
semantics::{
PathResolution, Semantics, SemanticsImpl, SemanticsScope, TypeInfo, VisibleTraits,
},
};
pub use hir_ty::method_resolution::TyFingerprint;
// Be careful with these re-exports.
//
// `hir` is the boundary between the compiler and the IDE. It should try hard to
// isolate the compiler from the ide, to allow the two to be refactored
// independently. Re-exporting something from the compiler is the sure way to
// breach the boundary.
//
// Generally, a refactoring which *removes* a name from this list is a good
// idea!
pub use {
cfg::{CfgAtom, CfgExpr, CfgOptions},
hir_def::{
attr::{AttrSourceMap, Attrs, AttrsWithOwner},
data::adt::StructKind,
find_path::PrefixKind,
import_map,
lang_item::LangItem,
nameres::{DefMap, ModuleSource},
path::{ModPath, PathKind},
per_ns::Namespace,
type_ref::{Mutability, TypeRef},
visibility::Visibility,
ImportPathConfig,
// FIXME: This is here since some queries take it as input that are used
// outside of hir.
{AdtId, MacroId, ModuleDefId},
},
hir_expand::{
attrs::{Attr, AttrId},
change::ChangeWithProcMacros,
files::{
FilePosition, FilePositionWrapper, FileRange, FileRangeWrapper, HirFilePosition,
HirFileRange, InFile, InFileWrapper, InMacroFile, InRealFile, MacroFilePosition,
MacroFileRange,
},
hygiene::{marks_rev, SyntaxContextExt},
inert_attr_macro::AttributeTemplate,
name::Name,
prettify_macro_expansion,
proc_macro::{ProcMacros, ProcMacrosBuilder},
tt, ExpandResult, HirFileId, HirFileIdExt, MacroFileId, MacroFileIdExt,
},
hir_ty::{
consteval::ConstEvalError,
display::{ClosureStyle, HirDisplay, HirDisplayError, HirWrite},
dyn_compatibility::{DynCompatibilityViolation, MethodViolationCode},
layout::LayoutError,
mir::{MirEvalError, MirLowerError},
CastError, FnAbi, PointerCast, Safety,
},
// FIXME: Properly encapsulate mir
hir_ty::{mir, Interner as ChalkTyInterner},
intern::{sym, Symbol},
};
// These are negative re-exports: pub using these names is forbidden, they
// should remain private to hir internals.
#[allow(unused)]
use {
hir_def::path::Path,
hir_expand::{
name::AsName,
span_map::{ExpansionSpanMap, RealSpanMap, SpanMap, SpanMapRef},
},
};
/// hir::Crate describes a single crate. It's the main interface with which
/// a crate's dependencies interact. Mostly, it should be just a proxy for the
/// root module.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Crate {
pub(crate) id: CrateId,
}
#[derive(Debug)]
pub struct CrateDependency {
pub krate: Crate,
pub name: Name,
}
impl Crate {
pub fn origin(self, db: &dyn HirDatabase) -> CrateOrigin {
db.crate_graph()[self.id].origin.clone()
}
pub fn is_builtin(self, db: &dyn HirDatabase) -> bool {
matches!(self.origin(db), CrateOrigin::Lang(_))
}
pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
db.crate_graph()[self.id]
.dependencies
.iter()
.map(|dep| {
let krate = Crate { id: dep.crate_id };
let name = dep.as_name();
CrateDependency { krate, name }
})
.collect()
}
pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
let crate_graph = db.crate_graph();
crate_graph
.iter()
.filter(|&krate| {
crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
})
.map(|id| Crate { id })
.collect()
}
pub fn transitive_reverse_dependencies(
self,
db: &dyn HirDatabase,
) -> impl Iterator<Item = Crate> {
db.crate_graph().transitive_rev_deps(self.id).map(|id| Crate { id })
}
pub fn root_module(self) -> Module {
Module { id: CrateRootModuleId::from(self.id).into() }
}
pub fn modules(self, db: &dyn HirDatabase) -> Vec<Module> {
let def_map = db.crate_def_map(self.id);
def_map.modules().map(|(id, _)| def_map.module_id(id).into()).collect()
}
pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
db.crate_graph()[self.id].root_file_id
}
pub fn edition(self, db: &dyn HirDatabase) -> Edition {
db.crate_graph()[self.id].edition
}
pub fn version(self, db: &dyn HirDatabase) -> Option<String> {
db.crate_graph()[self.id].version.clone()
}
pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
db.crate_graph()[self.id].display_name.clone()
}
pub fn query_external_importables(
self,
db: &dyn DefDatabase,
query: import_map::Query,
) -> impl Iterator<Item = Either<ModuleDef, Macro>> {
let _p = tracing::info_span!("query_external_importables").entered();
import_map::search_dependencies(db, self.into(), &query).into_iter().map(|item| {
match ItemInNs::from(item) {
ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id),
ItemInNs::Macros(mac_id) => Either::Right(mac_id),
}
})
}
pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
db.crate_graph().iter().map(|id| Crate { id }).collect()
}
/// Try to get the root URL of the documentation of a crate.
pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
// Look for #![doc(html_root_url = "...")]
let attrs = db.attrs(AttrDefId::ModuleId(self.root_module().into()));
let doc_url = attrs.by_key(&sym::doc).find_string_value_in_tt(&sym::html_root_url);
doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
}
pub fn cfg(&self, db: &dyn HirDatabase) -> Arc<CfgOptions> {
db.crate_graph()[self.id].cfg_options.clone()
}
pub fn potential_cfg(&self, db: &dyn HirDatabase) -> Arc<CfgOptions> {
let data = &db.crate_graph()[self.id];
data.potential_cfg_options.clone().unwrap_or_else(|| data.cfg_options.clone())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Module {
pub(crate) id: ModuleId,
}
/// The defs which can be visible in the module.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ModuleDef {
Module(Module),
Function(Function),
Adt(Adt),
// Can't be directly declared, but can be imported.
Variant(Variant),
Const(Const),
Static(Static),
Trait(Trait),
TraitAlias(TraitAlias),
TypeAlias(TypeAlias),
BuiltinType(BuiltinType),
Macro(Macro),
}
impl_from!(
Module,
Function,
Adt(Struct, Enum, Union),
Variant,
Const,
Static,
Trait,
TraitAlias,
TypeAlias,
BuiltinType,
Macro
for ModuleDef
);
impl From<VariantDef> for ModuleDef {
fn from(var: VariantDef) -> Self {
match var {
VariantDef::Struct(t) => Adt::from(t).into(),
VariantDef::Union(t) => Adt::from(t).into(),
VariantDef::Variant(t) => t.into(),
}
}
}
impl ModuleDef {
pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
match self {
ModuleDef::Module(it) => it.parent(db),
ModuleDef::Function(it) => Some(it.module(db)),
ModuleDef::Adt(it) => Some(it.module(db)),
ModuleDef::Variant(it) => Some(it.module(db)),
ModuleDef::Const(it) => Some(it.module(db)),
ModuleDef::Static(it) => Some(it.module(db)),
ModuleDef::Trait(it) => Some(it.module(db)),
ModuleDef::TraitAlias(it) => Some(it.module(db)),
ModuleDef::TypeAlias(it) => Some(it.module(db)),
ModuleDef::Macro(it) => Some(it.module(db)),
ModuleDef::BuiltinType(_) => None,
}
}
pub fn canonical_path(&self, db: &dyn HirDatabase, edition: Edition) -> Option<String> {
let mut segments = vec![self.name(db)?];
for m in self.module(db)?.path_to_root(db) {
segments.extend(m.name(db))
}
segments.reverse();
Some(segments.iter().map(|it| it.display(db.upcast(), edition)).join("::"))
}
pub fn canonical_module_path(
&self,
db: &dyn HirDatabase,
) -> Option<impl Iterator<Item = Module>> {
self.module(db).map(|it| it.path_to_root(db).into_iter().rev())
}
pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
let name = match self {
ModuleDef::Module(it) => it.name(db)?,
ModuleDef::Const(it) => it.name(db)?,
ModuleDef::Adt(it) => it.name(db),
ModuleDef::Trait(it) => it.name(db),
ModuleDef::TraitAlias(it) => it.name(db),
ModuleDef::Function(it) => it.name(db),
ModuleDef::Variant(it) => it.name(db),
ModuleDef::TypeAlias(it) => it.name(db),
ModuleDef::Static(it) => it.name(db),
ModuleDef::Macro(it) => it.name(db),
ModuleDef::BuiltinType(it) => it.name(),
};
Some(name)
}
pub fn diagnostics(self, db: &dyn HirDatabase, style_lints: bool) -> Vec<AnyDiagnostic> {
let id = match self {
ModuleDef::Adt(it) => match it {
Adt::Struct(it) => it.id.into(),
Adt::Enum(it) => it.id.into(),
Adt::Union(it) => it.id.into(),
},
ModuleDef::Trait(it) => it.id.into(),
ModuleDef::TraitAlias(it) => it.id.into(),
ModuleDef::Function(it) => it.id.into(),
ModuleDef::TypeAlias(it) => it.id.into(),
ModuleDef::Module(it) => it.id.into(),
ModuleDef::Const(it) => it.id.into(),
ModuleDef::Static(it) => it.id.into(),
ModuleDef::Variant(it) => it.id.into(),
ModuleDef::BuiltinType(_) | ModuleDef::Macro(_) => return Vec::new(),
};
let mut acc = Vec::new();
match self.as_def_with_body() {
Some(def) => {
def.diagnostics(db, &mut acc, style_lints);
}
None => {
for diag in hir_ty::diagnostics::incorrect_case(db, id) {
acc.push(diag.into())
}
}
}
acc
}
pub fn as_def_with_body(self) -> Option<DefWithBody> {
match self {
ModuleDef::Function(it) => Some(it.into()),
ModuleDef::Const(it) => Some(it.into()),
ModuleDef::Static(it) => Some(it.into()),
ModuleDef::Variant(it) => Some(it.into()),
ModuleDef::Module(_)
| ModuleDef::Adt(_)
| ModuleDef::Trait(_)
| ModuleDef::TraitAlias(_)
| ModuleDef::TypeAlias(_)
| ModuleDef::Macro(_)
| ModuleDef::BuiltinType(_) => None,
}
}
pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
Some(match self {
ModuleDef::Module(it) => it.attrs(db),
ModuleDef::Function(it) => it.attrs(db),
ModuleDef::Adt(it) => it.attrs(db),
ModuleDef::Variant(it) => it.attrs(db),
ModuleDef::Const(it) => it.attrs(db),
ModuleDef::Static(it) => it.attrs(db),
ModuleDef::Trait(it) => it.attrs(db),
ModuleDef::TraitAlias(it) => it.attrs(db),
ModuleDef::TypeAlias(it) => it.attrs(db),
ModuleDef::Macro(it) => it.attrs(db),
ModuleDef::BuiltinType(_) => return None,
})
}
}
impl HasVisibility for ModuleDef {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
match *self {
ModuleDef::Module(it) => it.visibility(db),
ModuleDef::Function(it) => it.visibility(db),
ModuleDef::Adt(it) => it.visibility(db),
ModuleDef::Const(it) => it.visibility(db),
ModuleDef::Static(it) => it.visibility(db),
ModuleDef::Trait(it) => it.visibility(db),
ModuleDef::TraitAlias(it) => it.visibility(db),
ModuleDef::TypeAlias(it) => it.visibility(db),
ModuleDef::Variant(it) => it.visibility(db),
ModuleDef::Macro(it) => it.visibility(db),
ModuleDef::BuiltinType(_) => Visibility::Public,
}
}
}
impl Module {
/// Name of this module.
pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
self.id.name(db.upcast())
}
/// Returns the crate this module is part of.
pub fn krate(self) -> Crate {
Crate { id: self.id.krate() }
}
/// Topmost parent of this module. Every module has a `crate_root`, but some
/// might be missing `krate`. This can happen if a module's file is not included
/// in the module tree of any target in `Cargo.toml`.
pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
let def_map = db.crate_def_map(self.id.krate());
Module { id: def_map.crate_root().into() }
}
pub fn is_crate_root(self) -> bool {
DefMap::ROOT == self.id.local_id
}
/// Iterates over all child modules.
pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
let def_map = self.id.def_map(db.upcast());
let children = def_map[self.id.local_id]
.children
.values()
.map(|module_id| Module { id: def_map.module_id(*module_id) })
.collect::<Vec<_>>();
children.into_iter()
}
/// Finds a parent module.
pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
// FIXME: handle block expressions as modules (their parent is in a different DefMap)
let def_map = self.id.def_map(db.upcast());
let parent_id = def_map[self.id.local_id].parent?;
Some(Module { id: def_map.module_id(parent_id) })
}
/// Finds nearest non-block ancestor `Module` (`self` included).
pub fn nearest_non_block_module(self, db: &dyn HirDatabase) -> Module {
let mut id = self.id;
while id.is_block_module() {
id = id.containing_module(db.upcast()).expect("block without parent module");
}
Module { id }
}
pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
let mut res = vec![self];
let mut curr = self;
while let Some(next) = curr.parent(db) {
res.push(next);
curr = next
}
res
}
/// Returns a `ModuleScope`: a set of items, visible in this module.
pub fn scope(
self,
db: &dyn HirDatabase,
visible_from: Option<Module>,
) -> Vec<(Name, ScopeDef)> {
self.id.def_map(db.upcast())[self.id.local_id]
.scope
.entries()
.filter_map(|(name, def)| {
if let Some(m) = visible_from {
let filtered =
def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
if filtered.is_none() && !def.is_none() {
None
} else {
Some((name, filtered))
}
} else {
Some((name, def))
}
})
.flat_map(|(name, def)| {
ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
})
.collect()
}
/// Fills `acc` with the module's diagnostics.
pub fn diagnostics(
self,
db: &dyn HirDatabase,
acc: &mut Vec<AnyDiagnostic>,
style_lints: bool,
) {
let _p = tracing::info_span!("Module::diagnostics", name = ?self.name(db)).entered();
let edition = db.crate_graph()[self.id.krate()].edition;
let def_map = self.id.def_map(db.upcast());
for diag in def_map.diagnostics() {
if diag.in_module != self.id.local_id {
// FIXME: This is accidentally quadratic.
continue;
}
emit_def_diagnostic(db, acc, diag, edition);
}
if !self.id.is_block_module() {
// These are reported by the body of block modules
let scope = &def_map[self.id.local_id].scope;
scope.all_macro_calls().for_each(|it| macro_call_diagnostics(db, it, acc));
}
for def in self.declarations(db) {
match def {
ModuleDef::Module(m) => {
// Only add diagnostics from inline modules
if def_map[m.id.local_id].origin.is_inline() {
m.diagnostics(db, acc, style_lints)
}
acc.extend(def.diagnostics(db, style_lints))
}
ModuleDef::Trait(t) => {
for diag in db.trait_data_with_diagnostics(t.id).1.iter() {
emit_def_diagnostic(db, acc, diag, edition);
}
for item in t.items(db) {
item.diagnostics(db, acc, style_lints);
}
t.all_macro_calls(db)
.iter()
.for_each(|&(_ast, call_id)| macro_call_diagnostics(db, call_id, acc));
acc.extend(def.diagnostics(db, style_lints))
}
ModuleDef::Adt(adt) => {
match adt {
Adt::Struct(s) => {
for diag in db.struct_data_with_diagnostics(s.id).1.iter() {
emit_def_diagnostic(db, acc, diag, edition);
}
}
Adt::Union(u) => {
for diag in db.union_data_with_diagnostics(u.id).1.iter() {
emit_def_diagnostic(db, acc, diag, edition);
}
}
Adt::Enum(e) => {
for v in e.variants(db) {
acc.extend(ModuleDef::Variant(v).diagnostics(db, style_lints));
for diag in db.enum_variant_data_with_diagnostics(v.id).1.iter() {
emit_def_diagnostic(db, acc, diag, edition);
}
}
}
}
acc.extend(def.diagnostics(db, style_lints))
}
ModuleDef::Macro(m) => emit_macro_def_diagnostics(db, acc, m),
_ => acc.extend(def.diagnostics(db, style_lints)),
}
}
self.legacy_macros(db).into_iter().for_each(|m| emit_macro_def_diagnostics(db, acc, m));
let inherent_impls = db.inherent_impls_in_crate(self.id.krate());
let mut impl_assoc_items_scratch = vec![];
for impl_def in self.impl_defs(db) {
let loc = impl_def.id.lookup(db.upcast());
let tree = loc.id.item_tree(db.upcast());
let node = &tree[loc.id.value];
let file_id = loc.id.file_id();
if file_id.macro_file().map_or(false, |it| it.is_builtin_derive(db.upcast())) {
// these expansion come from us, diagnosing them is a waste of resources
// FIXME: Once we diagnose the inputs to builtin derives, we should at least extract those diagnostics somehow
continue;
}
impl_def
.all_macro_calls(db)
.iter()
.for_each(|&(_ast, call_id)| macro_call_diagnostics(db, call_id, acc));
let ast_id_map = db.ast_id_map(file_id);
for diag in db.impl_data_with_diagnostics(impl_def.id).1.iter() {
emit_def_diagnostic(db, acc, diag, edition);
}
if inherent_impls.invalid_impls().contains(&impl_def.id) {
acc.push(IncoherentImpl { impl_: ast_id_map.get(node.ast_id()), file_id }.into())
}
if !impl_def.check_orphan_rules(db) {
acc.push(TraitImplOrphan { impl_: ast_id_map.get(node.ast_id()), file_id }.into())
}
let trait_ = impl_def.trait_(db);
let trait_is_unsafe = trait_.map_or(false, |t| t.is_unsafe(db));
let impl_is_negative = impl_def.is_negative(db);
let impl_is_unsafe = impl_def.is_unsafe(db);
let drop_maybe_dangle = (|| {
// FIXME: This can be simplified a lot by exposing hir-ty's utils.rs::Generics helper
let trait_ = trait_?;
let drop_trait = db.lang_item(self.krate().into(), LangItem::Drop)?.as_trait()?;
if drop_trait != trait_.into() {
return None;
}
let parent = impl_def.id.into();
let generic_params = db.generic_params(parent);
let lifetime_params = generic_params.iter_lt().map(|(local_id, _)| {
GenericParamId::LifetimeParamId(LifetimeParamId { parent, local_id })
});
let type_params = generic_params
.iter_type_or_consts()
.filter(|(_, it)| it.type_param().is_some())
.map(|(local_id, _)| {
GenericParamId::TypeParamId(TypeParamId::from_unchecked(
TypeOrConstParamId { parent, local_id },
))
});
let res = type_params.chain(lifetime_params).any(|p| {
db.attrs(AttrDefId::GenericParamId(p)).by_key(&sym::may_dangle).exists()
});
Some(res)
})()
.unwrap_or(false);
match (impl_is_unsafe, trait_is_unsafe, impl_is_negative, drop_maybe_dangle) {
// unsafe negative impl
(true, _, true, _) |
// unsafe impl for safe trait
(true, false, _, false) => acc.push(TraitImplIncorrectSafety { impl_: ast_id_map.get(node.ast_id()), file_id, should_be_safe: true }.into()),
// safe impl for unsafe trait
(false, true, false, _) |
// safe impl of dangling drop
(false, false, _, true) => acc.push(TraitImplIncorrectSafety { impl_: ast_id_map.get(node.ast_id()), file_id, should_be_safe: false }.into()),
_ => (),
};
// Negative impls can't have items, don't emit missing items diagnostic for them
if let (false, Some(trait_)) = (impl_is_negative, trait_) {
let items = &db.trait_data(trait_.into()).items;
let required_items = items.iter().filter(|&(_, assoc)| match *assoc {
AssocItemId::FunctionId(it) => !db.function_data(it).has_body(),
AssocItemId::ConstId(id) => !db.const_data(id).has_body,
AssocItemId::TypeAliasId(it) => db.type_alias_data(it).type_ref.is_none(),
});
impl_assoc_items_scratch.extend(db.impl_data(impl_def.id).items.iter().filter_map(
|&item| {
Some((
item,
match item {
AssocItemId::FunctionId(it) => db.function_data(it).name.clone(),
AssocItemId::ConstId(it) => {
db.const_data(it).name.as_ref()?.clone()
}
AssocItemId::TypeAliasId(it) => db.type_alias_data(it).name.clone(),
},
))
},
));
let redundant = impl_assoc_items_scratch
.iter()
.filter(|(id, name)| {
!items.iter().any(|(impl_name, impl_item)| {
discriminant(impl_item) == discriminant(id) && impl_name == name
})
})
.map(|(item, name)| (name.clone(), AssocItem::from(*item)));
for (name, assoc_item) in redundant {
acc.push(
TraitImplRedundantAssocItems {
trait_,
file_id,
impl_: ast_id_map.get(node.ast_id()),
assoc_item: (name, assoc_item),
}
.into(),
)
}
let missing: Vec<_> = required_items
.filter(|(name, id)| {
!impl_assoc_items_scratch.iter().any(|(impl_item, impl_name)| {
discriminant(impl_item) == discriminant(id) && impl_name == name
})
})
.map(|(name, item)| (name.clone(), AssocItem::from(*item)))
.collect();
if !missing.is_empty() {
acc.push(
TraitImplMissingAssocItems {
impl_: ast_id_map.get(node.ast_id()),
file_id,
missing,
}
.into(),
)
}
impl_assoc_items_scratch.clear();
}
for &item in db.impl_data(impl_def.id).items.iter() {
AssocItem::from(item).diagnostics(db, acc, style_lints);
}
}
}
pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
let def_map = self.id.def_map(db.upcast());
let scope = &def_map[self.id.local_id].scope;
scope
.declarations()
.map(ModuleDef::from)
.chain(scope.unnamed_consts().map(|id| ModuleDef::Const(Const::from(id))))
.collect()
}
pub fn legacy_macros(self, db: &dyn HirDatabase) -> Vec<Macro> {
let def_map = self.id.def_map(db.upcast());
let scope = &def_map[self.id.local_id].scope;
scope.legacy_macros().flat_map(|(_, it)| it).map(|&it| it.into()).collect()
}
pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
let def_map = self.id.def_map(db.upcast());
def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
}
/// Finds a path that can be used to refer to the given item from within
/// this module, if possible.
pub fn find_path(
self,
db: &dyn DefDatabase,
item: impl Into<ItemInNs>,
cfg: ImportPathConfig,
) -> Option<ModPath> {
hir_def::find_path::find_path(
db,
item.into().into(),
self.into(),
PrefixKind::Plain,
false,
cfg,
)
}
/// Finds a path that can be used to refer to the given item from within
/// this module, if possible. This is used for returning import paths for use-statements.
pub fn find_use_path(
self,
db: &dyn DefDatabase,
item: impl Into<ItemInNs>,
prefix_kind: PrefixKind,
cfg: ImportPathConfig,
) -> Option<ModPath> {
hir_def::find_path::find_path(db, item.into().into(), self.into(), prefix_kind, true, cfg)
}
}
fn macro_call_diagnostics(
db: &dyn HirDatabase,
macro_call_id: MacroCallId,
acc: &mut Vec<AnyDiagnostic>,
) {
let Some(e) = db.parse_macro_expansion_error(macro_call_id) else {
return;
};
let ValueResult { value: parse_errors, err } = &*e;
if let Some(err) = err {
let loc = db.lookup_intern_macro_call(macro_call_id);
let file_id = loc.kind.file_id();
let node =
InFile::new(file_id, db.ast_id_map(file_id).get_erased(loc.kind.erased_ast_id()));
let (message, error) = err.render_to_string(db.upcast());
let precise_location = if err.span().anchor.file_id == file_id {
Some(
err.span().range
+ db.ast_id_map(err.span().anchor.file_id.into())
.get_erased(err.span().anchor.ast_id)
.text_range()
.start(),
)
} else {
None
};
acc.push(MacroError { node, precise_location, message, error }.into());
}
if !parse_errors.is_empty() {
let loc = db.lookup_intern_macro_call(macro_call_id);
let (node, precise_location) = precise_macro_call_location(&loc.kind, db);
acc.push(
MacroExpansionParseError { node, precise_location, errors: parse_errors.clone() }
.into(),
)
}
}
fn emit_macro_def_diagnostics(db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>, m: Macro) {
let id = db.macro_def(m.id);
if let hir_expand::db::TokenExpander::DeclarativeMacro(expander) = db.macro_expander(id) {
if let Some(e) = expander.mac.err() {
let Some(ast) = id.ast_id().left() else {
never!("declarative expander for non decl-macro: {:?}", e);
return;
};
let krate = HasModule::krate(&m.id, db.upcast());
let edition = db.crate_graph()[krate].edition;
emit_def_diagnostic_(
db,
acc,
&DefDiagnosticKind::MacroDefError { ast, message: e.to_string() },
edition,
);
}
}
}
fn emit_def_diagnostic(
db: &dyn HirDatabase,
acc: &mut Vec<AnyDiagnostic>,
diag: &DefDiagnostic,
edition: Edition,
) {
emit_def_diagnostic_(db, acc, &diag.kind, edition)
}
fn emit_def_diagnostic_(
db: &dyn HirDatabase,
acc: &mut Vec<AnyDiagnostic>,
diag: &DefDiagnosticKind,
edition: Edition,
) {
match diag {
DefDiagnosticKind::UnresolvedModule { ast: declaration, candidates } => {
let decl = declaration.to_ptr(db.upcast());
acc.push(
UnresolvedModule {
decl: InFile::new(declaration.file_id, decl),
candidates: candidates.clone(),
}
.into(),
)
}
DefDiagnosticKind::UnresolvedExternCrate { ast } => {
let item = ast.to_ptr(db.upcast());
acc.push(UnresolvedExternCrate { decl: InFile::new(ast.file_id, item) }.into());
}
DefDiagnosticKind::MacroError { ast, path, err } => {
let item = ast.to_ptr(db.upcast());
let (message, error) = err.render_to_string(db.upcast());
acc.push(
MacroError {
node: InFile::new(ast.file_id, item.syntax_node_ptr()),
precise_location: None,
message: format!("{}: {message}", path.display(db.upcast(), edition)),
error,
}
.into(),
)
}
DefDiagnosticKind::UnresolvedImport { id, index } => {
let file_id = id.file_id();
let item_tree = id.item_tree(db.upcast());
let import = &item_tree[id.value];
let use_tree = import.use_tree_to_ast(db.upcast(), file_id, *index);
acc.push(
UnresolvedImport { decl: InFile::new(file_id, AstPtr::new(&use_tree)) }.into(),
);
}
DefDiagnosticKind::UnconfiguredCode { tree, item, cfg, opts } => {
let item_tree = tree.item_tree(db.upcast());
let ast_id_map = db.ast_id_map(tree.file_id());
// FIXME: This parses... We could probably store relative ranges for the children things
// here in the item tree?
(|| {
let process_field_list =
|field_list: Option<_>, idx: ItemTreeFieldId| match field_list? {
ast::FieldList::RecordFieldList(it) => Some(SyntaxNodePtr::new(
it.fields().nth(idx.into_raw().into_u32() as usize)?.syntax(),
)),
ast::FieldList::TupleFieldList(it) => Some(SyntaxNodePtr::new(
it.fields().nth(idx.into_raw().into_u32() as usize)?.syntax(),
)),
};
let ptr = match *item {
AttrOwner::ModItem(it) => {
ast_id_map.get(it.ast_id(&item_tree)).syntax_node_ptr()
}
AttrOwner::TopLevel => ast_id_map.root(),
AttrOwner::Variant(it) => {
ast_id_map.get(item_tree[it].ast_id).syntax_node_ptr()
}
AttrOwner::Field(FieldParent::Variant(parent), idx) => process_field_list(
ast_id_map
.get(item_tree[parent].ast_id)
.to_node(&db.parse_or_expand(tree.file_id()))
.field_list(),
idx,
)?,
AttrOwner::Field(FieldParent::Struct(parent), idx) => process_field_list(
ast_id_map
.get(item_tree[parent.index()].ast_id)
.to_node(&db.parse_or_expand(tree.file_id()))
.field_list(),
idx,
)?,
AttrOwner::Field(FieldParent::Union(parent), idx) => SyntaxNodePtr::new(
ast_id_map
.get(item_tree[parent.index()].ast_id)
.to_node(&db.parse_or_expand(tree.file_id()))
.record_field_list()?
.fields()
.nth(idx.into_raw().into_u32() as usize)?
.syntax(),
),
AttrOwner::Param(parent, idx) => SyntaxNodePtr::new(
ast_id_map
.get(item_tree[parent.index()].ast_id)
.to_node(&db.parse_or_expand(tree.file_id()))
.param_list()?
.params()
.nth(idx.into_raw().into_u32() as usize)?
.syntax(),
),
AttrOwner::TypeOrConstParamData(parent, idx) => SyntaxNodePtr::new(
ast_id_map
.get(parent.ast_id(&item_tree))
.to_node(&db.parse_or_expand(tree.file_id()))
.generic_param_list()?
.type_or_const_params()
.nth(idx.into_raw().into_u32() as usize)?
.syntax(),
),
AttrOwner::LifetimeParamData(parent, idx) => SyntaxNodePtr::new(
ast_id_map
.get(parent.ast_id(&item_tree))
.to_node(&db.parse_or_expand(tree.file_id()))
.generic_param_list()?
.lifetime_params()
.nth(idx.into_raw().into_u32() as usize)?
.syntax(),
),
};
acc.push(
InactiveCode {
node: InFile::new(tree.file_id(), ptr),
cfg: cfg.clone(),
opts: opts.clone(),
}
.into(),
);
Some(())
})();
}
DefDiagnosticKind::UnresolvedMacroCall { ast, path } => {
let (node, precise_location) = precise_macro_call_location(ast, db);
acc.push(
UnresolvedMacroCall {
macro_call: node,
precise_location,
path: path.clone(),
is_bang: matches!(ast, MacroCallKind::FnLike { .. }),
}
.into(),
);
}
DefDiagnosticKind::UnimplementedBuiltinMacro { ast } => {
let node = ast.to_node(db.upcast());
// Must have a name, otherwise we wouldn't emit it.
let name = node.name().expect("unimplemented builtin macro with no name");
acc.push(
UnimplementedBuiltinMacro {
node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&name))),
}
.into(),
);
}
DefDiagnosticKind::InvalidDeriveTarget { ast, id } => {
let node = ast.to_node(db.upcast());
let derive = node.attrs().nth(*id);
match derive {
Some(derive) => {
acc.push(
InvalidDeriveTarget {
node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
}
.into(),
);
}
None => stdx::never!("derive diagnostic on item without derive attribute"),
}
}
DefDiagnosticKind::MalformedDerive { ast, id } => {
let node = ast.to_node(db.upcast());
let derive = node.attrs().nth(*id);
match derive {
Some(derive) => {
acc.push(
MalformedDerive {
node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
}
.into(),
);
}
None => stdx::never!("derive diagnostic on item without derive attribute"),
}
}
DefDiagnosticKind::MacroDefError { ast, message } => {
let node = ast.to_node(db.upcast());
acc.push(
MacroDefError {
node: InFile::new(ast.file_id, AstPtr::new(&node)),
name: node.name().map(|it| it.syntax().text_range()),
message: message.clone(),
}
.into(),
);
}
}
}
fn precise_macro_call_location(
ast: &MacroCallKind,
db: &dyn HirDatabase,
) -> (InFile<SyntaxNodePtr>, Option<TextRange>) {
// FIXME: maybe we actually want slightly different ranges for the different macro diagnostics
// - e.g. the full attribute for macro errors, but only the name for name resolution
match ast {
MacroCallKind::FnLike { ast_id, .. } => {
let node = ast_id.to_node(db.upcast());
(
ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))),
node.path()
.and_then(|it| it.segment())
.and_then(|it| it.name_ref())
.map(|it| it.syntax().text_range()),
)
}
MacroCallKind::Derive { ast_id, derive_attr_index, derive_index, .. } => {
let node = ast_id.to_node(db.upcast());
// Compute the precise location of the macro name's token in the derive
// list.
let token = (|| {
let derive_attr = collect_attrs(&node)
.nth(derive_attr_index.ast_index())
.and_then(|x| Either::left(x.1))?;
let token_tree = derive_attr.meta()?.token_tree()?;
let group_by = token_tree
.syntax()
.children_with_tokens()
.filter_map(|elem| match elem {
syntax::NodeOrToken::Token(tok) => Some(tok),
_ => None,
})
.group_by(|t| t.kind() == T![,]);
let (_, mut group) = group_by
.into_iter()
.filter(|&(comma, _)| !comma)
.nth(*derive_index as usize)?;
group.find(|t| t.kind() == T![ident])
})();
(
ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))),
token.as_ref().map(|tok| tok.text_range()),
)
}
MacroCallKind::Attr { ast_id, invoc_attr_index, .. } => {
let node = ast_id.to_node(db.upcast());
let attr = collect_attrs(&node)
.nth(invoc_attr_index.ast_index())
.and_then(|x| Either::left(x.1))
.unwrap_or_else(|| {
panic!("cannot find attribute #{}", invoc_attr_index.ast_index())
});
(
ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&attr))),
Some(attr.syntax().text_range()),
)
}
}
}
impl HasVisibility for Module {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
let def_map = self.id.def_map(db.upcast());
let module_data = &def_map[self.id.local_id];
module_data.visibility
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Field {
pub(crate) parent: VariantDef,
pub(crate) id: LocalFieldId,
}
#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)]
pub struct TupleField {
pub owner: DefWithBodyId,
pub tuple: TupleId,
pub index: u32,
}
impl TupleField {
pub fn name(&self) -> Name {
Name::new_tuple_field(self.index as usize)
}
pub fn ty(&self, db: &dyn HirDatabase) -> Type {
let ty = db.infer(self.owner).tuple_field_access_types[&self.tuple]
.as_slice(Interner)
.get(self.index as usize)
.and_then(|arg| arg.ty(Interner))
.cloned()
.unwrap_or_else(|| TyKind::Error.intern(Interner));
Type { env: db.trait_environment_for_body(self.owner), ty }
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum FieldSource {
Named(ast::RecordField),
Pos(ast::TupleField),
}
impl AstNode for FieldSource {
fn can_cast(kind: syntax::SyntaxKind) -> bool
where
Self: Sized,
{
ast::RecordField::can_cast(kind) || ast::TupleField::can_cast(kind)
}
fn cast(syntax: SyntaxNode) -> Option<Self>
where
Self: Sized,
{
if ast::RecordField::can_cast(syntax.kind()) {
<ast::RecordField as AstNode>::cast(syntax).map(FieldSource::Named)
} else if ast::TupleField::can_cast(syntax.kind()) {
<ast::TupleField as AstNode>::cast(syntax).map(FieldSource::Pos)
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
match self {
FieldSource::Named(it) => it.syntax(),
FieldSource::Pos(it) => it.syntax(),
}
}
}
impl Field {
pub fn name(&self, db: &dyn HirDatabase) -> Name {
self.parent.variant_data(db).fields()[self.id].name.clone()
}
pub fn index(&self) -> usize {
u32::from(self.id.into_raw()) as usize
}
/// Returns the type as in the signature of the struct (i.e., with
/// placeholder types for type parameters). Only use this in the context of
/// the field definition.
pub fn ty(&self, db: &dyn HirDatabase) -> Type {
let var_id = self.parent.into();
let generic_def_id: GenericDefId = match self.parent {
VariantDef::Struct(it) => it.id.into(),
VariantDef::Union(it) => it.id.into(),
VariantDef::Variant(it) => it.id.lookup(db.upcast()).parent.into(),
};
let substs = TyBuilder::placeholder_subst(db, generic_def_id);
let ty = db.field_types(var_id)[self.id].clone().substitute(Interner, &substs);
Type::new(db, var_id, ty)
}
// FIXME: Find better API to also handle const generics
pub fn ty_with_args(&self, db: &dyn HirDatabase, generics: impl Iterator<Item = Type>) -> Type {
let var_id = self.parent.into();
let def_id: AdtId = match self.parent {
VariantDef::Struct(it) => it.id.into(),
VariantDef::Union(it) => it.id.into(),
VariantDef::Variant(it) => it.parent_enum(db).id.into(),
};
let mut generics = generics.map(|it| it.ty);
let substs = TyBuilder::subst_for_def(db, def_id, None)
.fill(|x| match x {
ParamKind::Type => {
generics.next().unwrap_or_else(|| TyKind::Error.intern(Interner)).cast(Interner)
}
ParamKind::Const(ty) => unknown_const_as_generic(ty.clone()),
ParamKind::Lifetime => error_lifetime().cast(Interner),
})
.build();
let ty = db.field_types(var_id)[self.id].clone().substitute(Interner, &substs);
Type::new(db, var_id, ty)
}
pub fn layout(&self, db: &dyn HirDatabase) -> Result<Layout, LayoutError> {
db.layout_of_ty(
self.ty(db).ty,
db.trait_environment(match hir_def::VariantId::from(self.parent) {
hir_def::VariantId::EnumVariantId(id) => {
GenericDefId::AdtId(id.lookup(db.upcast()).parent.into())
}
hir_def::VariantId::StructId(id) => GenericDefId::AdtId(id.into()),
hir_def::VariantId::UnionId(id) => GenericDefId::AdtId(id.into()),
}),
)
.map(|layout| Layout(layout, db.target_data_layout(self.krate(db).into()).unwrap()))
}
pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
self.parent
}
}
impl HasVisibility for Field {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
let variant_data = self.parent.variant_data(db);
let visibility = &variant_data.fields()[self.id].visibility;
let parent_id: hir_def::VariantId = self.parent.into();
visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Struct {
pub(crate) id: StructId,
}
impl Struct {
pub fn module(self, db: &dyn HirDatabase) -> Module {
Module { id: self.id.lookup(db.upcast()).container }
}
pub fn name(self, db: &dyn HirDatabase) -> Name {
db.struct_data(self.id).name.clone()
}
pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
db.struct_data(self.id)
.variant_data
.fields()
.iter()
.map(|(id, _)| Field { parent: self.into(), id })
.collect()
}
pub fn ty(self, db: &dyn HirDatabase) -> Type {
Type::from_def(db, self.id)
}
pub fn constructor_ty(self, db: &dyn HirDatabase) -> Type {
Type::from_value_def(db, self.id)
}
pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprOptions> {
db.struct_data(self.id).repr
}
pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
self.variant_data(db).kind()
}
fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
db.struct_data(self.id).variant_data.clone()
}
pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
db.attrs(self.id.into()).is_unstable()
}
}
impl HasVisibility for Struct {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Union {
pub(crate) id: UnionId,
}
impl Union {
pub fn name(self, db: &dyn HirDatabase) -> Name {
db.union_data(self.id).name.clone()
}
pub fn module(self, db: &dyn HirDatabase) -> Module {
Module { id: self.id.lookup(db.upcast()).container }
}
pub fn ty(self, db: &dyn HirDatabase) -> Type {
Type::from_def(db, self.id)
}
pub fn constructor_ty(self, db: &dyn HirDatabase) -> Type {
Type::from_value_def(db, self.id)
}
pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
db.union_data(self.id)
.variant_data
.fields()
.iter()
.map(|(id, _)| Field { parent: self.into(), id })
.collect()
}
fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
db.union_data(self.id).variant_data.clone()
}
pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
db.attrs(self.id.into()).is_unstable()
}
}
impl HasVisibility for Union {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Enum {
pub(crate) id: EnumId,
}
impl Enum {
pub fn module(self, db: &dyn HirDatabase) -> Module {
Module { id: self.id.lookup(db.upcast()).container }
}
pub fn name(self, db: &dyn HirDatabase) -> Name {
db.enum_data(self.id).name.clone()
}
pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
db.enum_data(self.id).variants.iter().map(|&(id, _)| Variant { id }).collect()
}
pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprOptions> {
db.enum_data(self.id).repr
}
pub fn ty(self, db: &dyn HirDatabase) -> Type {
Type::from_def(db, self.id)
}
/// The type of the enum variant bodies.
pub fn variant_body_ty(self, db: &dyn HirDatabase) -> Type {
Type::new_for_crate(
self.id.lookup(db.upcast()).container.krate(),
TyBuilder::builtin(match db.enum_data(self.id).variant_body_type() {
layout::IntegerType::Pointer(sign) => match sign {
true => hir_def::builtin_type::BuiltinType::Int(
hir_def::builtin_type::BuiltinInt::Isize,
),
false => hir_def::builtin_type::BuiltinType::Uint(
hir_def::builtin_type::BuiltinUint::Usize,
),
},
layout::IntegerType::Fixed(i, sign) => match sign {
true => hir_def::builtin_type::BuiltinType::Int(match i {
layout::Integer::I8 => hir_def::builtin_type::BuiltinInt::I8,
layout::Integer::I16 => hir_def::builtin_type::BuiltinInt::I16,
layout::Integer::I32 => hir_def::builtin_type::BuiltinInt::I32,
layout::Integer::I64 => hir_def::builtin_type::BuiltinInt::I64,
layout::Integer::I128 => hir_def::builtin_type::BuiltinInt::I128,
}),
false => hir_def::builtin_type::BuiltinType::Uint(match i {
layout::Integer::I8 => hir_def::builtin_type::BuiltinUint::U8,
layout::Integer::I16 => hir_def::builtin_type::BuiltinUint::U16,
layout::Integer::I32 => hir_def::builtin_type::BuiltinUint::U32,
layout::Integer::I64 => hir_def::builtin_type::BuiltinUint::U64,
layout::Integer::I128 => hir_def::builtin_type::BuiltinUint::U128,
}),
},
}),
)
}
/// Returns true if at least one variant of this enum is a non-unit variant.
pub fn is_data_carrying(self, db: &dyn HirDatabase) -> bool {
self.variants(db).iter().any(|v| !matches!(v.kind(db), StructKind::Unit))
}
pub fn layout(self, db: &dyn HirDatabase) -> Result<Layout, LayoutError> {
Adt::from(self).layout(db)
}
pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
db.attrs(self.id.into()).is_unstable()
}
}
impl HasVisibility for Enum {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
}
}
impl From<&Variant> for DefWithBodyId {
fn from(&v: &Variant) -> Self {
DefWithBodyId::VariantId(v.into())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Variant {
pub(crate) id: EnumVariantId,
}
impl Variant {
pub fn module(self, db: &dyn HirDatabase) -> Module {
Module { id: self.id.module(db.upcast()) }
}
pub fn parent_enum(self, db: &dyn HirDatabase) -> Enum {
self.id.lookup(db.upcast()).parent.into()
}
pub fn constructor_ty(self, db: &dyn HirDatabase) -> Type {
Type::from_value_def(db, self.id)
}
pub fn name(self, db: &dyn HirDatabase) -> Name {
db.enum_variant_data(self.id).name.clone()
}
pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
self.variant_data(db)
.fields()
.iter()
.map(|(id, _)| Field { parent: self.into(), id })
.collect()
}
pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
self.variant_data(db).kind()
}
pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
db.enum_variant_data(self.id).variant_data.clone()
}
pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
self.source(db)?.value.expr()
}
pub fn eval(self, db: &dyn HirDatabase) -> Result<i128, ConstEvalError> {
db.const_eval_discriminant(self.into())
}
pub fn layout(&self, db: &dyn HirDatabase) -> Result<Layout, LayoutError> {
let parent_enum = self.parent_enum(db);
let parent_layout = parent_enum.layout(db)?;
Ok(match &parent_layout.0.variants {
layout::Variants::Multiple { variants, .. } => Layout(
{
let lookup = self.id.lookup(db.upcast());
let rustc_enum_variant_idx = RustcEnumVariantIdx(lookup.index as usize);
Arc::new(variants[rustc_enum_variant_idx].clone())
},
db.target_data_layout(parent_enum.krate(db).into()).unwrap(),
),
_ => parent_layout,
})
}
pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
db.attrs(self.id.into()).is_unstable()
}
}
/// Variants inherit visibility from the parent enum.
impl HasVisibility for Variant {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
self.parent_enum(db).visibility(db)
}
}
/// A Data Type
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Adt {
Struct(Struct),
Union(Union),
Enum(Enum),
}
impl_from!(Struct, Union, Enum for Adt);
impl Adt {
pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
let subst = db.generic_defaults(self.into());
subst.iter().any(|ty| match ty.skip_binders().data(Interner) {
GenericArgData::Ty(it) => it.is_unknown(),
_ => false,
})
}
pub fn layout(self, db: &dyn HirDatabase) -> Result<Layout, LayoutError> {
db.layout_of_adt(
self.into(),
TyBuilder::adt(db, self.into())
.fill_with_defaults(db, || TyKind::Error.intern(Interner))
.build_into_subst(),
db.trait_environment(self.into()),
)
.map(|layout| Layout(layout, db.target_data_layout(self.krate(db).id).unwrap()))
}
/// Turns this ADT into a type. Any type parameters of the ADT will be
/// turned into unknown types, which is good for e.g. finding the most
/// general set of completions, but will not look very nice when printed.
pub fn ty(self, db: &dyn HirDatabase) -> Type {
let id = AdtId::from(self);
Type::from_def(db, id)
}
/// Turns this ADT into a type with the given type parameters. This isn't
/// the greatest API, FIXME find a better one.
pub fn ty_with_args(self, db: &dyn HirDatabase, args: impl Iterator<Item = Type>) -> Type {
let id = AdtId::from(self);
let mut it = args.map(|t| t.ty);
let ty = TyBuilder::def_ty(db, id.into(), None)
.fill(|x| {
let r = it.next().unwrap_or_else(|| TyKind::Error.intern(Interner));
match x {
ParamKind::Type => r.cast(Interner),
ParamKind::Const(ty) => unknown_const_as_generic(ty.clone()),
ParamKind::Lifetime => error_lifetime().cast(Interner),
}
})
.build();
Type::new(db, id, ty)
}
pub fn module(self, db: &dyn HirDatabase) -> Module {
match self {
Adt::Struct(s) => s.module(db),
Adt::Union(s) => s.module(db),
Adt::Enum(e) => e.module(db),
}
}
pub fn name(self, db: &dyn HirDatabase) -> Name {
match self {
Adt::Struct(s) => s.name(db),
Adt::Union(u) => u.name(db),
Adt::Enum(e) => e.name(db),
}
}
/// Returns the lifetime of the DataType
pub fn lifetime(&self, db: &dyn HirDatabase) -> Option<LifetimeParamData> {
let resolver = match self {
Adt::Struct(s) => s.id.resolver(db.upcast()),
Adt::Union(u) => u.id.resolver(db.upcast()),
Adt::Enum(e) => e.id.resolver(db.upcast()),
};
resolver
.generic_params()
.and_then(|gp| {
gp.iter_lt()
// there should only be a single lifetime
// but `Arena` requires to use an iterator
.nth(0)
})
.map(|arena| arena.1.clone())
}
pub fn as_struct(&self) -> Option<Struct> {
if let Self::Struct(v) = self {
Some(*v)
} else {
None
}
}
pub fn as_enum(&self) -> Option<Enum> {
if let Self::Enum(v) = self {
Some(*v)
} else {
None
}
}
}
impl HasVisibility for Adt {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
match self {
Adt::Struct(it) => it.visibility(db),
Adt::Union(it) => it.visibility(db),
Adt::Enum(it) => it.visibility(db),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VariantDef {
Struct(Struct),
Union(Union),
Variant(Variant),
}
impl_from!(Struct, Union, Variant for VariantDef);
impl VariantDef {
pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
match self {
VariantDef::Struct(it) => it.fields(db),
VariantDef::Union(it) => it.fields(db),
VariantDef::Variant(it) => it.fields(db),
}
}
pub fn module(self, db: &dyn HirDatabase) -> Module {
match self {
VariantDef::Struct(it) => it.module(db),
VariantDef::Union(it) => it.module(db),
VariantDef::Variant(it) => it.module(db),
}
}
pub fn name(&self, db: &dyn HirDatabase) -> Name {
match self {
VariantDef::Struct(s) => s.name(db),
VariantDef::Union(u) => u.name(db),
VariantDef::Variant(e) => e.name(db),
}
}
pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
match self {
VariantDef::Struct(it) => it.variant_data(db),
VariantDef::Union(it) => it.variant_data(db),
VariantDef::Variant(it) => it.variant_data(db),
}
}
}
/// The defs which have a body.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DefWithBody {
Function(Function),
Static(Static),
Const(Const),
Variant(Variant),
InTypeConst(InTypeConst),
}
impl_from!(Function, Const, Static, Variant, InTypeConst for DefWithBody);
impl DefWithBody {
pub fn module(self, db: &dyn HirDatabase) -> Module {
match self {
DefWithBody::Const(c) => c.module(db),
DefWithBody::Function(f) => f.module(db),
DefWithBody::Static(s) => s.module(db),
DefWithBody::Variant(v) => v.module(db),
DefWithBody::InTypeConst(c) => c.module(db),
}
}
pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
match self {
DefWithBody::Function(f) => Some(f.name(db)),
DefWithBody::Static(s) => Some(s.name(db)),
DefWithBody::Const(c) => c.name(db),
DefWithBody::Variant(v) => Some(v.name(db)),
DefWithBody::InTypeConst(_) => None,
}
}
/// Returns the type this def's body has to evaluate to.
pub fn body_type(self, db: &dyn HirDatabase) -> Type {
match self {
DefWithBody::Function(it) => it.ret_type(db),
DefWithBody::Static(it) => it.ty(db),
DefWithBody::Const(it) => it.ty(db),
DefWithBody::Variant(it) => it.parent_enum(db).variant_body_ty(db),
DefWithBody::InTypeConst(it) => Type::new_with_resolver_inner(
db,
&DefWithBodyId::from(it.id).resolver(db.upcast()),
TyKind::Error.intern(Interner),
),
}
}
fn id(&self) -> DefWithBodyId {
match self {
DefWithBody::Function(it) => it.id.into(),
DefWithBody::Static(it) => it.id.into(),
DefWithBody::Const(it) => it.id.into(),
DefWithBody::Variant(it) => it.into(),
DefWithBody::InTypeConst(it) => it.id.into(),
}
}
/// A textual representation of the HIR of this def's body for debugging purposes.
pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
let body = db.body(self.id());
body.pretty_print(db.upcast(), self.id(), Edition::CURRENT)
}
/// A textual representation of the MIR of this def's body for debugging purposes.
pub fn debug_mir(self, db: &dyn HirDatabase) -> String {
let body = db.mir_body(self.id());
match body {
Ok(body) => body.pretty_print(db),
Err(e) => format!("error:\n{e:?}"),
}
}
pub fn diagnostics(
self,
db: &dyn HirDatabase,
acc: &mut Vec<AnyDiagnostic>,
style_lints: bool,
) {
let krate = self.module(db).id.krate();
let (body, source_map) = db.body_with_source_map(self.into());
for (_, def_map) in body.blocks(db.upcast()) {
Module { id: def_map.module_id(DefMap::ROOT) }.diagnostics(db, acc, style_lints);
}
source_map
.macro_calls()
.for_each(|(_ast_id, call_id)| macro_call_diagnostics(db, call_id.macro_call_id, acc));
for diag in source_map.diagnostics() {
acc.push(match diag {
BodyDiagnostic::InactiveCode { node, cfg, opts } => {
InactiveCode { node: *node, cfg: cfg.clone(), opts: opts.clone() }.into()
}
BodyDiagnostic::MacroError { node, err } => {
let (message, error) = err.render_to_string(db.upcast());
let precise_location = if err.span().anchor.file_id == node.file_id {
Some(
err.span().range
+ db.ast_id_map(err.span().anchor.file_id.into())
.get_erased(err.span().anchor.ast_id)
.text_range()
.start(),
)
} else {
None
};
MacroError {
node: (*node).map(|it| it.into()),
precise_location,
message,
error,
}
.into()
}
BodyDiagnostic::UnresolvedMacroCall { node, path } => UnresolvedMacroCall {
macro_call: (*node).map(|ast_ptr| ast_ptr.into()),
precise_location: None,
path: path.clone(),
is_bang: true,
}
.into(),
BodyDiagnostic::AwaitOutsideOfAsync { node, location } => {
AwaitOutsideOfAsync { node: *node, location: location.clone() }.into()
}
BodyDiagnostic::UnreachableLabel { node, name } => {
UnreachableLabel { node: *node, name: name.clone() }.into()
}
BodyDiagnostic::UndeclaredLabel { node, name } => {
UndeclaredLabel { node: *node, name: name.clone() }.into()
}
});
}
let infer = db.infer(self.into());
for d in &infer.diagnostics {
acc.extend(AnyDiagnostic::inference_diagnostic(db, self.into(), d, &source_map));
}
for (pat_or_expr, mismatch) in infer.type_mismatches() {
let expr_or_pat = match pat_or_expr {
ExprOrPatId::ExprId(expr) => source_map.expr_syntax(expr).map(Either::Left),
ExprOrPatId::PatId(pat) => source_map.pat_syntax(pat).map(Either::Right),
};
let expr_or_pat = match expr_or_pat {
Ok(Either::Left(expr)) => expr.map(AstPtr::wrap_left),
Ok(Either::Right(InFile { file_id, value: pat })) => {
// cast from Either<Pat, SelfParam> -> Either<_, Pat>
let Some(ptr) = AstPtr::try_from_raw(pat.syntax_node_ptr()) else {
continue;
};
InFile { file_id, value: ptr }
}
Err(SyntheticSyntax) => continue,
};
acc.push(
TypeMismatch {
expr_or_pat,
expected: Type::new(db, DefWithBodyId::from(self), mismatch.expected.clone()),
actual: Type::new(db, DefWithBodyId::from(self), mismatch.actual.clone()),
}
.into(),
);
}
let (unafe_exprs, only_lint) = hir_ty::diagnostics::missing_unsafe(db, self.into());
for expr in unafe_exprs {
match source_map.expr_syntax(expr) {
Ok(expr) => acc.push(MissingUnsafe { expr, only_lint }.into()),
Err(SyntheticSyntax) => {
// FIXME: Here and elsewhere in this file, the `expr` was
// desugared, report or assert that this doesn't happen.
}
}
}
if let Ok(borrowck_results) = db.borrowck(self.into()) {
for borrowck_result in borrowck_results.iter() {
let mir_body = &borrowck_result.mir_body;
for moof in &borrowck_result.moved_out_of_ref {
let span: InFile<SyntaxNodePtr> = match moof.span {
mir::MirSpan::ExprId(e) => match source_map.expr_syntax(e) {
Ok(s) => s.map(|it| it.into()),
Err(_) => continue,
},
mir::MirSpan::PatId(p) => match source_map.pat_syntax(p) {
Ok(s) => s.map(|it| it.into()),
Err(_) => continue,
},
mir::MirSpan::SelfParam => match source_map.self_param_syntax() {
Some(s) => s.map(|it| it.into()),
None => continue,
},
mir::MirSpan::BindingId(b) => {
match source_map
.patterns_for_binding(b)
.iter()
.find_map(|p| source_map.pat_syntax(*p).ok())
{
Some(s) => s.map(|it| it.into()),
None => continue,
}
}
mir::MirSpan::Unknown => continue,
};
acc.push(
MovedOutOfRef { ty: Type::new_for_crate(krate, moof.ty.clone()), span }
.into(),
)
}
let mol = &borrowck_result.mutability_of_locals;
for (binding_id, binding_data) in body.bindings.iter() {
if binding_data.problems.is_some() {
// We should report specific diagnostics for these problems, not `need-mut` and `unused-mut`.
continue;
}
let Some(&local) = mir_body.binding_locals.get(binding_id) else {
continue;
};
if source_map
.patterns_for_binding(binding_id)
.iter()
.any(|&pat| source_map.pat_syntax(pat).is_err())
{
// Skip synthetic bindings
continue;
}
let mut need_mut = &mol[local];
if body[binding_id].name == sym::self_.clone()
&& need_mut == &mir::MutabilityReason::Unused
{
need_mut = &mir::MutabilityReason::Not;
}
let local = Local { parent: self.into(), binding_id };
let is_mut = body[binding_id].mode == BindingAnnotation::Mutable;
match (need_mut, is_mut) {
(mir::MutabilityReason::Unused, _) => {
let should_ignore = body[binding_id].name.as_str().starts_with('_');
if !should_ignore {
acc.push(UnusedVariable { local }.into())
}
}
(mir::MutabilityReason::Mut { .. }, true)
| (mir::MutabilityReason::Not, false) => (),
(mir::MutabilityReason::Mut { spans }, false) => {
for span in spans {
let span: InFile<SyntaxNodePtr> = match span {
mir::MirSpan::ExprId(e) => match source_map.expr_syntax(*e) {
Ok(s) => s.map(|it| it.into()),
Err(_) => continue,
},
mir::MirSpan::PatId(p) => match source_map.pat_syntax(*p) {
Ok(s) => s.map(|it| it.into()),
Err(_) => continue,
},
mir::MirSpan::BindingId(b) => {
match source_map
.patterns_for_binding(*b)
.iter()
.find_map(|p| source_map.pat_syntax(*p).ok())
{
Some(s) => s.map(|it| it.into()),
None => continue,
}
}
mir::MirSpan::SelfParam => match source_map.self_param_syntax()
{
Some(s) => s.map(|it| it.into()),
None => continue,
},
mir::MirSpan::Unknown => continue,
};
acc.push(NeedMut { local, span }.into());
}
}
(mir::MutabilityReason::Not, true) => {
if !infer.mutated_bindings_in_closure.contains(&binding_id) {
let should_ignore = body[binding_id].name.as_str().starts_with('_');
if !should_ignore {
acc.push(UnusedMut { local }.into())
}
}
}
}
}
}
}
for diagnostic in BodyValidationDiagnostic::collect(db, self.into(), style_lints) {
acc.extend(AnyDiagnostic::body_validation_diagnostic(db, diagnostic, &source_map));
}
let def: ModuleDef = match self {
DefWithBody::Function(it) => it.into(),
DefWithBody::Static(it) => it.into(),
DefWithBody::Const(it) => it.into(),
DefWithBody::Variant(it) => it.into(),
// FIXME: don't ignore diagnostics for in type const
DefWithBody::InTypeConst(_) => return,
};
for diag in hir_ty::diagnostics::incorrect_case(db, def.into()) {
acc.push(diag.into())
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Function {
pub(crate) id: FunctionId,
}
impl Function {
pub fn module(self, db: &dyn HirDatabase) -> Module {
self.id.module(db.upcast()).into()
}
pub fn name(self, db: &dyn HirDatabase) -> Name {
db.function_data(self.id).name.clone()
}
pub fn ty(self, db: &dyn HirDatabase) -> Type {
Type::from_value_def(db, self.id)
}
pub fn fn_ptr_type(self, db: &dyn HirDatabase) -> Type {
let resolver = self.id.resolver(db.upcast());
let substs = TyBuilder::placeholder_subst(db, self.id);
let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
let ty = TyKind::Function(callable_sig.to_fn_ptr()).intern(Interner);
Type::new_with_resolver_inner(db, &resolver, ty)
}
/// Get this function's return type
pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
let resolver = self.id.resolver(db.upcast());
let substs = TyBuilder::placeholder_subst(db, self.id);
let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
let ty = callable_sig.ret().clone();
Type::new_with_resolver_inner(db, &resolver, ty)
}
// FIXME: Find better API to also handle const generics
pub fn ret_type_with_args(
self,
db: &dyn HirDatabase,
generics: impl Iterator<Item = Type>,
) -> Type {
let resolver = self.id.resolver(db.upcast());
let parent_id: Option<GenericDefId> = match self.id.lookup(db.upcast()).container {
ItemContainerId::ImplId(it) => Some(it.into()),
ItemContainerId::TraitId(it) => Some(it.into()),
ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
};
let mut generics = generics.map(|it| it.ty);
let mut filler = |x: &_| match x {
ParamKind::Type => {
generics.next().unwrap_or_else(|| TyKind::Error.intern(Interner)).cast(Interner)
}
ParamKind::Const(ty) => unknown_const_as_generic(ty.clone()),
ParamKind::Lifetime => error_lifetime().cast(Interner),
};
let parent_substs =
parent_id.map(|id| TyBuilder::subst_for_def(db, id, None).fill(&mut filler).build());
let substs = TyBuilder::subst_for_def(db, self.id, parent_substs).fill(&mut filler).build();
let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
let ty = callable_sig.ret().clone();
Type::new_with_resolver_inner(db, &resolver, ty)
}
pub fn async_ret_type(self, db: &dyn HirDatabase) -> Option<Type> {
if !self.is_async(db) {
return None;
}
let resolver = self.id.resolver(db.upcast());
let substs = TyBuilder::placeholder_subst(db, self.id);
let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
let ret_ty = callable_sig.ret().clone();
for pred in ret_ty.impl_trait_bounds(db).into_iter().flatten() {
if let WhereClause::AliasEq(output_eq) = pred.into_value_and_skipped_binders().0 {
return Type::new_with_resolver_inner(db, &resolver, output_eq.ty).into();
}
}
None
}
pub fn has_self_param(self, db: &dyn HirDatabase) -> bool {
db.function_data(self.id).has_self_param()
}
pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
self.has_self_param(db).then_some(SelfParam { func: self.id })
}
pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
let environment = db.trait_environment(self.id.into());
let substs = TyBuilder::placeholder_subst(db, self.id);
let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
callable_sig
.params()
.iter()
.enumerate()
.map(|(idx, ty)| {
let ty = Type { env: environment.clone(), ty: ty.clone() };
Param { func: Callee::Def(CallableDefId::FunctionId(self.id)), ty, idx }
})
.collect()
}
pub fn num_params(self, db: &dyn HirDatabase) -> usize {
db.function_data(self.id).params.len()
}
pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
self.self_param(db)?;
Some(self.params_without_self(db))
}
pub fn params_without_self(self, db: &dyn HirDatabase) -> Vec<Param> {
let environment = db.trait_environment(self.id.into());
let substs = TyBuilder::placeholder_subst(db, self.id);
let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
let skip = if db.function_data(self.id).has_self_param() { 1 } else { 0 };
callable_sig
.params()
.iter()
.enumerate()
.skip(skip)
.map(|(idx, ty)| {
let ty = Type { env: environment.clone(), ty: ty.clone() };
Param { func: Callee::Def(CallableDefId::FunctionId(self.id)), ty, idx }
})
.collect()
}
// FIXME: Find better API to also handle const generics
pub fn params_without_self_with_args(
self,
db: &dyn HirDatabase,
generics: impl Iterator<Item = Type>,
) -> Vec<Param> {
let environment = db.trait_environment(self.id.into());
let parent_id: Option<GenericDefId> = match self.id.lookup(db.upcast()).container {
ItemContainerId::ImplId(it) => Some(it.into()),
ItemContainerId::TraitId(it) => Some(it.into()),
ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
};
let mut generics = generics.map(|it| it.ty);
let parent_substs = parent_id.map(|id| {
TyBuilder::subst_for_def(db, id, None)
.fill(|x| match x {
ParamKind::Type => generics
.next()
.unwrap_or_else(|| TyKind::Error.intern(Interner))
.cast(Interner),
ParamKind::Const(ty) => unknown_const_as_generic(ty.clone()),
ParamKind::Lifetime => error_lifetime().cast(Interner),
})
.build()
});
let substs = TyBuilder::subst_for_def(db, self.id, parent_substs)
.fill(|_| {
let ty = generics.next().unwrap_or_else(|| TyKind::Error.intern(Interner));
GenericArg::new(Interner, GenericArgData::Ty(ty))
})
.build();
let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
let skip = if db.function_data(self.id).has_self_param() { 1 } else { 0 };
callable_sig
.params()
.iter()
.enumerate()
.skip(skip)
.map(|(idx, ty)| {
let ty = Type { env: environment.clone(), ty: ty.clone() };
Param { func: Callee::Def(CallableDefId::FunctionId(self.id)), ty, idx }
})
.collect()
}
pub fn is_const(self, db: &dyn HirDatabase) -> bool {
db.function_data(self.id).is_const()
}
pub fn is_async(self, db: &dyn HirDatabase) -> bool {
db.function_data(self.id).is_async()
}
pub fn returns_impl_future(self, db: &dyn HirDatabase) -> bool {
if self.is_async(db) {
return true;
}
let Some(impl_traits) = self.ret_type(db).as_impl_traits(db) else { return false };
let Some(future_trait_id) =
db.lang_item(self.ty(db).env.krate, LangItem::Future).and_then(|t| t.as_trait())
else {
return false;
};
let Some(sized_trait_id) =
db.lang_item(self.ty(db).env.krate, LangItem::Sized).and_then(|t| t.as_trait())
else {
return false;
};
let mut has_impl_future = false;
impl_traits
.filter(|t| {
let fut = t.id == future_trait_id;
has_impl_future |= fut;
!fut && t.id != sized_trait_id
})
// all traits but the future trait must be auto traits
.all(|t| t.is_auto(db))
&& has_impl_future
}
/// Does this function have `#[test]` attribute?
pub fn is_test(self, db: &dyn HirDatabase) -> bool {
db.function_data(self.id).attrs.is_test()
}
/// is this a `fn main` or a function with an `export_name` of `main`?
pub fn is_main(self, db: &dyn HirDatabase) -> bool {
let data = db.function_data(self.id);
data.attrs.export_name() == Some(&sym::main)
|| self.module(db).is_crate_root() && data.name == sym::main
}
/// Is this a function with an `export_name` of `main`?
pub fn exported_main(self, db: &dyn HirDatabase) -> bool {
let data = db.function_data(self.id);
data.attrs.export_name() == Some(&sym::main)
}
/// Does this function have the ignore attribute?
pub fn is_ignore(self, db: &dyn HirDatabase) -> bool {
db.function_data(self.id).attrs.is_ignore()
}
/// Does this function have `#[bench]` attribute?
pub fn is_bench(self, db: &dyn HirDatabase) -> bool {
db.function_data(self.id).attrs.is_bench()
}
/// Is this function marked as unstable with `#[feature]` attribute?
pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
db.function_data(self.id).attrs.is_unstable()
}
pub fn is_unsafe_to_call(self, db: &dyn HirDatabase) -> bool {
hir_ty::is_fn_unsafe_to_call(db, self.id)
}
/// Whether this function declaration has a definition.
///
/// This is false in the case of required (not provided) trait methods.
pub fn has_body(self, db: &dyn HirDatabase) -> bool {
db.function_data(self.id).has_body()
}
pub fn as_proc_macro(self, db: &dyn HirDatabase) -> Option<Macro> {
let function_data = db.function_data(self.id);
let attrs = &function_data.attrs;
// FIXME: Store this in FunctionData flags?
if !(attrs.is_proc_macro()
|| attrs.is_proc_macro_attribute()
|| attrs.is_proc_macro_derive())
{
return None;
}
let def_map = db.crate_def_map(HasModule::krate(&self.id, db.upcast()));
def_map.fn_as_proc_macro(self.id).map(|id| Macro { id: id.into() })
}
pub fn eval(
self,
db: &dyn HirDatabase,
span_formatter: impl Fn(FileId, TextRange) -> String,
) -> String {
let krate = HasModule::krate(&self.id, db.upcast());
let edition = db.crate_graph()[krate].edition;
let body = match db.monomorphized_mir_body(
self.id.into(),
Substitution::empty(Interner),
db.trait_environment(self.id.into()),
) {
Ok(body) => body,
Err(e) => {
let mut r = String::new();
_ = e.pretty_print(&mut r, db, &span_formatter, edition);
return r;
}
};
let (result, output) = interpret_mir(db, body, false, None);
let mut text = match result {
Ok(_) => "pass".to_owned(),
Err(e) => {
let mut r = String::new();
_ = e.pretty_print(&mut r, db, &span_formatter, edition);
r
}
};
let stdout = output.stdout().into_owned();
if !stdout.is_empty() {
text += "\n--------- stdout ---------\n";
text += &stdout;
}
let stderr = output.stdout().into_owned();
if !stderr.is_empty() {
text += "\n--------- stderr ---------\n";
text += &stderr;
}
text
}
}
// Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Access {
Shared,
Exclusive,
Owned,
}
impl From<hir_ty::Mutability> for Access {
fn from(mutability: hir_ty::Mutability) -> Access {
match mutability {
hir_ty::Mutability::Not => Access::Shared,
hir_ty::Mutability::Mut => Access::Exclusive,
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Param {
func: Callee,
/// The index in parameter list, including self parameter.
idx: usize,
ty: Type,
}
impl Param {
pub fn parent_fn(&self) -> Option<Function> {
match self.func {
Callee::Def(CallableDefId::FunctionId(f)) => Some(f.into()),
_ => None,
}
}
// pub fn parent_closure(&self) -> Option<Closure> {
// self.func.as_ref().right().cloned()
// }
pub fn index(&self) -> usize {
self.idx
}
pub fn ty(&self) -> &Type {
&self.ty
}
pub fn name(&self, db: &dyn HirDatabase) -> Option<Name> {
Some(self.as_local(db)?.name(db))
}
pub fn as_local(&self, db: &dyn HirDatabase) -> Option<Local> {
let parent = match self.func {
Callee::Def(CallableDefId::FunctionId(it)) => DefWithBodyId::FunctionId(it),
Callee::Closure(closure, _) => db.lookup_intern_closure(closure.into()).0,
_ => return None,
};
let body = db.body(parent);
if let Some(self_param) = body.self_param.filter(|_| self.idx == 0) {
Some(Local { parent, binding_id: self_param })
} else if let Pat::Bind { id, .. } =
&body[body.params[self.idx - body.self_param.is_some() as usize]]
{
Some(Local { parent, binding_id: *id })
} else {
None
}
}
pub fn pattern_source(self, db: &dyn HirDatabase) -> Option<ast::Pat> {
self.source(db).and_then(|p| p.value.right()?.pat())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SelfParam {
func: FunctionId,
}
impl SelfParam {
pub fn access(self, db: &dyn HirDatabase) -> Access {
let func_data = db.function_data(self.func);
func_data
.params
.first()
.map(|param| match &**param {
TypeRef::Reference(.., mutability) => match mutability {
hir_def::type_ref::Mutability::Shared => Access::Shared,
hir_def::type_ref::Mutability::Mut => Access::Exclusive,
},