Skip to content

Commit 697b165

Browse files
authored
Merge pull request #21400 from Veykril/push-kslvlxlpmwwu
internal: Clean up proc-macro-srv callback trait
2 parents 13d71e0 + 148028b commit 697b165

8 files changed

Lines changed: 58 additions & 61 deletions

File tree

crates/base-db/src/editioned_file_id.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ const _: () = {
2626
krate: Crate,
2727
}
2828

29+
// FIXME: This poses an invalidation problem, if one constructs an `EditionedFileId` with a
30+
// different crate then whatever the input of a memo used, it will invalidate the memo causing
31+
// it to recompute even if the crate is not really used.
2932
/// We like to include the origin crate in an `EditionedFileId` (for use in the item tree),
3033
/// but this poses us a problem.
3134
///

crates/hir-expand/src/db.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ use triomphe::Arc;
99

1010
use crate::{
1111
AstId, BuiltinAttrExpander, BuiltinDeriveExpander, BuiltinFnLikeExpander, EagerCallInfo,
12-
EagerExpander, EditionedFileId, ExpandError, ExpandResult, ExpandTo, HirFileId, MacroCallId,
13-
MacroCallKind, MacroCallLoc, MacroDefId, MacroDefKind,
12+
EagerExpander, EditionedFileId, ExpandError, ExpandResult, ExpandTo, FileRange, HirFileId,
13+
MacroCallId, MacroCallKind, MacroCallLoc, MacroDefId, MacroDefKind,
1414
attrs::Meta,
1515
builtin::pseudo_derive_attr_expansion,
1616
cfg_process::attr_macro_input_to_token_tree,
@@ -61,6 +61,9 @@ pub trait ExpandDatabase: RootQueryDb {
6161
#[salsa::lru(1024)]
6262
fn ast_id_map(&self, file_id: HirFileId) -> Arc<AstIdMap>;
6363

64+
#[salsa::transparent]
65+
fn resolve_span(&self, span: Span) -> FileRange;
66+
6467
#[salsa::transparent]
6568
fn parse_or_expand(&self, file_id: HirFileId) -> SyntaxNode;
6669

@@ -158,6 +161,13 @@ fn syntax_context(db: &dyn ExpandDatabase, file: HirFileId, edition: Edition) ->
158161
}
159162
}
160163

164+
fn resolve_span(db: &dyn ExpandDatabase, Span { range, anchor, ctx: _ }: Span) -> FileRange {
165+
let file_id = EditionedFileId::from_span_guess_origin(db, anchor.file_id);
166+
let anchor_offset =
167+
db.ast_id_map(file_id.into()).get_erased(anchor.ast_id).text_range().start();
168+
FileRange { file_id, range: range + anchor_offset }
169+
}
170+
161171
/// This expands the given macro call, but with different arguments. This is
162172
/// used for completion, where we want to see what 'would happen' if we insert a
163173
/// token. The `token_to_map` mapped down into the expansion, with the mapped

crates/hir-expand/src/lib.rs

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -901,11 +901,8 @@ impl ExpansionInfo {
901901
let span = self.exp_map.span_at(token.start());
902902
match &self.arg_map {
903903
SpanMap::RealSpanMap(_) => {
904-
let file_id =
905-
EditionedFileId::from_span_guess_origin(db, span.anchor.file_id).into();
906-
let anchor_offset =
907-
db.ast_id_map(file_id).get_erased(span.anchor.ast_id).text_range().start();
908-
InFile { file_id, value: smallvec::smallvec![span.range + anchor_offset] }
904+
let range = db.resolve_span(span);
905+
InFile { file_id: range.file_id.into(), value: smallvec::smallvec![range.range] }
909906
}
910907
SpanMap::ExpansionSpanMap(arg_map) => {
911908
let Some(arg_node) = &self.arg.value else {
@@ -947,7 +944,7 @@ pub fn map_node_range_up_rooted(
947944
range: TextRange,
948945
) -> Option<FileRange> {
949946
let mut spans = exp_map.spans_for_range(range).filter(|span| span.ctx.is_root());
950-
let Span { range, anchor, ctx: _ } = spans.next()?;
947+
let Span { range, anchor, ctx } = spans.next()?;
951948
let mut start = range.start();
952949
let mut end = range.end();
953950

@@ -958,10 +955,7 @@ pub fn map_node_range_up_rooted(
958955
start = start.min(span.range.start());
959956
end = end.max(span.range.end());
960957
}
961-
let file_id = EditionedFileId::from_span_guess_origin(db, anchor.file_id);
962-
let anchor_offset =
963-
db.ast_id_map(file_id.into()).get_erased(anchor.ast_id).text_range().start();
964-
Some(FileRange { file_id, range: TextRange::new(start, end) + anchor_offset })
958+
Some(db.resolve_span(Span { range: TextRange::new(start, end), anchor, ctx }))
965959
}
966960

967961
/// Maps up the text range out of the expansion hierarchy back into the original file its from.
@@ -984,10 +978,7 @@ pub fn map_node_range_up(
984978
start = start.min(span.range.start());
985979
end = end.max(span.range.end());
986980
}
987-
let file_id = EditionedFileId::from_span_guess_origin(db, anchor.file_id);
988-
let anchor_offset =
989-
db.ast_id_map(file_id.into()).get_erased(anchor.ast_id).text_range().start();
990-
Some((FileRange { file_id, range: TextRange::new(start, end) + anchor_offset }, ctx))
981+
Some((db.resolve_span(Span { range: TextRange::new(start, end), anchor, ctx }), ctx))
991982
}
992983

993984
/// Looks up the span at the given offset.
@@ -997,10 +988,7 @@ pub fn span_for_offset(
997988
offset: TextSize,
998989
) -> (FileRange, SyntaxContext) {
999990
let span = exp_map.span_at(offset);
1000-
let file_id = EditionedFileId::from_span_guess_origin(db, span.anchor.file_id);
1001-
let anchor_offset =
1002-
db.ast_id_map(file_id.into()).get_erased(span.anchor.ast_id).text_range().start();
1003-
(FileRange { file_id, range: span.range + anchor_offset }, span.ctx)
991+
(db.resolve_span(span), span.ctx)
1004992
}
1005993

1006994
/// In Rust, macros expand token trees to token trees. When we want to turn a

crates/load-cargo/src/lib.rs

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use hir_expand::{
1919
},
2020
};
2121
use ide_db::{
22-
ChangeWithProcMacros, EditionedFileId, FxHashMap, RootDatabase,
22+
ChangeWithProcMacros, FxHashMap, RootDatabase,
2323
base_db::{CrateGraphBuilder, Env, ProcMacroLoadingError, SourceRoot, SourceRootId},
2424
prime_caches,
2525
};
@@ -32,7 +32,8 @@ use proc_macro_api::{
3232
},
3333
};
3434
use project_model::{CargoConfig, PackageRoot, ProjectManifest, ProjectWorkspace};
35-
use span::Span;
35+
use span::{Span, SpanAnchor, SyntaxContext};
36+
use tt::{TextRange, TextSize};
3637
use vfs::{
3738
AbsPath, AbsPathBuf, FileId, VfsPath,
3839
file_set::FileSetConfig,
@@ -553,20 +554,18 @@ impl ProcMacroExpander for Expander {
553554
Ok(SubResponse::LocalFilePathResult { name })
554555
}
555556
SubRequest::SourceText { file_id, ast_id, start, end } => {
556-
let raw_file_id = FileId::from_raw(file_id);
557-
let editioned_file_id = span::EditionedFileId::from_raw(file_id);
558557
let ast_id = span::ErasedFileAstId::from_raw(ast_id);
559-
let hir_file_id = EditionedFileId::from_span_guess_origin(db, editioned_file_id);
560-
let anchor_offset = db
561-
.ast_id_map(hir_expand::HirFileId::FileId(hir_file_id))
562-
.get_erased(ast_id)
563-
.text_range()
564-
.start();
565-
let anchor_offset = u32::from(anchor_offset);
566-
let abs_start = start + anchor_offset;
567-
let abs_end = end + anchor_offset;
568-
let source = db.file_text(raw_file_id).text(db);
569-
let text = source.get(abs_start as usize..abs_end as usize).map(ToOwned::to_owned);
558+
let editioned_file_id = span::EditionedFileId::from_raw(file_id);
559+
let span = Span {
560+
range: TextRange::new(TextSize::from(start), TextSize::from(end)),
561+
anchor: SpanAnchor { file_id: editioned_file_id, ast_id },
562+
ctx: SyntaxContext::root(editioned_file_id.edition()),
563+
};
564+
let range = db.resolve_span(span);
565+
let source = db.file_text(range.file_id.file_id(db)).text(db);
566+
let text = source
567+
.get(usize::from(range.range.start())..usize::from(range.range.end()))
568+
.map(ToOwned::to_owned);
570569

571570
Ok(SubResponse::SourceTextResult { text })
572571
}

crates/proc-macro-srv-cli/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ clap = {version = "4.5.42", default-features = false, features = ["std"]}
1818

1919
[features]
2020
default = []
21+
# default = ["sysroot-abi"]
2122
sysroot-abi = ["proc-macro-srv/sysroot-abi", "proc-macro-api/sysroot-abi"]
2223
in-rust-tree = ["proc-macro-srv/in-rust-tree", "sysroot-abi"]
2324

crates/proc-macro-srv-cli/src/main_loop.rs

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -185,27 +185,35 @@ impl<'a, C: Codec> ProcMacroClientHandle<'a, C> {
185185
}
186186

187187
impl<C: Codec> proc_macro_srv::ProcMacroClientInterface for ProcMacroClientHandle<'_, C> {
188-
fn file(&mut self, file_id: u32) -> String {
189-
match self.roundtrip(bidirectional::SubRequest::FilePath { file_id }) {
188+
fn file(&mut self, file_id: proc_macro_srv::span::FileId) -> String {
189+
match self.roundtrip(bidirectional::SubRequest::FilePath { file_id: file_id.index() }) {
190190
Some(bidirectional::BidirectionalMessage::SubResponse(
191191
bidirectional::SubResponse::FilePathResult { name },
192192
)) => name,
193193
_ => String::new(),
194194
}
195195
}
196196

197-
fn source_text(&mut self, file_id: u32, ast_id: u32, start: u32, end: u32) -> Option<String> {
198-
match self.roundtrip(bidirectional::SubRequest::SourceText { file_id, ast_id, start, end })
199-
{
197+
fn source_text(
198+
&mut self,
199+
proc_macro_srv::span::Span { range, anchor, ctx: _ }: proc_macro_srv::span::Span,
200+
) -> Option<String> {
201+
match self.roundtrip(bidirectional::SubRequest::SourceText {
202+
file_id: anchor.file_id.as_u32(),
203+
ast_id: anchor.ast_id.into_raw(),
204+
start: range.start().into(),
205+
end: range.end().into(),
206+
}) {
200207
Some(bidirectional::BidirectionalMessage::SubResponse(
201208
bidirectional::SubResponse::SourceTextResult { text },
202209
)) => text,
203210
_ => None,
204211
}
205212
}
206213

207-
fn local_file(&mut self, file_id: u32) -> Option<String> {
208-
match self.roundtrip(bidirectional::SubRequest::LocalFilePath { file_id }) {
214+
fn local_file(&mut self, file_id: proc_macro_srv::span::FileId) -> Option<String> {
215+
match self.roundtrip(bidirectional::SubRequest::LocalFilePath { file_id: file_id.index() })
216+
{
209217
Some(bidirectional::BidirectionalMessage::SubResponse(
210218
bidirectional::SubResponse::LocalFilePathResult { name },
211219
)) => name,

crates/proc-macro-srv/src/lib.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ use temp_dir::TempDir;
5353
pub use crate::server_impl::token_id::SpanId;
5454

5555
pub use proc_macro::Delimiter;
56+
pub use span;
5657

5758
pub use crate::bridge::*;
5859
pub use crate::server_impl::literal_from_str;
@@ -94,9 +95,9 @@ impl<'env> ProcMacroSrv<'env> {
9495
pub type ProcMacroClientHandle<'a> = &'a mut (dyn ProcMacroClientInterface + Sync + Send);
9596

9697
pub trait ProcMacroClientInterface {
97-
fn file(&mut self, file_id: u32) -> String;
98-
fn source_text(&mut self, file_id: u32, ast_id: u32, start: u32, end: u32) -> Option<String>;
99-
fn local_file(&mut self, file_id: u32) -> Option<String>;
98+
fn file(&mut self, file_id: span::FileId) -> String;
99+
fn source_text(&mut self, span: Span) -> Option<String>;
100+
fn local_file(&mut self, file_id: span::FileId) -> Option<String>;
100101
}
101102

102103
const EXPANDER_STACK_SIZE: usize = 8 * 1024 * 1024;

crates/proc-macro-srv/src/server_impl/rust_analyzer_span.rs

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -128,13 +128,10 @@ impl server::Span for RaSpanServer<'_> {
128128
format!("{:?}", span)
129129
}
130130
fn file(&mut self, span: Self::Span) -> String {
131-
self.callback
132-
.as_mut()
133-
.map(|cb| cb.file(span.anchor.file_id.file_id().index()))
134-
.unwrap_or_default()
131+
self.callback.as_mut().map(|cb| cb.file(span.anchor.file_id.file_id())).unwrap_or_default()
135132
}
136133
fn local_file(&mut self, span: Self::Span) -> Option<String> {
137-
self.callback.as_mut().and_then(|cb| cb.local_file(span.anchor.file_id.file_id().index()))
134+
self.callback.as_mut().and_then(|cb| cb.local_file(span.anchor.file_id.file_id()))
138135
}
139136
fn save_span(&mut self, _span: Self::Span) -> usize {
140137
// FIXME, quote is incompatible with third-party tools
@@ -153,17 +150,7 @@ impl server::Span for RaSpanServer<'_> {
153150
/// See PR:
154151
/// https://github.com/rust-lang/rust/pull/55780
155152
fn source_text(&mut self, span: Self::Span) -> Option<String> {
156-
let file_id = span.anchor.file_id;
157-
let ast_id = span.anchor.ast_id;
158-
let start: u32 = span.range.start().into();
159-
let end: u32 = span.range.end().into();
160-
161-
self.callback.as_mut()?.source_text(
162-
file_id.file_id().index(),
163-
ast_id.into_raw(),
164-
start,
165-
end,
166-
)
153+
self.callback.as_mut()?.source_text(span)
167154
}
168155

169156
fn parent(&mut self, _span: Self::Span) -> Option<Self::Span> {

0 commit comments

Comments
 (0)