Skip to content

Commit 92ae11e

Browse files
committed
remove internal callbacks, and move callback to rust-analyzer level
1 parent 2c71fa8 commit 92ae11e

File tree

8 files changed

+72
-95
lines changed

8 files changed

+72
-95
lines changed

.github/workflows/ci.yaml

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,8 @@ jobs:
7171
- name: Test
7272
run: cargo test --features sysroot-abi -p proc-macro-srv -p proc-macro-srv-cli -p proc-macro-api -- --quiet
7373

74-
# FIXME: This is temporarily disable, more info: https://rust-lang.zulipchat.com/#narrow/channel/185405-t-compiler.2Frust-analyzer/topic/Non-generic.20spans/with/564604549
75-
# - name: Check salsa dependency
76-
# run: "! (cargo tree -p proc-macro-srv-cli | grep -q salsa)"
74+
- name: Check salsa dependency
75+
run: "! (cargo tree -p proc-macro-srv-cli | grep -q salsa)"
7776

7877
rust:
7978
if: github.repository == 'rust-lang/rust-analyzer'

Cargo.lock

Lines changed: 0 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/load-cargo/src/lib.rs

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,17 @@ use ide_db::{
2323
prime_caches,
2424
};
2525
use itertools::Itertools;
26-
use proc_macro_api::{MacroDylib, ProcMacroClient};
26+
use proc_macro_api::{
27+
MacroDylib, ProcMacroClient,
28+
bidirectional_protocol::{
29+
msg::{SubRequest, SubResponse},
30+
reject_subrequests,
31+
},
32+
};
2733
use project_model::{CargoConfig, PackageRoot, ProjectManifest, ProjectWorkspace};
2834
use span::Span;
2935
use vfs::{
30-
AbsPath, AbsPathBuf, VfsPath,
36+
AbsPath, AbsPathBuf, FileId, VfsPath,
3137
file_set::FileSetConfig,
3238
loader::{Handle, LoadingProgress},
3339
};
@@ -427,7 +433,7 @@ pub fn load_proc_macro(
427433
) -> ProcMacroLoadResult {
428434
let res: Result<Vec<_>, _> = (|| {
429435
let dylib = MacroDylib::new(path.to_path_buf());
430-
let vec = server.load_dylib(dylib).map_err(|e| {
436+
let vec = server.load_dylib(dylib, Some(&mut reject_subrequests)).map_err(|e| {
431437
ProcMacroLoadingError::ProcMacroSrvError(format!("{e}").into_boxed_str())
432438
})?;
433439
if vec.is_empty() {
@@ -533,15 +539,23 @@ impl ProcMacroExpander for Expander {
533539
mixed_site: Span,
534540
current_dir: String,
535541
) -> Result<tt::TopSubtree<Span>, ProcMacroExpansionError> {
542+
let mut cb = |req| match req {
543+
SubRequest::SourceText { file_id, start, end } => {
544+
let file = FileId::from_raw(file_id);
545+
let text = db.file_text(file).text(db);
546+
let slice = text.get(start as usize..end as usize).map(ToOwned::to_owned);
547+
Ok(SubResponse::SourceTextResult { text: slice })
548+
}
549+
};
536550
match self.0.expand(
537-
db,
538551
subtree.view(),
539552
attrs.map(|attrs| attrs.view()),
540553
env.clone().into(),
541554
def_site,
542555
call_site,
543556
mixed_site,
544557
current_dir,
558+
Some(&mut cb),
545559
) {
546560
Ok(Ok(subtree)) => Ok(subtree),
547561
Ok(Err(err)) => Err(ProcMacroExpansionError::Panic(err)),

crates/proc-macro-api/Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ serde_json = { workspace = true, features = ["unbounded_depth"] }
1919
tracing.workspace = true
2020
rustc-hash.workspace = true
2121
indexmap.workspace = true
22-
base-db.workspace = true
2322

2423
# local deps
2524
paths = { workspace = true, features = ["serde1"] }

crates/proc-macro-api/src/bidirectional_protocol.rs

Lines changed: 22 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,8 @@ use std::{
55
sync::Arc,
66
};
77

8-
use base_db::SourceDatabase;
98
use paths::AbsPath;
10-
use span::{FileId, Span};
9+
use span::Span;
1110

1211
use crate::{
1312
Codec, ProcMacro, ProcMacroKind, ServerError,
@@ -29,16 +28,14 @@ use crate::{
2928

3029
pub mod msg;
3130

32-
pub trait ClientCallbacks {
33-
fn handle_sub_request(&mut self, req: SubRequest) -> Result<SubResponse, ServerError>;
34-
}
31+
pub type SubCallback<'a> = &'a mut dyn FnMut(SubRequest) -> Result<SubResponse, ServerError>;
3532

3633
pub fn run_conversation<C: Codec>(
3734
writer: &mut dyn Write,
3835
reader: &mut dyn BufRead,
3936
buf: &mut C::Buf,
4037
msg: BidirectionalMessage,
41-
callbacks: &mut dyn ClientCallbacks,
38+
callback: SubCallback<'_>,
4239
) -> Result<BidirectionalMessage, ServerError> {
4340
let encoded = C::encode(&msg).map_err(wrap_encode)?;
4441
C::write(writer, &encoded).map_err(wrap_io("failed to write initial request"))?;
@@ -59,7 +56,7 @@ pub fn run_conversation<C: Codec>(
5956
return Ok(BidirectionalMessage::Response(response));
6057
}
6158
BidirectionalMessage::SubRequest(sr) => {
62-
let resp = callbacks.handle_sub_request(sr)?;
59+
let resp = callback(sr)?;
6360
let reply = BidirectionalMessage::SubResponse(resp);
6461
let encoded = C::encode(&reply).map_err(wrap_encode)?;
6562
C::write(writer, &encoded).map_err(wrap_io("failed to write sub-response"))?;
@@ -86,19 +83,13 @@ fn wrap_decode(err: io::Error) -> ServerError {
8683
ServerError { message: "failed to decode message".into(), io: Some(Arc::new(err)) }
8784
}
8885

89-
pub(crate) fn version_check(srv: &ProcMacroServerProcess) -> Result<u32, ServerError> {
86+
pub(crate) fn version_check(
87+
srv: &ProcMacroServerProcess,
88+
callback: SubCallback<'_>,
89+
) -> Result<u32, ServerError> {
9090
let request = BidirectionalMessage::Request(Request::ApiVersionCheck {});
9191

92-
struct NoCallbacks;
93-
impl ClientCallbacks for NoCallbacks {
94-
fn handle_sub_request(&mut self, _req: SubRequest) -> Result<SubResponse, ServerError> {
95-
Err(ServerError { message: "sub-request not supported here".into(), io: None })
96-
}
97-
}
98-
99-
let mut callbacks = NoCallbacks;
100-
101-
let response_payload = run_request(srv, request, &mut callbacks)?;
92+
let response_payload = run_request(srv, request, callback)?;
10293

10394
match response_payload {
10495
BidirectionalMessage::Response(Response::ApiVersionCheck(version)) => Ok(version),
@@ -111,21 +102,13 @@ pub(crate) fn version_check(srv: &ProcMacroServerProcess) -> Result<u32, ServerE
111102
/// Enable support for rust-analyzer span mode if the server supports it.
112103
pub(crate) fn enable_rust_analyzer_spans(
113104
srv: &ProcMacroServerProcess,
105+
callback: SubCallback<'_>,
114106
) -> Result<SpanMode, ServerError> {
115107
let request = BidirectionalMessage::Request(Request::SetConfig(ServerConfig {
116108
span_mode: SpanMode::RustAnalyzer,
117109
}));
118110

119-
struct NoCallbacks;
120-
impl ClientCallbacks for NoCallbacks {
121-
fn handle_sub_request(&mut self, _req: SubRequest) -> Result<SubResponse, ServerError> {
122-
Err(ServerError { message: "sub-request not supported here".into(), io: None })
123-
}
124-
}
125-
126-
let mut callbacks = NoCallbacks;
127-
128-
let response_payload = run_request(srv, request, &mut callbacks)?;
111+
let response_payload = run_request(srv, request, callback)?;
129112

130113
match response_payload {
131114
BidirectionalMessage::Response(Response::SetConfig(ServerConfig { span_mode })) => {
@@ -139,21 +122,13 @@ pub(crate) fn enable_rust_analyzer_spans(
139122
pub(crate) fn find_proc_macros(
140123
srv: &ProcMacroServerProcess,
141124
dylib_path: &AbsPath,
125+
callback: SubCallback<'_>,
142126
) -> Result<Result<Vec<(String, ProcMacroKind)>, String>, ServerError> {
143127
let request = BidirectionalMessage::Request(Request::ListMacros {
144128
dylib_path: dylib_path.to_path_buf().into(),
145129
});
146130

147-
struct NoCallbacks;
148-
impl ClientCallbacks for NoCallbacks {
149-
fn handle_sub_request(&mut self, _req: SubRequest) -> Result<SubResponse, ServerError> {
150-
Err(ServerError { message: "sub-request not supported here".into(), io: None })
151-
}
152-
}
153-
154-
let mut callbacks = NoCallbacks;
155-
156-
let response_payload = run_request(srv, request, &mut callbacks)?;
131+
let response_payload = run_request(srv, request, callback)?;
157132

158133
match response_payload {
159134
BidirectionalMessage::Response(Response::ListMacros(it)) => Ok(it),
@@ -163,14 +138,14 @@ pub(crate) fn find_proc_macros(
163138

164139
pub(crate) fn expand(
165140
proc_macro: &ProcMacro,
166-
db: &dyn SourceDatabase,
167141
subtree: tt::SubtreeView<'_, Span>,
168142
attr: Option<tt::SubtreeView<'_, Span>>,
169143
env: Vec<(String, String)>,
170144
def_site: Span,
171145
call_site: Span,
172146
mixed_site: Span,
173147
current_dir: String,
148+
callback: SubCallback<'_>,
174149
) -> Result<Result<tt::TopSubtree<span::SpanData<span::SyntaxContext>>, String>, crate::ServerError>
175150
{
176151
let version = proc_macro.process.version();
@@ -201,27 +176,7 @@ pub(crate) fn expand(
201176
current_dir: Some(current_dir),
202177
})));
203178

204-
struct Callbacks<'de> {
205-
db: &'de dyn SourceDatabase,
206-
}
207-
impl<'db> ClientCallbacks for Callbacks<'db> {
208-
fn handle_sub_request(&mut self, req: SubRequest) -> Result<SubResponse, ServerError> {
209-
match req {
210-
SubRequest::SourceText { file_id, start, end } => {
211-
let file = FileId::from_raw(file_id);
212-
let text = self.db.file_text(file).text(self.db);
213-
214-
let slice = text.get(start as usize..end as usize).map(|s| s.to_owned());
215-
216-
Ok(SubResponse::SourceTextResult { text: slice })
217-
}
218-
}
219-
}
220-
}
221-
222-
let mut callbacks = Callbacks { db };
223-
224-
let response_payload = run_request(&proc_macro.process, task, &mut callbacks)?;
179+
let response_payload = run_request(&proc_macro.process, task, callback)?;
225180

226181
match response_payload {
227182
BidirectionalMessage::Response(Response::ExpandMacro(it)) => Ok(it
@@ -253,15 +208,19 @@ pub(crate) fn expand(
253208
fn run_request(
254209
srv: &ProcMacroServerProcess,
255210
msg: BidirectionalMessage,
256-
callbacks: &mut dyn ClientCallbacks,
211+
callback: SubCallback<'_>,
257212
) -> Result<BidirectionalMessage, ServerError> {
258213
if let Some(server_error) = srv.exited() {
259214
return Err(server_error.clone());
260215
}
261216

262217
if srv.use_postcard() {
263-
srv.run_bidirectional::<PostcardProtocol>(msg, callbacks)
218+
srv.run_bidirectional::<PostcardProtocol>(msg, callback)
264219
} else {
265-
srv.run_bidirectional::<JsonProtocol>(msg, callbacks)
220+
srv.run_bidirectional::<JsonProtocol>(msg, callback)
266221
}
267222
}
223+
224+
pub fn reject_subrequests(req: SubRequest) -> Result<SubResponse, ServerError> {
225+
Err(ServerError { message: format!("{req:?} sub-request not supported here"), io: None })
226+
}

crates/proc-macro-api/src/legacy_protocol.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ use std::{
77
sync::Arc,
88
};
99

10-
use base_db::SourceDatabase;
1110
use paths::AbsPath;
1211
use span::Span;
1312

@@ -78,7 +77,6 @@ pub(crate) fn find_proc_macros(
7877

7978
pub(crate) fn expand(
8079
proc_macro: &ProcMacro,
81-
_db: &dyn SourceDatabase,
8280
subtree: tt::SubtreeView<'_, Span>,
8381
attr: Option<tt::SubtreeView<'_, Span>>,
8482
env: Vec<(String, String)>,

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

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,13 @@ pub mod legacy_protocol;
2121
mod process;
2222
pub mod transport;
2323

24-
use base_db::SourceDatabase;
2524
use paths::{AbsPath, AbsPathBuf};
2625
use semver::Version;
2726
use span::{ErasedFileAstId, FIXUP_ERASED_FILE_AST_ID_MARKER, Span};
2827
use std::{fmt, io, sync::Arc, time::SystemTime};
2928

30-
use crate::process::ProcMacroServerProcess;
3129
pub use crate::transport::codec::Codec;
30+
use crate::{bidirectional_protocol::SubCallback, process::ProcMacroServerProcess};
3231

3332
/// The versions of the server protocol
3433
pub mod version {
@@ -143,9 +142,13 @@ impl ProcMacroClient {
143142
}
144143

145144
/// Loads a proc-macro dylib into the server process returning a list of `ProcMacro`s loaded.
146-
pub fn load_dylib(&self, dylib: MacroDylib) -> Result<Vec<ProcMacro>, ServerError> {
145+
pub fn load_dylib(
146+
&self,
147+
dylib: MacroDylib,
148+
callback: Option<SubCallback<'_>>,
149+
) -> Result<Vec<ProcMacro>, ServerError> {
147150
let _p = tracing::info_span!("ProcMacroServer::load_dylib").entered();
148-
let macros = self.process.find_proc_macros(&dylib.path)?;
151+
let macros = self.process.find_proc_macros(&dylib.path, callback)?;
149152

150153
let dylib_path = Arc::new(dylib.path);
151154
let dylib_last_modified = std::fs::metadata(dylib_path.as_path())
@@ -219,14 +222,14 @@ impl ProcMacro {
219222
/// This includes span information and environmental context.
220223
pub fn expand(
221224
&self,
222-
db: &dyn SourceDatabase,
223225
subtree: tt::SubtreeView<'_, Span>,
224226
attr: Option<tt::SubtreeView<'_, Span>>,
225227
env: Vec<(String, String)>,
226228
def_site: Span,
227229
call_site: Span,
228230
mixed_site: Span,
229231
current_dir: String,
232+
callback: Option<SubCallback<'_>>,
230233
) -> Result<Result<tt::TopSubtree<Span>, String>, ServerError> {
231234
let (mut subtree, mut attr) = (subtree, attr);
232235
let (mut subtree_changed, mut attr_changed);
@@ -243,7 +246,6 @@ impl ProcMacro {
243246
}
244247

245248
self.process.expand(
246-
db,
247249
self,
248250
subtree,
249251
attr,
@@ -252,6 +254,7 @@ impl ProcMacro {
252254
call_site,
253255
mixed_site,
254256
current_dir,
257+
callback,
255258
)
256259
}
257260
}

0 commit comments

Comments
 (0)