diff --git a/crates/mun_codegen/src/ir/body.rs b/crates/mun_codegen/src/ir/body.rs index e290fe98a..eb15ee595 100644 --- a/crates/mun_codegen/src/ir/body.rs +++ b/crates/mun_codegen/src/ir/body.rs @@ -6,9 +6,9 @@ use crate::{ value::Global, }; use hir::{ - ArenaId, ArithOp, BinaryOp, Body, CmpOp, Expr, ExprId, HirDatabase, HirDisplay, - InferenceResult, Literal, LogicOp, Name, Ordering, Pat, PatId, Path, Resolution, - ResolveBitness, Resolver, Statement, TypeCtor, UnaryOp, + ArithOp, BinaryOp, Body, CmpOp, Expr, ExprId, HirDatabase, HirDisplay, InferenceResult, + Literal, LogicOp, Name, Ordering, Pat, PatId, Path, Resolution, ResolveBitness, Resolver, + Statement, TypeCtor, UnaryOp, }; use inkwell::{ basic_block::BasicBlock, diff --git a/crates/mun_hir/src/adt.rs b/crates/mun_hir/src/adt.rs index f7e58a9ff..add0cf76c 100644 --- a/crates/mun_hir/src/adt.rs +++ b/crates/mun_hir/src/adt.rs @@ -1,8 +1,8 @@ use std::{fmt, sync::Arc}; -use crate::type_ref::{TypeRefBuilder, TypeRefId, TypeRefMap, TypeRefSourceMap}; +use crate::type_ref::{LocalTypeRefId, TypeRefBuilder, TypeRefMap, TypeRefSourceMap}; use crate::{ - arena::{Arena, RawId}, + arena::{Arena, Idx}, ids::{AstItemDef, StructId, TypeAliasId}, AsName, DefDatabase, Name, }; @@ -25,14 +25,9 @@ pub use mun_syntax::ast::StructMemoryKind; #[derive(Debug, Clone, PartialEq, Eq)] pub struct StructFieldData { pub name: Name, - pub type_ref: TypeRefId, + pub type_ref: LocalTypeRefId, } -/// An identifier for a struct's or tuple's field -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct StructFieldId(RawId); -impl_arena_id!(StructFieldId); - /// A struct's fields' data (record, tuple, or unit struct) #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum StructKind { @@ -51,10 +46,13 @@ impl fmt::Display for StructKind { } } +/// An identifier for a struct's or tuple's field +pub type LocalStructFieldId = Idx; + #[derive(Debug, PartialEq, Eq)] pub struct StructData { pub name: Name, - pub fields: Arena, + pub fields: Arena, pub kind: StructKind, pub memory_kind: StructMemoryKind, type_ref_map: TypeRefMap, @@ -125,7 +123,7 @@ impl StructData { #[derive(Debug, PartialEq, Eq)] pub struct TypeAliasData { pub name: Name, - pub type_ref_id: TypeRefId, + pub type_ref_id: LocalTypeRefId, type_ref_map: TypeRefMap, type_ref_source_map: TypeRefSourceMap, } diff --git a/crates/mun_hir/src/arena.rs b/crates/mun_hir/src/arena.rs index 348266a42..536bf4fcc 100644 --- a/crates/mun_hir/src/arena.rs +++ b/crates/mun_hir/src/arena.rs @@ -1,4 +1,5 @@ use std::fmt; +use std::hash::{Hash, Hasher}; use std::iter::FromIterator; use std::marker::PhantomData; use std::ops::{Index, IndexMut}; @@ -32,19 +33,65 @@ impl fmt::Display for RawId { } } -/// Enables storing in an `Arena`. -pub trait ArenaId { - fn from_raw(raw: RawId) -> Self; - fn into_raw(self) -> RawId; +pub struct Idx { + raw: RawId, + _ty: PhantomData T>, } +impl Clone for Idx { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for Idx {} + +impl PartialEq for Idx { + fn eq(&self, other: &Self) -> bool { + self.raw == other.raw + } +} + +impl Eq for Idx {} + +impl Hash for Idx { + fn hash(&self, state: &mut H) { + self.raw.hash(state) + } +} + +impl fmt::Debug for Idx { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut type_name = std::any::type_name::(); + if let Some(idx) = type_name.rfind(':') { + type_name = &type_name[idx + 1..] + } + write!(f, "Idx::<{}>({})", type_name, self.raw) + } +} + +impl Idx { + pub fn from_raw(raw: RawId) -> Self { + Idx { + raw, + _ty: PhantomData, + } + } + pub fn into_raw(self) -> RawId { + self.raw + } +} + +/// An `Arena` holds a collection of `T`s but allocates persistent ID's that are used to refer +/// to an element in the arena. When adding an item to an `Arena` it returns an `Idx` that is +/// only valid for the `Arena` that allocated the `Idx`. Its only possible to add items to an +/// `Arena`. #[derive(Clone, PartialEq, Eq)] -pub struct Arena { +pub struct Arena { data: Vec, - _ty: PhantomData, } -impl fmt::Debug for Arena { +impl fmt::Debug for Arena { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Arena") .field("len", &self.len()) @@ -53,7 +100,7 @@ impl fmt::Debug for Arena { } } -impl Arena { +impl Arena { /// Returns the number of elements in the arena pub fn len(&self) -> usize { self.data.len() @@ -65,67 +112,51 @@ impl Arena { } /// Stores `value` in the arena and returns the associated Id. - pub fn alloc(&mut self, value: T) -> ID { + pub fn alloc(&mut self, value: T) -> Idx { let id = RawId(self.data.len() as u32); self.data.push(value); - ID::from_raw(id) + Idx::from_raw(id) } /// Iterate over the elements in the arena - pub fn iter(&self) -> impl Iterator { + pub fn iter( + &self, + ) -> impl Iterator, &T)> + ExactSizeIterator + DoubleEndedIterator { self.data .iter() .enumerate() - .map(|(idx, value)| (ID::from_raw(RawId(idx as u32)), value)) + .map(|(idx, value)| (Idx::from_raw(RawId(idx as u32)), value)) } } -impl Default for Arena { - fn default() -> Arena { - Arena { - data: Vec::new(), - _ty: PhantomData, - } +impl Default for Arena { + fn default() -> Arena { + Arena { data: Vec::new() } } } -impl Index for Arena { +impl Index> for Arena { type Output = T; - fn index(&self, idx: ID) -> &T { + fn index(&self, idx: Idx) -> &T { let idx = idx.into_raw().0 as usize; &self.data[idx] } } -impl IndexMut for Arena { - fn index_mut(&mut self, idx: ID) -> &mut T { +impl IndexMut> for Arena { + fn index_mut(&mut self, idx: Idx) -> &mut T { let idx = idx.into_raw().0 as usize; &mut self.data[idx] } } -impl FromIterator for Arena { +impl FromIterator for Arena { fn from_iter(iter: I) -> Self where I: IntoIterator, { Arena { data: Vec::from_iter(iter), - _ty: PhantomData, } } } - -/// Implements `ArenaId` for the specified type. -macro_rules! impl_arena_id { - ($name:ident) => { - impl $crate::ArenaId for $name { - fn from_raw(raw: $crate::RawId) -> Self { - $name(raw) - } - fn into_raw(self) -> $crate::RawId { - self.0 - } - } - }; -} diff --git a/crates/mun_hir/src/arena/map.rs b/crates/mun_hir/src/arena/map.rs index 02c51c3d8..0bb33f671 100644 --- a/crates/mun_hir/src/arena/map.rs +++ b/crates/mun_hir/src/arena/map.rs @@ -2,7 +2,7 @@ use std::marker::PhantomData; -use super::ArenaId; +use super::Idx; /// A map from arena IDs to some other type. Space requirement is O(highest ID). #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -11,67 +11,62 @@ pub struct ArenaMap { _ty: PhantomData, } -impl ArenaMap { - pub fn insert(&mut self, id: ID, t: T) { - let idx = to_idx(id); - if self.v.capacity() <= idx { - self.v.reserve(idx + 1 - self.v.capacity()); - } - if self.v.len() <= idx { - while self.v.len() <= idx { - self.v.push(None); - } - } +impl ArenaMap, V> { + pub fn insert(&mut self, id: Idx, t: V) { + let idx = Self::idx_to_raw(id); + self.v.resize_with((idx + 1).max(self.v.len()), || None); self.v[idx] = Some(t); } - pub fn get(&self, id: ID) -> Option<&T> { - self.v.get(to_idx(id)).and_then(|it| it.as_ref()) + pub fn get(&self, id: Idx) -> Option<&V> { + self.v.get(Self::idx_to_raw(id)).and_then(|it| it.as_ref()) } - pub fn get_mut(&mut self, id: ID) -> Option<&mut T> { - self.v.get_mut(to_idx(id)).and_then(|it| it.as_mut()) + pub fn get_mut(&mut self, id: Idx) -> Option<&mut V> { + self.v + .get_mut(Self::idx_to_raw(id)) + .and_then(|it| it.as_mut()) } - pub fn values(&self) -> impl Iterator { + pub fn values(&self) -> impl Iterator { self.v.iter().filter_map(|o| o.as_ref()) } - pub fn values_mut(&mut self) -> impl Iterator { + pub fn values_mut(&mut self) -> impl Iterator { self.v.iter_mut().filter_map(|o| o.as_mut()) } - pub fn iter(&self) -> impl Iterator { + pub fn iter(&self) -> impl Iterator, &V)> { self.v .iter() .enumerate() - .filter_map(|(idx, o)| Some((from_idx(idx), o.as_ref()?))) + .filter_map(|(idx, o)| Some((Self::idx_from_raw(idx), o.as_ref()?))) } - pub fn iter_mut(&mut self) -> impl Iterator { + pub fn iter_mut(&mut self) -> impl Iterator, &mut V)> { self.v .iter_mut() .enumerate() - .filter_map(|(idx, o)| Some((from_idx(idx), o.as_mut()?))) + .filter_map(|(idx, o)| Some((Self::idx_from_raw(idx), o.as_mut()?))) } -} -fn to_idx(id: ID) -> usize { - u32::from(id.into_raw()) as usize -} + fn idx_to_raw(id: Idx) -> usize { + u32::from(id.into_raw()) as usize + } -fn from_idx(idx: usize) -> ID { - ID::from_raw((idx as u32).into()) + fn idx_from_raw(idx: usize) -> Idx { + Idx::from_raw((idx as u32).into()) + } } -impl std::ops::Index for ArenaMap { +impl std::ops::Index> for ArenaMap, T> { type Output = T; - fn index(&self, id: ID) -> &T { - self.v[to_idx(id)].as_ref().unwrap() + fn index(&self, id: Idx) -> &T { + self.v[Self::idx_to_raw(id)].as_ref().unwrap() } } -impl Default for ArenaMap { +impl Default for ArenaMap, T> { fn default() -> Self { ArenaMap { v: Vec::new(), diff --git a/crates/mun_hir/src/code_model.rs b/crates/mun_hir/src/code_model.rs index 83cd5db95..0b6d45534 100644 --- a/crates/mun_hir/src/code_model.rs +++ b/crates/mun_hir/src/code_model.rs @@ -1,7 +1,7 @@ pub(crate) mod src; use self::src::HasSource; -use crate::adt::{StructData, StructFieldId, TypeAliasData}; +use crate::adt::{LocalStructFieldId, StructData, TypeAliasData}; use crate::builtin_type::BuiltinType; use crate::code_model::diagnostics::ModuleDefinitionDiagnostic; use crate::diagnostics::DiagnosticSink; @@ -13,7 +13,7 @@ use crate::name_resolution::Namespace; use crate::raw::{DefKind, RawFileItem}; use crate::resolve::{Resolution, Resolver}; use crate::ty::{lower::LowerBatchResult, InferenceResult}; -use crate::type_ref::{TypeRefBuilder, TypeRefId, TypeRefMap, TypeRefSourceMap}; +use crate::type_ref::{LocalTypeRefId, TypeRefBuilder, TypeRefMap, TypeRefSourceMap}; use crate::{ ids::{FunctionId, StructId, TypeAliasId}, AsName, DefDatabase, FileId, HirDatabase, Name, Ty, @@ -232,9 +232,9 @@ pub struct Function { #[derive(Debug, PartialEq, Eq)] pub struct FnData { name: Name, - params: Vec, + params: Vec, visibility: Visibility, - ret_type: TypeRefId, + ret_type: LocalTypeRefId, type_ref_map: TypeRefMap, type_ref_source_map: TypeRefSourceMap, is_extern: bool, @@ -289,7 +289,7 @@ impl FnData { &self.name } - pub fn params(&self) -> &[TypeRefId] { + pub fn params(&self) -> &[LocalTypeRefId] { &self.params } @@ -297,7 +297,7 @@ impl FnData { self.visibility } - pub fn ret_type(&self) -> &TypeRefId { + pub fn ret_type(&self) -> &LocalTypeRefId { &self.ret_type } @@ -373,7 +373,7 @@ pub struct Struct { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct StructField { pub(crate) parent: Struct, - pub(crate) id: StructFieldId, + pub(crate) id: LocalStructFieldId, } impl StructField { @@ -388,7 +388,7 @@ impl StructField { self.parent.data(db.upcast()).fields[self.id].name.clone() } - pub fn id(self) -> StructFieldId { + pub fn id(self) -> LocalStructFieldId { self.id } } @@ -470,7 +470,7 @@ impl TypeAlias { self.data(db).name.clone() } - pub fn type_ref(self, db: &dyn HirDatabase) -> TypeRefId { + pub fn type_ref(self, db: &dyn HirDatabase) -> LocalTypeRefId { self.data(db.upcast()).type_ref_id } @@ -501,7 +501,7 @@ impl TypeAlias { mod diagnostics { use super::Module; use crate::diagnostics::{DiagnosticSink, DuplicateDefinition}; - use crate::raw::{DefId, DefKind}; + use crate::raw::{DefKind, LocalDefId}; use crate::{DefDatabase, Name}; use mun_syntax::{AstNode, SyntaxNodePtr}; @@ -509,8 +509,8 @@ mod diagnostics { pub(super) enum ModuleDefinitionDiagnostic { DuplicateName { name: Name, - definition: DefId, - first_definition: DefId, + definition: LocalDefId, + first_definition: LocalDefId, }, } diff --git a/crates/mun_hir/src/expr.rs b/crates/mun_hir/src/expr.rs index d18497ad8..646b20ca2 100644 --- a/crates/mun_hir/src/expr.rs +++ b/crates/mun_hir/src/expr.rs @@ -1,6 +1,6 @@ use crate::{ arena::map::ArenaMap, - arena::{Arena, RawId}, + arena::{Arena, Idx}, code_model::DefWithBody, FileId, HirDatabase, Name, Path, }; @@ -8,7 +8,7 @@ use crate::{ //pub use mun_syntax::ast::PrefixOp as UnaryOp; use crate::code_model::src::HasSource; use crate::name::AsName; -use crate::type_ref::{TypeRef, TypeRefBuilder, TypeRefId, TypeRefMap, TypeRefSourceMap}; +use crate::type_ref::{LocalTypeRefId, TypeRef, TypeRefBuilder, TypeRefMap, TypeRefSourceMap}; use either::Either; pub use mun_syntax::ast::PrefixOp as UnaryOp; use mun_syntax::ast::{ArgListOwner, BinOp, LoopBodyOwner, NameOwner, TypeAscriptionOwner}; @@ -28,13 +28,8 @@ use std::str::FromStr; pub(crate) mod scope; pub(crate) mod validator; -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct ExprId(RawId); -impl_arena_id!(ExprId); - -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct PatId(RawId); -impl_arena_id!(PatId); +pub type ExprId = Idx; +pub type PatId = Idx; #[derive(Debug, Clone, Eq, PartialEq)] pub enum ExprDiagnostic { @@ -45,25 +40,25 @@ pub enum ExprDiagnostic { #[derive(Debug, Eq, PartialEq)] pub struct Body { owner: DefWithBody, - exprs: Arena, - pats: Arena, + exprs: Arena, + pats: Arena, type_refs: TypeRefMap, /// The patterns for the function's parameters. While the parameter types are part of the /// function signature, the patterns are not (they don't change the external type of the /// function). /// /// If this `Body` is for the body of a constant, this will just be empty. - params: Vec<(PatId, TypeRefId)>, + params: Vec<(PatId, LocalTypeRefId)>, /// The `ExprId` of the actual body expression. body_expr: ExprId, - ret_type: TypeRefId, + ret_type: LocalTypeRefId, /// Diagnostics encountered when parsing the ast expressions diagnostics: Vec, } impl Body { - pub fn params(&self) -> &[(PatId, TypeRefId)] { + pub fn params(&self) -> &[(PatId, LocalTypeRefId)] { &self.params } @@ -87,7 +82,7 @@ impl Body { &self.type_refs } - pub fn ret_type(&self) -> TypeRefId { + pub fn ret_type(&self) -> LocalTypeRefId { self.ret_type } @@ -120,10 +115,10 @@ impl Index for Body { } } -impl Index for Body { +impl Index for Body { type Output = TypeRef; - fn index(&self, type_ref: TypeRefId) -> &TypeRef { + fn index(&self, type_ref: LocalTypeRefId) -> &TypeRef { &self.type_refs[type_ref] } } @@ -155,7 +150,7 @@ impl BodySourceMap { self.expr_map_back.get(expr).cloned() } - pub fn type_ref_syntax(&self, type_ref: TypeRefId) -> Option> { + pub fn type_ref_syntax(&self, type_ref: LocalTypeRefId) -> Option> { self.type_refs.type_ref_syntax(type_ref) } @@ -194,7 +189,7 @@ pub struct RecordLitField { pub enum Statement { Let { pat: PatId, - type_ref: Option, + type_ref: Option, initializer: Option, }, Expr(ExprId), @@ -293,7 +288,7 @@ pub enum Expr { body: ExprId, }, RecordLit { - type_id: TypeRefId, + type_id: LocalTypeRefId, fields: Vec, spread: Option, }, @@ -436,12 +431,12 @@ impl Pat { pub(crate) struct ExprCollector<'a> { db: &'a dyn HirDatabase, owner: DefWithBody, - exprs: Arena, - pats: Arena, + exprs: Arena, + pats: Arena, source_map: BodySourceMap, - params: Vec<(PatId, TypeRefId)>, + params: Vec<(PatId, LocalTypeRefId)>, body_expr: Option, - ret_type: Option, + ret_type: Option, type_ref_builder: TypeRefBuilder, current_file_id: FileId, diagnostics: Vec, @@ -943,7 +938,7 @@ pub fn resolver_for_expr(body: Arc, db: &dyn HirDatabase, expr_id: ExprId) pub(crate) fn resolver_for_scope( body: Arc, db: &dyn HirDatabase, - scope_id: Option, + scope_id: Option, ) -> Resolver { let mut r = body.owner.resolver(db); let scopes = db.expr_scopes(body.owner); diff --git a/crates/mun_hir/src/expr/scope.rs b/crates/mun_hir/src/expr/scope.rs index 399bd14ce..8940bcfc7 100644 --- a/crates/mun_hir/src/expr/scope.rs +++ b/crates/mun_hir/src/expr/scope.rs @@ -1,22 +1,21 @@ use crate::code_model::DefWithBody; use crate::expr::{Expr, Pat, PatId, Statement}; use crate::{ - arena::{Arena, RawId}, + arena::{Arena, Idx}, expr::{Body, ExprId}, HirDatabase, Name, }; use rustc_hash::FxHashMap; use std::sync::Arc; -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct ScopeId(RawId); -impl_arena_id!(ScopeId); +/// The ID of a scope in an `ExprScopes` +pub(crate) type LocalScopeId = Idx; #[derive(Debug, PartialEq, Eq)] pub struct ExprScopes { body: Arc, - scopes: Arena, - scope_by_expr: FxHashMap, + scopes: Arena, + scope_by_expr: FxHashMap, } #[derive(Debug, PartialEq, Eq)] @@ -37,7 +36,7 @@ impl ScopeEntry { #[derive(Debug, PartialEq, Eq)] pub(crate) struct ScopeData { - parent: Option, + parent: Option, entries: Vec, } @@ -60,40 +59,40 @@ impl ExprScopes { scopes } - pub(crate) fn entries(&self, scope: ScopeId) -> &[ScopeEntry] { + pub(crate) fn entries(&self, scope: LocalScopeId) -> &[ScopeEntry] { &self.scopes[scope].entries } pub(crate) fn scope_chain<'a>( &'a self, - scope: Option, - ) -> impl Iterator + 'a { + scope: Option, + ) -> impl Iterator + 'a { std::iter::successors(scope, move |&scope| self.scopes[scope].parent) } - pub(crate) fn scope_for(&self, expr: ExprId) -> Option { + pub(crate) fn scope_for(&self, expr: ExprId) -> Option { self.scope_by_expr.get(&expr).copied() } - pub(crate) fn scope_by_expr(&self) -> &FxHashMap { + pub(crate) fn scope_by_expr(&self) -> &FxHashMap { &self.scope_by_expr } - fn root_scope(&mut self) -> ScopeId { + fn root_scope(&mut self) -> LocalScopeId { self.scopes.alloc(ScopeData { parent: None, entries: vec![], }) } - fn new_scope(&mut self, parent: ScopeId) -> ScopeId { + fn new_scope(&mut self, parent: LocalScopeId) -> LocalScopeId { self.scopes.alloc(ScopeData { parent: Some(parent), entries: vec![], }) } - fn add_bindings(&mut self, body: &Body, scope: ScopeId, pat: PatId) { + fn add_bindings(&mut self, body: &Body, scope: LocalScopeId, pat: PatId) { match &body[pat] { Pat::Bind { name, .. } => { // bind can have a sub pattern, but it's actually not allowed @@ -108,12 +107,16 @@ impl ExprScopes { } } - fn add_params_bindings<'a>(&mut self, scope: ScopeId, params: impl Iterator) { + fn add_params_bindings<'a>( + &mut self, + scope: LocalScopeId, + params: impl Iterator, + ) { let body = Arc::clone(&self.body); params.for_each(|pat| self.add_bindings(&body, scope, *pat)); } - fn set_scope(&mut self, node: ExprId, scope: ScopeId) { + fn set_scope(&mut self, node: ExprId, scope: LocalScopeId) { self.scope_by_expr.insert(node, scope); } } @@ -123,7 +126,7 @@ fn compute_block_scopes( tail: Option, body: &Body, scopes: &mut ExprScopes, - mut scope: ScopeId, + mut scope: LocalScopeId, ) { for stmt in statements { match stmt { @@ -148,7 +151,7 @@ fn compute_block_scopes( } } -fn compute_expr_scopes(expr: ExprId, body: &Body, scopes: &mut ExprScopes, scope: ScopeId) { +fn compute_expr_scopes(expr: ExprId, body: &Body, scopes: &mut ExprScopes, scope: LocalScopeId) { scopes.set_scope(expr, scope); match &body[expr] { Expr::Block { statements, tail } => { diff --git a/crates/mun_hir/src/lib.rs b/crates/mun_hir/src/lib.rs index 3d766e00c..a9f29c372 100644 --- a/crates/mun_hir/src/lib.rs +++ b/crates/mun_hir/src/lib.rs @@ -41,7 +41,6 @@ pub use salsa; pub use relative_path::{RelativePath, RelativePathBuf}; pub use crate::{ - arena::{ArenaId, RawId}, builtin_type::{FloatBitness, IntBitness, Signedness}, db::{ DefDatabase, DefDatabaseStorage, HirDatabase, HirDatabaseStorage, SourceDatabase, @@ -68,7 +67,6 @@ pub use crate::{ }; use crate::{ - arena::Arena, name::AsName, source_id::{AstIdMap, FileAstId}, }; diff --git a/crates/mun_hir/src/raw.rs b/crates/mun_hir/src/raw.rs index 9fc6cdc99..b5851844e 100644 --- a/crates/mun_hir/src/raw.rs +++ b/crates/mun_hir/src/raw.rs @@ -1,21 +1,22 @@ use mun_syntax::ast::{self, ModuleItemOwner, NameOwner}; -use crate::name::AsName; -use crate::{Arena, DefDatabase, FileAstId, FileId, Name, RawId}; +use crate::{ + arena::{Arena, Idx}, + name::AsName, + DefDatabase, FileAstId, FileId, Name, +}; use std::ops::Index; use std::sync::Arc; /// `RawItems` are top level file items. `RawItems` do not change on most edits. #[derive(Debug, Default, PartialEq, Eq)] pub struct RawItems { - definitions: Arena, + definitions: Arena, items: Vec, } -/// Id for a module definition -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub(super) struct DefId(RawId); -impl_arena_id!(DefId); +/// Represents an id of a `DefData` in `RawItems`. +pub(super) type LocalDefId = Idx; #[derive(Debug, PartialEq, Eq)] pub(super) struct DefData { @@ -32,13 +33,13 @@ pub(super) enum DefKind { #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub(super) enum RawFileItem { - Definition(DefId), + Definition(LocalDefId), } -impl Index for RawItems { +impl Index for RawItems { type Output = DefData; - fn index(&self, index: DefId) -> &Self::Output { + fn index(&self, index: LocalDefId) -> &Self::Output { &self.definitions[index] } } diff --git a/crates/mun_hir/src/resolve.rs b/crates/mun_hir/src/resolve.rs index af3695a33..97f486b3b 100644 --- a/crates/mun_hir/src/resolve.rs +++ b/crates/mun_hir/src/resolve.rs @@ -1,5 +1,5 @@ use crate::{ - expr::scope::ScopeId, expr::PatId, ExprScopes, FileId, HirDatabase, ModuleDef, Name, Path, + expr::scope::LocalScopeId, expr::PatId, ExprScopes, FileId, HirDatabase, ModuleDef, Name, Path, PerNs, }; use std::sync::Arc; @@ -26,7 +26,7 @@ pub(crate) struct ModuleItemMap { #[derive(Debug, Clone)] pub(crate) struct ExprScope { expr_scopes: Arc, - scope_id: ScopeId, + scope_id: LocalScopeId, } impl Resolver { @@ -42,7 +42,7 @@ impl Resolver { pub(crate) fn push_expr_scope( self, expr_scopes: Arc, - scope_id: ScopeId, + scope_id: LocalScopeId, ) -> Resolver { self.push_scope(Scope::ExprScope(ExprScope { expr_scopes, diff --git a/crates/mun_hir/src/source_id.rs b/crates/mun_hir/src/source_id.rs index a5d28d5ab..3c52be89f 100644 --- a/crates/mun_hir/src/source_id.rs +++ b/crates/mun_hir/src/source_id.rs @@ -1,5 +1,6 @@ +use crate::arena::{Arena, Idx}; use crate::in_file::InFile; -use crate::{db::DefDatabase, Arena, FileId, RawId}; +use crate::{db::DefDatabase, FileId}; use mun_syntax::{ast, AstNode, AstPtr, SyntaxNode, SyntaxNodePtr}; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; @@ -53,13 +54,10 @@ impl FileAstId { /// Maps items' `SyntaxNode`s to `ErasedFileAstId`s and back. #[derive(Debug, PartialEq, Eq, Default)] pub struct AstIdMap { - arena: Arena, + arena: Arena, } -/// An id of an AST node in a specific file. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct ErasedFileAstId(RawId); -impl_arena_id!(ErasedFileAstId); +type ErasedFileAstId = Idx; impl AstIdMap { pub(crate) fn ast_id_map_query(db: &dyn DefDatabase, file_id: FileId) -> Arc { diff --git a/crates/mun_hir/src/ty/infer.rs b/crates/mun_hir/src/ty/infer.rs index 339f23368..e61a92e0b 100644 --- a/crates/mun_hir/src/ty/infer.rs +++ b/crates/mun_hir/src/ty/infer.rs @@ -12,7 +12,7 @@ use crate::{ ty::lower::LowerDiagnostic, ty::op, ty::{Ty, TypableDef}, - type_ref::TypeRefId, + type_ref::LocalTypeRefId, ApplicationTy, BinaryOp, Function, HirDatabase, Name, Path, TypeCtor, }; use rustc_hash::FxHashSet; @@ -178,9 +178,9 @@ impl<'a> InferenceResultBuilder<'a> { self.type_of_pat.insert(pat, ty); } - /// Given a `TypeRefId`, resolve the reference to an actual `Ty`. If the the type could not + /// Given a `LocalTypeRefId`, resolve the reference to an actual `Ty`. If the the type could not /// be resolved an error is emitted and `Ty::Error` is returned. - fn resolve_type(&mut self, type_ref: TypeRefId) -> Ty { + fn resolve_type(&mut self, type_ref: LocalTypeRefId) -> Ty { // Try to resolve the type from the Hir let result = Ty::from_hir( self.db, @@ -1011,7 +1011,7 @@ mod diagnostics { code_model::src::HasSource, diagnostics::{CyclicType, DiagnosticSink, UnresolvedType, UnresolvedValue}, ty::infer::ExprOrPatId, - type_ref::TypeRefId, + type_ref::LocalTypeRefId, ExprId, Function, HirDatabase, IntTy, Name, Ty, }; @@ -1021,10 +1021,10 @@ mod diagnostics { id: ExprOrPatId, }, UnresolvedType { - id: TypeRefId, + id: LocalTypeRefId, }, CyclicType { - id: TypeRefId, + id: LocalTypeRefId, }, ExpectedFunction { id: ExprId, diff --git a/crates/mun_hir/src/ty/lower.rs b/crates/mun_hir/src/ty/lower.rs index 5a22e03b3..37d0a1874 100644 --- a/crates/mun_hir/src/ty/lower.rs +++ b/crates/mun_hir/src/ty/lower.rs @@ -6,7 +6,7 @@ use crate::diagnostics::DiagnosticSink; use crate::name_resolution::Namespace; use crate::resolve::{Resolution, Resolver}; use crate::ty::{FnSig, Ty, TypeCtor}; -use crate::type_ref::{TypeRef, TypeRefId, TypeRefMap, TypeRefSourceMap}; +use crate::type_ref::{LocalTypeRefId, TypeRef, TypeRefMap, TypeRefSourceMap}; use crate::{FileId, Function, HirDatabase, ModuleDef, Path, Struct, TypeAlias}; use std::ops::Index; use std::sync::Arc; @@ -19,13 +19,13 @@ pub(crate) struct LowerResult { #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct LowerBatchResult { - pub(crate) type_ref_to_type: ArenaMap, + pub(crate) type_ref_to_type: ArenaMap, pub(crate) diagnostics: Vec, } -impl Index for LowerBatchResult { +impl Index for LowerBatchResult { type Output = Ty; - fn index(&self, expr: TypeRefId) -> &Ty { + fn index(&self, expr: LocalTypeRefId) -> &Ty { self.type_ref_to_type.get(expr).unwrap_or(&Ty::Unknown) } } @@ -50,7 +50,7 @@ impl Ty { db: &dyn HirDatabase, resolver: &Resolver, type_ref_map: &TypeRefMap, - type_ref: TypeRefId, + type_ref: LocalTypeRefId, ) -> LowerResult { let mut diagnostics = Vec::new(); let ty = @@ -63,7 +63,7 @@ impl Ty { resolver: &Resolver, type_ref_map: &TypeRefMap, diagnostics: &mut Vec, - type_ref: TypeRefId, + type_ref: LocalTypeRefId, ) -> Ty { let res = match &type_ref_map[type_ref] { TypeRef::Path(path) => Ty::from_hir_path(db, resolver, path), @@ -297,14 +297,14 @@ pub mod diagnostics { use crate::diagnostics::{CyclicType, UnresolvedType}; use crate::{ diagnostics::DiagnosticSink, - type_ref::{TypeRefId, TypeRefSourceMap}, + type_ref::{LocalTypeRefId, TypeRefSourceMap}, FileId, HirDatabase, }; #[derive(Debug, PartialEq, Eq, Clone)] pub(crate) enum LowerDiagnostic { - UnresolvedType { id: TypeRefId }, - CyclicType { id: TypeRefId }, + UnresolvedType { id: LocalTypeRefId }, + CyclicType { id: LocalTypeRefId }, } impl LowerDiagnostic { diff --git a/crates/mun_hir/src/type_ref.rs b/crates/mun_hir/src/type_ref.rs index 37ad763d8..92163d1f9 100644 --- a/crates/mun_hir/src/type_ref.rs +++ b/crates/mun_hir/src/type_ref.rs @@ -1,16 +1,16 @@ -use crate::arena::map::ArenaMap; -use crate::arena::{Arena, RawId}; -///! HIR for references to types. These paths are not yet resolved. They can be directly created -/// from an `ast::TypeRef`, without further queries. -use crate::Path; -use mun_syntax::ast; -use mun_syntax::AstPtr; +//! HIR for references to types. These paths are not yet resolved. They can be directly created +//! from an `ast::TypeRef`, without further queries. + +use crate::{ + arena::{map::ArenaMap, Arena, Idx}, + Path, +}; +use mun_syntax::{ast, AstPtr}; use rustc_hash::FxHashMap; use std::ops::Index; -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct TypeRefId(RawId); -impl_arena_id!(TypeRefId); +/// The ID of a `TypeRef` in a `TypeRefMap` +pub type LocalTypeRefId = Idx; /// Compare ty::Ty #[derive(Clone, PartialEq, Eq, Hash, Debug)] @@ -48,36 +48,36 @@ impl TypeRef { #[derive(Default, Debug, Eq, PartialEq)] pub struct TypeRefSourceMap { - type_ref_map: FxHashMap, TypeRefId>, - type_ref_map_back: ArenaMap>, + type_ref_map: FxHashMap, LocalTypeRefId>, + type_ref_map_back: ArenaMap>, } impl TypeRefSourceMap { - pub(crate) fn type_ref_syntax(&self, expr: TypeRefId) -> Option> { + pub(crate) fn type_ref_syntax(&self, expr: LocalTypeRefId) -> Option> { self.type_ref_map_back.get(expr).cloned() } - pub(crate) fn syntax_type_ref(&self, ptr: AstPtr) -> Option { + pub(crate) fn syntax_type_ref(&self, ptr: AstPtr) -> Option { self.type_ref_map.get(&ptr).cloned() } } #[derive(Default, Debug, Eq, PartialEq)] pub struct TypeRefMap { - type_refs: Arena, + type_refs: Arena, } impl TypeRefMap { /// Iterate over the elements in the map - pub fn iter(&self) -> impl Iterator { + pub fn iter(&self) -> impl Iterator { self.type_refs.iter() } } -impl Index for TypeRefMap { +impl Index for TypeRefMap { type Output = TypeRef; - fn index(&self, pat: TypeRefId) -> &Self::Output { + fn index(&self, pat: LocalTypeRefId) -> &Self::Output { &self.type_refs[pat] } } @@ -89,14 +89,14 @@ pub(crate) struct TypeRefBuilder { } impl TypeRefBuilder { - fn alloc_type_ref(&mut self, type_ref: TypeRef, ptr: AstPtr) -> TypeRefId { + fn alloc_type_ref(&mut self, type_ref: TypeRef, ptr: AstPtr) -> LocalTypeRefId { let id = self.map.type_refs.alloc(type_ref); self.source_map.type_ref_map.insert(ptr, id); self.source_map.type_ref_map_back.insert(id, ptr); id } - pub fn alloc_from_node_opt(&mut self, node: Option<&ast::TypeRef>) -> TypeRefId { + pub fn alloc_from_node_opt(&mut self, node: Option<&ast::TypeRef>) -> LocalTypeRefId { if let Some(node) = node { self.alloc_from_node(node) } else { @@ -104,7 +104,7 @@ impl TypeRefBuilder { } } - pub fn alloc_from_node(&mut self, node: &ast::TypeRef) -> TypeRefId { + pub fn alloc_from_node(&mut self, node: &ast::TypeRef) -> LocalTypeRefId { use mun_syntax::ast::TypeRefKind::*; let ptr = AstPtr::new(node); let type_ref = match node.kind() { @@ -118,11 +118,11 @@ impl TypeRefBuilder { self.alloc_type_ref(type_ref, ptr) } - pub fn unit(&mut self) -> TypeRefId { + pub fn unit(&mut self) -> LocalTypeRefId { self.map.type_refs.alloc(TypeRef::Empty) } - pub fn error(&mut self) -> TypeRefId { + pub fn error(&mut self) -> LocalTypeRefId { self.map.type_refs.alloc(TypeRef::Error) }