Re-implement InFile wrappers as type aliases over generic InFileWrapper

This commit is contained in:
Lukas Wirth 2023-11-25 14:39:55 +01:00
parent 30093a6d81
commit c43078f99d
13 changed files with 151 additions and 107 deletions

View file

@ -102,7 +102,7 @@ impl fmt::Debug for HirFileId {
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MacroFile {
pub struct MacroFileId {
pub macro_call_id: MacroCallId,
}
/// `MacroCallId` identifies a particular macro invocation, like
@ -113,18 +113,18 @@ crate::impl_intern_key!(MacroCallId);
impl MacroCallId {
pub fn as_file(self) -> HirFileId {
MacroFile { macro_call_id: self }.into()
MacroFileId { macro_call_id: self }.into()
}
pub fn as_macro_file(self) -> MacroFile {
MacroFile { macro_call_id: self }
pub fn as_macro_file(self) -> MacroFileId {
MacroFileId { macro_call_id: self }
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum HirFileIdRepr {
FileId(FileId),
MacroFile(MacroFile),
MacroFile(MacroFileId),
}
impl fmt::Debug for HirFileIdRepr {
@ -145,8 +145,8 @@ impl From<FileId> for HirFileId {
}
}
impl From<MacroFile> for HirFileId {
fn from(MacroFile { macro_call_id: MacroCallId(id) }: MacroFile) -> Self {
impl From<MacroFileId> for HirFileId {
fn from(MacroFileId { macro_call_id: MacroCallId(id) }: MacroFileId) -> Self {
let id = id.as_u32();
assert!(id < Self::MAX_FILE_ID);
HirFileId(id | Self::MACRO_FILE_TAG_MASK)
@ -163,10 +163,10 @@ impl HirFileId {
}
#[inline]
pub fn macro_file(self) -> Option<MacroFile> {
pub fn macro_file(self) -> Option<MacroFileId> {
match self.0 & Self::MACRO_FILE_TAG_MASK {
0 => None,
_ => Some(MacroFile {
_ => Some(MacroFileId {
macro_call_id: MacroCallId(InternId::from(self.0 ^ Self::MACRO_FILE_TAG_MASK)),
}),
}
@ -184,7 +184,7 @@ impl HirFileId {
pub fn repr(self) -> HirFileIdRepr {
match self.0 & Self::MACRO_FILE_TAG_MASK {
0 => HirFileIdRepr::FileId(FileId(self.0)),
_ => HirFileIdRepr::MacroFile(MacroFile {
_ => HirFileIdRepr::MacroFile(MacroFileId {
macro_call_id: MacroCallId(InternId::from(self.0 ^ Self::MACRO_FILE_TAG_MASK)),
}),
}

View file

@ -18,7 +18,7 @@ use std::{iter, ops::Range, sync};
use base_db::{fixture::WithFixture, ProcMacro, SourceDatabase};
use expect_test::Expect;
use hir_expand::{db::ExpandDatabase, span::SpanMapRef, HirFileIdExt, InFile, MacroFile};
use hir_expand::{db::ExpandDatabase, span::SpanMapRef, HirFileIdExt, InFile, MacroFileId};
use stdx::format_to;
use syntax::{
ast::{self, edit::IndentLevel},
@ -94,7 +94,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream
})
.unwrap();
let macro_call_id = res.value.unwrap();
let macro_file = MacroFile { macro_call_id };
let macro_file = MacroFileId { macro_call_id };
let mut expansion_result = db.parse_macro_expansion(macro_file);
expansion_result.err = expansion_result.err.or(res.err);
expansions.push((macro_call.value.clone(), expansion_result));

View file

@ -24,7 +24,7 @@ use crate::{
span::{RealSpanMap, SpanMap, SpanMapRef},
tt, AstId, BuiltinAttrExpander, BuiltinDeriveExpander, BuiltinFnLikeExpander, EagerCallInfo,
ExpandError, ExpandResult, ExpandTo, ExpansionSpanMap, HirFileId, HirFileIdRepr, MacroCallId,
MacroCallKind, MacroCallLoc, MacroDefId, MacroDefKind, MacroFile, ProcMacroExpander,
MacroCallKind, MacroCallLoc, MacroDefId, MacroDefKind, MacroFileId, ProcMacroExpander,
};
/// Total limit on the number of tokens produced by any macro invocation.
@ -102,7 +102,7 @@ pub trait ExpandDatabase: SourceDatabase {
// This query is LRU cached
fn parse_macro_expansion(
&self,
macro_file: MacroFile,
macro_file: MacroFileId,
) -> ExpandResult<(Parse<SyntaxNode>, Arc<ExpansionSpanMap>)>;
#[salsa::transparent]
fn span_map(&self, file_id: HirFileId) -> SpanMap;
@ -307,7 +307,7 @@ fn parse_or_expand_with_err(
fn parse_macro_expansion(
db: &dyn ExpandDatabase,
macro_file: MacroFile,
macro_file: MacroFileId,
) -> ExpandResult<(Parse<SyntaxNode>, Arc<ExpansionSpanMap>)> {
let _p = profile::span("parse_macro_expansion");
let mbe::ValueResult { value: tt, err } = db.macro_expand(macro_file.macro_call_id);
@ -326,7 +326,7 @@ fn parse_macro_expansion_error(
db: &dyn ExpandDatabase,
macro_call_id: MacroCallId,
) -> ExpandResult<Box<[SyntaxError]>> {
db.parse_macro_expansion(MacroFile { macro_call_id })
db.parse_macro_expansion(MacroFileId { macro_call_id })
.map(|it| it.0.errors().to_vec().into_boxed_slice())
}

View file

@ -1,15 +1,14 @@
use std::iter;
use base_db::{
span::{HirFileId, HirFileIdRepr, MacroFile, SyntaxContextId},
FileRange,
span::{HirFileId, HirFileIdRepr, MacroFileId, SyntaxContextId},
FileId, FileRange,
};
use either::Either;
use syntax::{AstNode, SyntaxNode, SyntaxToken, TextRange};
use crate::{db, ExpansionInfo, HirFileIdExt as _};
// FIXME: Make an InRealFile wrapper
/// `InFile<T>` stores a value of `T` inside a particular file/syntax tree.
///
/// Typical usages are:
@ -18,52 +17,88 @@ use crate::{db, ExpansionInfo, HirFileIdExt as _};
/// * `InFile<ast::FnDef>` -- ast node in a file
/// * `InFile<TextSize>` -- offset in a file
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
pub struct InFile<T> {
pub file_id: HirFileId,
pub struct InFileWrapper<FileKind, T> {
pub file_id: FileKind,
pub value: T,
}
pub type InFile<T> = InFileWrapper<HirFileId, T>;
pub type InMacroFile<T> = InFileWrapper<MacroFileId, T>;
pub type InRealFile<T> = InFileWrapper<FileId, T>;
impl<T> InFile<T> {
pub fn new(file_id: HirFileId, value: T) -> InFile<T> {
InFile { file_id, value }
impl<FileKind, T> InFileWrapper<FileKind, T> {
pub fn new(file_id: FileKind, value: T) -> Self {
Self { file_id, value }
}
pub fn with_value<U>(&self, value: U) -> InFile<U> {
InFile::new(self.file_id, value)
pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> InFileWrapper<FileKind, U> {
InFileWrapper::new(self.file_id, f(self.value))
}
}
impl<FileKind: Copy, T> InFileWrapper<FileKind, T> {
pub fn with_value<U>(&self, value: U) -> InFileWrapper<FileKind, U> {
InFileWrapper::new(self.file_id, value)
}
pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> InFile<U> {
InFile::new(self.file_id, f(self.value))
}
pub fn as_ref(&self) -> InFile<&T> {
pub fn as_ref(&self) -> InFileWrapper<FileKind, &T> {
self.with_value(&self.value)
}
}
impl<FileKind: Copy, T: Clone> InFileWrapper<FileKind, &T> {
pub fn cloned(&self) -> InFileWrapper<FileKind, T> {
self.with_value(self.value.clone())
}
}
impl<T> From<InMacroFile<T>> for InFile<T> {
fn from(InMacroFile { file_id, value }: InMacroFile<T>) -> Self {
InFile { file_id: file_id.into(), value }
}
}
impl<T> From<InRealFile<T>> for InFile<T> {
fn from(InRealFile { file_id, value }: InRealFile<T>) -> Self {
InFile { file_id: file_id.into(), value }
}
}
// region:transpose impls
impl<FileKind, T> InFileWrapper<FileKind, Option<T>> {
pub fn transpose(self) -> Option<InFileWrapper<FileKind, T>> {
Some(InFileWrapper::new(self.file_id, self.value?))
}
}
impl<FileKind, L, R> InFileWrapper<FileKind, Either<L, R>> {
pub fn transpose(self) -> Either<InFileWrapper<FileKind, L>, InFileWrapper<FileKind, R>> {
match self.value {
Either::Left(l) => Either::Left(InFileWrapper::new(self.file_id, l)),
Either::Right(r) => Either::Right(InFileWrapper::new(self.file_id, r)),
}
}
}
// endregion:transpose impls
// region:specific impls
impl<T> InFile<T> {
pub fn file_syntax(&self, db: &dyn db::ExpandDatabase) -> SyntaxNode {
db.parse_or_expand(self.file_id)
}
}
impl<T: Clone> InFile<&T> {
pub fn cloned(&self) -> InFile<T> {
self.with_value(self.value.clone())
impl<T> InRealFile<T> {
pub fn file_syntax(&self, db: &dyn db::ExpandDatabase) -> SyntaxNode {
db.parse(self.file_id).syntax_node()
}
}
impl<T> InFile<Option<T>> {
pub fn transpose(self) -> Option<InFile<T>> {
let value = self.value?;
Some(InFile::new(self.file_id, value))
}
}
impl<L, R> InFile<Either<L, R>> {
pub fn transpose(self) -> Either<InFile<L>, InFile<R>> {
match self.value {
Either::Left(l) => Either::Left(InFile::new(self.file_id, l)),
Either::Right(r) => Either::Right(InFile::new(self.file_id, r)),
}
impl<T> InMacroFile<T> {
pub fn file_syntax(&self, db: &dyn db::ExpandDatabase) -> SyntaxNode {
db.parse_macro_expansion(self.file_id).value.0.syntax_node()
}
}
@ -159,11 +194,17 @@ impl InFile<&SyntaxNode> {
}
}
pub fn original_syntax_node(self, db: &dyn db::ExpandDatabase) -> Option<InFile<SyntaxNode>> {
pub fn original_syntax_node(
self,
db: &dyn db::ExpandDatabase,
) -> Option<InRealFile<SyntaxNode>> {
// This kind of upmapping can only be achieved in attribute expanded files,
// as we don't have node inputs otherwise and therefore can't find an `N` node in the input
let Some(file_id) = self.file_id.macro_file() else {
return Some(self.map(Clone::clone));
let file_id = match self.file_id.repr() {
HirFileIdRepr::FileId(file_id) => {
return Some(InRealFile { file_id, value: self.value.clone() })
}
HirFileIdRepr::MacroFile(m) => m,
};
if !self.file_id.is_attr_macro(db) {
return None;
@ -182,7 +223,7 @@ impl InFile<&SyntaxNode> {
let kind = self.value.kind();
// FIXME: This heuristic is brittle and with the right macro may select completely unrelated nodes?
let value = anc.ancestors().find(|it| it.kind() == kind)?;
Some(InFile::new(file_id.into(), value))
Some(InRealFile::new(file_id, value))
}
}
@ -230,29 +271,11 @@ impl InFile<SyntaxToken> {
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
pub struct InMacroFile<T> {
pub file_id: MacroFile,
pub value: T,
}
impl<T> From<InMacroFile<T>> for InFile<T> {
fn from(macro_file: InMacroFile<T>) -> Self {
InFile { file_id: macro_file.file_id.into(), value: macro_file.value }
}
}
pub fn ascend_range_up_macros(
db: &dyn db::ExpandDatabase,
range: InFile<TextRange>,
) -> (FileRange, SyntaxContextId) {
match range.file_id.repr() {
HirFileIdRepr::FileId(file_id) => {
(FileRange { file_id, range: range.value }, SyntaxContextId::ROOT)
}
HirFileIdRepr::MacroFile(m) => {
ExpansionInfo::new(db, m).map_token_range_up(db, range.value)
}
impl InFile<TextRange> {
/// Attempts to map the syntax node back up its macro calls.
pub fn original_file_range(self, db: &dyn db::ExpandDatabase) -> FileRange {
let (range, _ctxt) = ascend_range_up_macros(db, self);
range
}
}
@ -261,12 +284,14 @@ impl<N: AstNode> InFile<N> {
self.value.syntax().descendants().filter_map(T::cast).map(move |n| self.with_value(n))
}
// FIXME: this should return `Option<InFileNotHirFile<N>>`
pub fn original_ast_node(self, db: &dyn db::ExpandDatabase) -> Option<InFile<N>> {
pub fn original_ast_node(self, db: &dyn db::ExpandDatabase) -> Option<InRealFile<N>> {
// This kind of upmapping can only be achieved in attribute expanded files,
// as we don't have node inputs otherwise and therefore can't find an `N` node in the input
let Some(file_id) = self.file_id.macro_file() else {
return Some(self);
let file_id = match self.file_id.repr() {
HirFileIdRepr::FileId(file_id) => {
return Some(InRealFile { file_id, value: self.value })
}
HirFileIdRepr::MacroFile(m) => m,
};
if !self.file_id.is_attr_macro(db) {
return None;
@ -284,10 +309,24 @@ impl<N: AstNode> InFile<N> {
// FIXME: This heuristic is brittle and with the right macro may select completely unrelated nodes?
let anc = db.parse(file_id).syntax_node().covering_element(range);
let value = anc.ancestors().find_map(N::cast)?;
return Some(InFile::new(file_id.into(), value));
Some(InRealFile::new(file_id, value))
}
pub fn syntax(&self) -> InFile<&SyntaxNode> {
self.with_value(self.value.syntax())
}
}
fn ascend_range_up_macros(
db: &dyn db::ExpandDatabase,
range: InFile<TextRange>,
) -> (FileRange, SyntaxContextId) {
match range.file_id.repr() {
HirFileIdRepr::FileId(file_id) => {
(FileRange { file_id, range: range.value }, SyntaxContextId::ROOT)
}
HirFileIdRepr::MacroFile(m) => {
ExpansionInfo::new(db, m).map_token_range_up(db, range.value)
}
}
}

View file

@ -48,9 +48,9 @@ use crate::{
};
pub use crate::ast_id_map::{AstId, ErasedAstId, ErasedFileAstId};
pub use crate::files::{InFile, InMacroFile};
pub use crate::files::{InFile, InMacroFile, InRealFile};
pub use base_db::span::{HirFileId, MacroCallId, MacroFile};
pub use base_db::span::{HirFileId, MacroCallId, MacroFileId};
pub use mbe::ValueResult;
pub type DeclarativeMacro = ::mbe::DeclarativeMacro<tt::SpanData>;
@ -206,7 +206,7 @@ impl HirFileIdExt for HirFileId {
loop {
match file_id.repr() {
HirFileIdRepr::FileId(id) => break id,
HirFileIdRepr::MacroFile(MacroFile { macro_call_id }) => {
HirFileIdRepr::MacroFile(MacroFileId { macro_call_id }) => {
let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_call_id);
let is_include_expansion = loc.def.is_include() && loc.eager.is_some();
file_id = match is_include_expansion.then(|| db.include_expand(macro_call_id)) {
@ -241,7 +241,7 @@ impl HirFileIdExt for HirFileId {
loop {
match call.file_id.repr() {
HirFileIdRepr::FileId(file_id) => break Some((file_id, call.value)),
HirFileIdRepr::MacroFile(MacroFile { macro_call_id }) => {
HirFileIdRepr::MacroFile(MacroFileId { macro_call_id }) => {
call = db.lookup_intern_macro_call(macro_call_id).to_node(db);
}
}
@ -700,7 +700,7 @@ impl ExpansionInfo {
}
}
pub fn new(db: &dyn db::ExpandDatabase, macro_file: MacroFile) -> ExpansionInfo {
pub fn new(db: &dyn db::ExpandDatabase, macro_file: MacroFileId) -> ExpansionInfo {
let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
let arg_tt = loc.kind.arg(db);

View file

@ -59,7 +59,7 @@ use hir_def::{
Lookup, MacroExpander, MacroId, ModuleId, StaticId, StructId, TraitAliasId, TraitId,
TypeAliasId, TypeOrConstParamId, TypeParamId, UnionId,
};
use hir_expand::{name::name, InMacroFile, MacroCallKind};
use hir_expand::{name::name, MacroCallKind};
use hir_ty::{
all_super_traits, autoderef, check_orphan_rules,
consteval::{try_const_usize, unknown_const_as_generic, ConstEvalError, ConstExt},
@ -124,7 +124,7 @@ pub use {
hir_expand::{
attrs::{Attr, AttrId},
name::{known, Name},
tt, ExpandResult, HirFileId, HirFileIdExt, InFile, MacroFile,
tt, ExpandResult, HirFileId, HirFileIdExt, InFile, InMacroFile, InRealFile, MacroFileId,
},
hir_ty::{
display::{ClosureStyle, HirDisplay, HirDisplayError, HirWrite},
@ -3505,7 +3505,7 @@ impl Impl {
}
_ => return None,
};
let file_id = MacroFile { macro_call_id: derive_attr };
let file_id = MacroFileId { macro_call_id: derive_attr };
let path = db
.parse_macro_expansion(file_id)
.value

View file

@ -15,7 +15,9 @@ use hir_def::{
type_ref::Mutability,
AsMacroCall, DefWithBodyId, FieldId, FunctionId, MacroId, TraitId, VariantId,
};
use hir_expand::{db::ExpandDatabase, name::AsName, ExpansionInfo, HirFileIdExt, MacroCallId};
use hir_expand::{
db::ExpandDatabase, files::InRealFile, name::AsName, ExpansionInfo, HirFileIdExt, MacroCallId,
};
use itertools::Itertools;
use rustc_hash::{FxHashMap, FxHashSet};
use smallvec::{smallvec, SmallVec};
@ -756,8 +758,8 @@ impl<'db> SemanticsImpl<'db> {
/// This only work for attribute expansions, as other ones do not have nodes as input.
pub fn original_ast_node<N: AstNode>(&self, node: N) -> Option<N> {
self.wrap_node_infile(node).original_ast_node(self.db.upcast()).map(
|InFile { file_id, value }| {
self.cache(find_root(value.syntax()), file_id);
|InRealFile { file_id, value }| {
self.cache(find_root(value.syntax()), file_id.into());
value
},
)
@ -768,8 +770,8 @@ impl<'db> SemanticsImpl<'db> {
pub fn original_syntax_node(&self, node: &SyntaxNode) -> Option<SyntaxNode> {
let InFile { file_id, .. } = self.find_file(node);
InFile::new(file_id, node).original_syntax_node(self.db.upcast()).map(
|InFile { file_id, value }| {
self.cache(find_root(&value), file_id);
|InRealFile { file_id, value }| {
self.cache(find_root(&value), file_id.into());
value
},
)

View file

@ -7,7 +7,7 @@ use hir_def::{
AdtId, AssocItemId, DefWithBodyId, HasModule, ImplId, Lookup, MacroId, ModuleDefId, ModuleId,
TraitId,
};
use hir_expand::{files::ascend_range_up_macros, HirFileId, InFile};
use hir_expand::{HirFileId, InFile};
use hir_ty::db::HirDatabase;
use syntax::{ast::HasName, AstNode, SmolStr, SyntaxNode, SyntaxNodePtr};
@ -51,8 +51,7 @@ impl DeclarationLocation {
}
pub fn original_name_range(&self, db: &dyn HirDatabase) -> FileRange {
let mapping = InFile::new(self.hir_file_id, self.name_ptr.text_range());
ascend_range_up_macros(db.upcast(), mapping).0
InFile::new(self.hir_file_id, self.name_ptr.text_range()).original_file_range(db.upcast())
}
}

View file

@ -1,4 +1,4 @@
use hir::{HasSource, HirDisplay, HirFileIdExt, InFile};
use hir::{HasSource, HirDisplay, InRealFile};
use ide_db::assists::{AssistId, AssistKind};
use syntax::{
ast::{self, make, HasArgList},
@ -114,14 +114,14 @@ fn add_variant_to_accumulator(
parent: PathParent,
) -> Option<()> {
let db = ctx.db();
let InFile { file_id, value: enum_node } = adt.source(db)?.original_ast_node(db)?;
let InRealFile { file_id, value: enum_node } = adt.source(db)?.original_ast_node(db)?;
acc.add(
AssistId("generate_enum_variant", AssistKind::Generate),
"Generate variant",
target,
|builder| {
builder.edit_file(file_id.original_file(db));
builder.edit_file(file_id);
let node = builder.make_mut(enum_node);
let variant = make_variant(ctx, name_ref, parent);
node.variant_list().map(|it| it.add_variant(variant.clone_for_update()));

View file

@ -533,7 +533,7 @@ fn source_edit_from_def(
}
},
};
file_id = source.file_id.file_id();
file_id = Some(source.file_id);
if let Either::Left(pat) = source.value {
let name_range = pat.name().unwrap().syntax().text_range();
// special cases required for renaming fields/locals in Record patterns

View file

@ -1,4 +1,4 @@
use hir::{HasSource, InFile, Semantics};
use hir::{HasSource, InFile, InRealFile, Semantics};
use ide_db::{
base_db::{FileId, FilePosition, FileRange},
defs::Definition,
@ -149,8 +149,8 @@ pub(crate) fn annotations(
node: InFile<T>,
source_file_id: FileId,
) -> Option<(TextRange, Option<TextRange>)> {
if let Some(InFile { file_id, value }) = node.original_ast_node(db) {
if file_id == source_file_id.into() {
if let Some(InRealFile { file_id, value }) = node.original_ast_node(db) {
if file_id == source_file_id {
return Some((
value.syntax().text_range(),
value.name().map(|name| name.syntax().text_range()),

View file

@ -2,7 +2,7 @@ use std::{fmt, marker::PhantomData};
use hir::{
db::{AstIdMapQuery, AttrsQuery, BlockDefMapQuery, ParseMacroExpansionQuery},
Attr, Attrs, ExpandResult, MacroFile, Module,
Attr, Attrs, ExpandResult, MacroFileId, Module,
};
use ide_db::{
base_db::{
@ -199,8 +199,12 @@ impl StatCollect<FileId, Parse<ast::SourceFile>> for SyntaxTreeStats<false> {
}
}
impl<M> StatCollect<MacroFile, ExpandResult<(Parse<SyntaxNode>, M)>> for SyntaxTreeStats<true> {
fn collect_entry(&mut self, _: MacroFile, value: Option<ExpandResult<(Parse<SyntaxNode>, M)>>) {
impl<M> StatCollect<MacroFileId, ExpandResult<(Parse<SyntaxNode>, M)>> for SyntaxTreeStats<true> {
fn collect_entry(
&mut self,
_: MacroFileId,
value: Option<ExpandResult<(Parse<SyntaxNode>, M)>>,
) {
self.total += 1;
self.retained += value.is_some() as usize;
}

View file

@ -88,7 +88,7 @@ pub struct FlatTree {
}
#[derive(Serialize, Deserialize, Debug)]
pub struct SpanMap {
struct SpanMap {
#[serde(skip_serializing)]
serialize: bool,
span_size: u32,
@ -122,7 +122,7 @@ impl SpanMap {
}
impl SpanMap {
pub fn do_serialize(&self) -> bool {
fn do_serialize(&self) -> bool {
self.serialize
}
}