Skip to content

feat: Virtual macro files #19130

New issue

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

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

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 18 additions & 1 deletion crates/hir-def/src/nameres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ use intern::Symbol;
use itertools::Itertools;
use la_arena::Arena;
use rustc_hash::{FxHashMap, FxHashSet};
use span::{Edition, EditionedFileId, FileAstId, FileId, ROOT_ERASED_FILE_AST_ID};
use span::{Edition, EditionedFileId, FileAstId, FileId, MacroFileId, ROOT_ERASED_FILE_AST_ID};
use stdx::format_to;
use syntax::{ast, AstNode, SmolStr, SyntaxNode};
use triomphe::Arc;
Expand Down Expand Up @@ -441,6 +441,23 @@ impl DefMap {
.map(|(id, _data)| id)
}

pub fn inline_modules_for_macro_file(
&self,
file_id: MacroFileId,
) -> impl Iterator<Item = LocalModuleId> + '_ {
self.modules
.iter()
.filter(move |(_id, data)| {
(match data.origin {
ModuleOrigin::Inline { definition_tree_id, .. } => {
definition_tree_id.file_id().macro_file()
}
_ => None,
}) == Some(file_id)
})
.map(|(id, _data)| id)
}

pub fn modules(&self) -> impl Iterator<Item = (LocalModuleId, &ModuleData)> + '_ {
self.modules.iter()
}
Expand Down
53 changes: 48 additions & 5 deletions crates/hir-expand/src/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,51 @@ pub type HirFilePosition = FilePositionWrapper<HirFileId>;
pub type MacroFilePosition = FilePositionWrapper<MacroFileId>;
pub type FilePosition = FilePositionWrapper<EditionedFileId>;

impl From<FilePositionWrapper<EditionedFileId>> for FilePositionWrapper<span::FileId> {
fn from(value: FilePositionWrapper<EditionedFileId>) -> Self {
impl From<FilePosition> for FilePositionWrapper<span::FileId> {
fn from(value: FilePosition) -> Self {
FilePositionWrapper { file_id: value.file_id.into(), offset: value.offset }
}
}

impl From<FileRange> for HirFileRange {
fn from(value: FileRange) -> Self {
HirFileRange { file_id: value.file_id.into(), range: value.range }
}
}

impl From<FilePosition> for HirFilePosition {
fn from(value: FilePosition) -> Self {
HirFilePosition { file_id: value.file_id.into(), offset: value.offset }
}
}

impl FilePositionWrapper<span::FileId> {
pub fn with_edition(self, edition: span::Edition) -> FilePosition {
FilePositionWrapper {
file_id: EditionedFileId::new(self.file_id, edition),
offset: self.offset,
}
}
}

impl FileRangeWrapper<span::FileId> {
pub fn with_edition(self, edition: span::Edition) -> FileRange {
FileRangeWrapper { file_id: EditionedFileId::new(self.file_id, edition), range: self.range }
}
}

impl<T> InFileWrapper<span::FileId, T> {
pub fn with_edition(self, edition: span::Edition) -> InRealFile<T> {
InRealFile { file_id: EditionedFileId::new(self.file_id, edition), value: self.value }
}
}

impl HirFileRange {
pub fn file_range(self) -> Option<FileRange> {
Some(FileRange { file_id: self.file_id.file_id()?, range: self.range })
}
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
pub struct FileRangeWrapper<FileKind> {
pub file_id: FileKind,
Expand Down Expand Up @@ -191,6 +231,9 @@ impl<FileId: Copy, N: AstNode> InFileWrapper<FileId, N> {
pub fn syntax(&self) -> InFileWrapper<FileId, &SyntaxNode> {
self.with_value(self.value.syntax())
}
pub fn node_file_range(&self) -> FileRangeWrapper<FileId> {
FileRangeWrapper { file_id: self.file_id, range: self.value.syntax().text_range() }
}
}

impl<FileId: Copy, N: AstNode> InFileWrapper<FileId, &N> {
Expand All @@ -201,9 +244,9 @@ impl<FileId: Copy, N: AstNode> InFileWrapper<FileId, &N> {
}

// region:specific impls
impl<SN: Borrow<SyntaxNode>> InRealFile<SN> {
pub fn file_range(&self) -> FileRange {
FileRange { file_id: self.file_id, range: self.value.borrow().text_range() }
impl<FileId: Copy, SN: Borrow<SyntaxNode>> InFileWrapper<FileId, SN> {
pub fn file_range(&self) -> FileRangeWrapper<FileId> {
FileRangeWrapper { file_id: self.file_id, range: self.value.borrow().text_range() }
}
}

Expand Down
19 changes: 13 additions & 6 deletions crates/hir-expand/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,7 @@ pub trait HirFileIdExt {

/// If this is a macro call, returns the syntax node of the very first macro call this file resides in.
fn original_call_node(self, db: &dyn ExpandDatabase) -> Option<InRealFile<SyntaxNode>>;
fn call_node(self, db: &dyn ExpandDatabase) -> Option<InFile<SyntaxNode>>;

fn as_builtin_derive_attr_node(&self, db: &dyn ExpandDatabase) -> Option<InFile<ast::Attr>>;
}
Expand Down Expand Up @@ -405,6 +406,10 @@ impl HirFileIdExt for HirFileId {
}
}

fn call_node(self, db: &dyn ExpandDatabase) -> Option<InFile<SyntaxNode>> {
Some(db.lookup_intern_macro_call(self.macro_file()?.macro_call_id).to_node(db))
}

fn as_builtin_derive_attr_node(&self, db: &dyn ExpandDatabase) -> Option<InFile<ast::Attr>> {
let macro_file = self.macro_file()?;
let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
Expand Down Expand Up @@ -873,7 +878,10 @@ impl ExpansionInfo {
map_node_range_up(db, &self.exp_map, range)
}

/// Maps up the text range out of the expansion into is macro call.
/// Maps up the text range out of the expansion into its macro call.
///
/// Note that this may return multiple ranges as we lose the precise association between input to output
/// and as such we may consider inputs that are unrelated.
pub fn map_range_up_once(
&self,
db: &dyn ExpandDatabase,
Expand All @@ -889,11 +897,10 @@ impl ExpansionInfo {
InFile { file_id, value: smallvec::smallvec![span.range + anchor_offset] }
}
SpanMap::ExpansionSpanMap(arg_map) => {
let arg_range = self
.arg
.value
.as_ref()
.map_or_else(|| TextRange::empty(TextSize::from(0)), |it| it.text_range());
let Some(arg_node) = &self.arg.value else {
return InFile::new(self.arg.file_id, smallvec::smallvec![]);
};
let arg_range = arg_node.text_range();
InFile::new(
self.arg.file_id,
arg_map
Expand Down
82 changes: 43 additions & 39 deletions crates/hir-expand/src/prettify_macro_expansion_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,43 +21,47 @@ pub fn prettify_macro_expansion(
let crate_graph = db.crate_graph();
let target_crate = &crate_graph[target_crate_id];
let mut syntax_ctx_id_to_dollar_crate_replacement = FxHashMap::default();
syntax_bridge::prettify_macro_expansion::prettify_macro_expansion(syn, &mut |dollar_crate| {
let ctx = span_map.span_at(dollar_crate.text_range().start() + span_offset).ctx;
let replacement =
syntax_ctx_id_to_dollar_crate_replacement.entry(ctx).or_insert_with(|| {
let ctx_data = db.lookup_intern_syntax_context(ctx);
let macro_call_id =
ctx_data.outer_expn.expect("`$crate` cannot come from `SyntaxContextId::ROOT`");
let macro_call = db.lookup_intern_macro_call(macro_call_id);
let macro_def_crate = macro_call.def.krate;
// First, if this is the same crate as the macro, nothing will work but `crate`.
// If not, if the target trait has the macro's crate as a dependency, using the dependency name
// will work in inserted code and match the user's expectation.
// If not, the crate's display name is what the dependency name is likely to be once such dependency
// is inserted, and also understandable to the user.
// Lastly, if nothing else found, resort to leaving `$crate`.
if target_crate_id == macro_def_crate {
make::tokens::crate_kw()
} else if let Some(dep) =
target_crate.dependencies.iter().find(|dep| dep.crate_id == macro_def_crate)
{
make::tokens::ident(dep.name.as_str())
} else if let Some(crate_name) = &crate_graph[macro_def_crate].display_name {
make::tokens::ident(crate_name.crate_name().as_str())
} else {
return dollar_crate.clone();
}
});
if replacement.text() == "$crate" {
// The parent may have many children, and looking for the token may yield incorrect results.
return dollar_crate.clone();
}
// We need to `clone_subtree()` but rowan doesn't provide such operation for tokens.
let parent = replacement.parent().unwrap().clone_subtree().clone_for_update();
parent
.children_with_tokens()
.filter_map(NodeOrToken::into_token)
.find(|it| it.kind() == replacement.kind())
.unwrap()
})
syntax_bridge::prettify_macro_expansion::prettify_macro_expansion(
syn,
&mut |dollar_crate| {
let ctx = span_map.span_at(dollar_crate.text_range().start() + span_offset).ctx;
let replacement =
syntax_ctx_id_to_dollar_crate_replacement.entry(ctx).or_insert_with(|| {
let ctx_data = db.lookup_intern_syntax_context(ctx);
let macro_call_id = ctx_data
.outer_expn
.expect("`$crate` cannot come from `SyntaxContextId::ROOT`");
let macro_call = db.lookup_intern_macro_call(macro_call_id);
let macro_def_crate = macro_call.def.krate;
// First, if this is the same crate as the macro, nothing will work but `crate`.
// If not, if the target trait has the macro's crate as a dependency, using the dependency name
// will work in inserted code and match the user's expectation.
// If not, the crate's display name is what the dependency name is likely to be once such dependency
// is inserted, and also understandable to the user.
// Lastly, if nothing else found, resort to leaving `$crate`.
if target_crate_id == macro_def_crate {
make::tokens::crate_kw()
} else if let Some(dep) =
target_crate.dependencies.iter().find(|dep| dep.crate_id == macro_def_crate)
{
make::tokens::ident(dep.name.as_str())
} else if let Some(crate_name) = &crate_graph[macro_def_crate].display_name {
make::tokens::ident(crate_name.crate_name().as_str())
} else {
return dollar_crate.clone();
}
});
if replacement.text() == "$crate" {
// The parent may have many children, and looking for the token may yield incorrect results.
return None;
}
// We need to `clone_subtree()` but rowan doesn't provide such operation for tokens.
let parent = replacement.parent().unwrap().clone_subtree().clone_for_update();
parent
.children_with_tokens()
.filter_map(NodeOrToken::into_token)
.find(|it| it.kind() == replacement.kind())
},
|_| (),
)
}
Loading
Loading