Skip to content

Commit b29f507

Browse files
committed
doc: add doc to proc-macro-api
1 parent 62dea27 commit b29f507

File tree

4 files changed

+73
-3
lines changed

4 files changed

+73
-3
lines changed

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

+2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Protocol functions for json.
22
use std::io::{self, BufRead, Write};
33

4+
/// Reads a JSON message from the input stream.
45
pub fn read_json<'a>(
56
inp: &mut impl BufRead,
67
buf: &'a mut String,
@@ -26,6 +27,7 @@ pub fn read_json<'a>(
2627
}
2728
}
2829

30+
/// Writes a JSON message to the output stream.
2931
pub fn write_json(out: &mut impl Write, msg: &str) -> io::Result<()> {
3032
tracing::debug!("> {}", msg);
3133
out.write_all(msg.as_bytes())?;

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

+43-1
Original file line numberDiff line numberDiff line change
@@ -20,69 +20,103 @@ pub const VERSION_CHECK_VERSION: u32 = 1;
2020
pub const ENCODE_CLOSE_SPAN_VERSION: u32 = 2;
2121
pub const HAS_GLOBAL_SPANS: u32 = 3;
2222
pub const RUST_ANALYZER_SPAN_SUPPORT: u32 = 4;
23-
/// Whether literals encode their kind as an additional u32 field and idents their rawness as a u32 field
23+
/// Whether literals encode their kind as an additional u32 field and idents their rawness as a u32 field.
2424
pub const EXTENDED_LEAF_DATA: u32 = 5;
2525

26+
/// Current API version of the proc-macro protocol.
2627
pub const CURRENT_API_VERSION: u32 = EXTENDED_LEAF_DATA;
2728

29+
/// Represents requests sent from the client to the proc-macro-srv.
2830
#[derive(Debug, Serialize, Deserialize)]
2931
pub enum Request {
32+
/// Retrieves a list of macros from a given dynamic library.
3033
/// Since [`NO_VERSION_CHECK_VERSION`]
3134
ListMacros { dylib_path: Utf8PathBuf },
35+
36+
/// Expands a procedural macro.
3237
/// Since [`NO_VERSION_CHECK_VERSION`]
3338
ExpandMacro(Box<ExpandMacro>),
39+
40+
/// Performs an API version check between the client and the server.
3441
/// Since [`VERSION_CHECK_VERSION`]
3542
ApiVersionCheck {},
43+
44+
/// Sets server-specific configurations.
3645
/// Since [`RUST_ANALYZER_SPAN_SUPPORT`]
3746
SetConfig(ServerConfig),
3847
}
3948

49+
/// Defines the mode used for handling span data.
4050
#[derive(Copy, Clone, Default, Debug, Serialize, Deserialize)]
4151
pub enum SpanMode {
52+
/// Default mode, where spans are identified by an ID.
4253
#[default]
4354
Id,
55+
56+
/// Rust Analyzer-specific span handling mode.
4457
RustAnalyzer,
4558
}
4659

60+
/// Represents responses sent from the proc-macro-srv to the client.
4761
#[derive(Debug, Serialize, Deserialize)]
4862
pub enum Response {
63+
/// Returns a list of available macros in a dynamic library.
4964
/// Since [`NO_VERSION_CHECK_VERSION`]
5065
ListMacros(Result<Vec<(String, ProcMacroKind)>, String>),
66+
67+
/// Returns result of a macro expansion.
5168
/// Since [`NO_VERSION_CHECK_VERSION`]
5269
ExpandMacro(Result<FlatTree, PanicMessage>),
70+
71+
/// Returns the API version supported by the server.
5372
/// Since [`NO_VERSION_CHECK_VERSION`]
5473
ApiVersionCheck(u32),
74+
75+
/// Confirms the application of a configuration update.
5576
/// Since [`RUST_ANALYZER_SPAN_SUPPORT`]
5677
SetConfig(ServerConfig),
78+
79+
/// Returns the result of a macro expansion, including extended span data.
5780
/// Since [`RUST_ANALYZER_SPAN_SUPPORT`]
5881
ExpandMacroExtended(Result<ExpandMacroExtended, PanicMessage>),
5982
}
6083

84+
/// Configuration settings for the proc-macro-srv.
6185
#[derive(Debug, Serialize, Deserialize, Default)]
6286
#[serde(default)]
6387
pub struct ServerConfig {
88+
/// Defines how span data should be handled.
6489
pub span_mode: SpanMode,
6590
}
6691

92+
/// Represents an extended macro expansion response, including span data mappings.
6793
#[derive(Debug, Serialize, Deserialize)]
6894
pub struct ExpandMacroExtended {
95+
/// The expanded syntax tree.
6996
pub tree: FlatTree,
97+
/// Additional span data mappings.
7098
pub span_data_table: Vec<u32>,
7199
}
72100

101+
/// Represents an error message when a macro expansion results in a panic.
73102
#[derive(Debug, Serialize, Deserialize)]
74103
pub struct PanicMessage(pub String);
75104

105+
/// Represents a macro expansion request sent from the client.
76106
#[derive(Debug, Serialize, Deserialize)]
77107
pub struct ExpandMacro {
108+
/// The path to the dynamic library containing the macro.
78109
pub lib: Utf8PathBuf,
79110
/// Environment variables to set during macro expansion.
80111
pub env: Vec<(String, String)>,
112+
/// The current working directory for the macro expansion.
81113
pub current_dir: Option<String>,
114+
/// Macro expansion data, including the macro body, name and attributes.
82115
#[serde(flatten)]
83116
pub data: ExpandMacroData,
84117
}
85118

119+
/// Represents the input data required for expanding a macro.
86120
#[derive(Debug, Serialize, Deserialize)]
87121
pub struct ExpandMacroData {
88122
/// Argument of macro call.
@@ -103,18 +137,24 @@ pub struct ExpandMacroData {
103137
#[serde(skip_serializing_if = "ExpnGlobals::skip_serializing_if")]
104138
#[serde(default)]
105139
pub has_global_spans: ExpnGlobals,
140+
/// Table of additional span data.
106141
#[serde(skip_serializing_if = "Vec::is_empty")]
107142
#[serde(default)]
108143
pub span_data_table: Vec<u32>,
109144
}
110145

146+
/// Represents global expansion settings, including span resolution.
111147
#[derive(Copy, Clone, Default, Debug, Serialize, Deserialize)]
112148
pub struct ExpnGlobals {
149+
/// Determines whether to serialize the expansion settings.
113150
#[serde(skip_serializing)]
114151
#[serde(default)]
115152
pub serialize: bool,
153+
/// Defines the `def_site` span location.
116154
pub def_site: usize,
155+
/// Defines the `call_site` span location.
117156
pub call_site: usize,
157+
/// Defines the `mixed_site` span location.
118158
pub mixed_site: usize,
119159
}
120160

@@ -150,9 +190,11 @@ pub trait Message: serde::Serialize + DeserializeOwned {
150190
impl Message for Request {}
151191
impl Message for Response {}
152192

193+
/// Type alias for a function that reads protocol messages from a buffered input stream.
153194
#[allow(type_alias_bounds)]
154195
type ProtocolRead<R: BufRead> =
155196
for<'i, 'buf> fn(inp: &'i mut R, buf: &'buf mut String) -> io::Result<Option<&'buf String>>;
197+
/// Type alias for a function that writes protocol messages to an output stream.
156198
#[allow(type_alias_bounds)]
157199
type ProtocolWrite<W: Write> = for<'o, 'msg> fn(out: &'o mut W, msg: &'msg str) -> io::Result<()>;
158200

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

+12
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,12 @@ use crate::{
2424
process::ProcMacroServerProcess,
2525
};
2626

27+
/// Represents different kinds of procedural macros that can be expanded by the external server.
2728
#[derive(Copy, Clone, Eq, PartialEq, Debug, serde_derive::Serialize, serde_derive::Deserialize)]
2829
pub enum ProcMacroKind {
30+
/// A macro that derives implementations for a struct or enum.
2931
CustomDerive,
32+
/// An attribute-like procedural macro.
3033
Attr,
3134
// This used to be called FuncLike, so that's what the server expects currently.
3235
#[serde(alias = "Bang")]
@@ -46,11 +49,13 @@ pub struct ProcMacroClient {
4649
path: AbsPathBuf,
4750
}
4851

52+
/// Represents a dynamically loaded library containing procedural macros.
4953
pub struct MacroDylib {
5054
path: AbsPathBuf,
5155
}
5256

5357
impl MacroDylib {
58+
/// Creates a new MacroDylib instance with the given path.
5459
pub fn new(path: AbsPathBuf) -> MacroDylib {
5560
MacroDylib { path }
5661
}
@@ -78,6 +83,7 @@ impl PartialEq for ProcMacro {
7883
}
7984
}
8085

86+
/// Represents errors encountered when communicating with the proc-macro server.
8187
#[derive(Clone, Debug)]
8288
pub struct ServerError {
8389
pub message: String,
@@ -106,6 +112,7 @@ impl ProcMacroClient {
106112
Ok(ProcMacroClient { process: Arc::new(process), path: process_path.to_owned() })
107113
}
108114

115+
/// Returns the absolute path to the proc-macro server.
109116
pub fn server_path(&self) -> &AbsPath {
110117
&self.path
111118
}
@@ -130,20 +137,25 @@ impl ProcMacroClient {
130137
}
131138
}
132139

140+
/// Checks if the proc-macro server has exited.
133141
pub fn exited(&self) -> Option<&ServerError> {
134142
self.process.exited()
135143
}
136144
}
137145

138146
impl ProcMacro {
147+
/// Returns the name of the procedural macro.
139148
pub fn name(&self) -> &str {
140149
&self.name
141150
}
142151

152+
/// Returns the type of procedural macro.
143153
pub fn kind(&self) -> ProcMacroKind {
144154
self.kind
145155
}
146156

157+
/// Expands the procedural macro by sending an expansion request to the server.
158+
/// This includes span information and environmental context.
147159
pub fn expand(
148160
&self,
149161
subtree: tt::SubtreeView<'_, Span>,

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

+16-2
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use crate::{
2121
ProcMacroKind, ServerError,
2222
};
2323

24+
/// Represents a process handling proc-macro communication.
2425
#[derive(Debug)]
2526
pub(crate) struct ProcMacroServerProcess {
2627
/// The state of the proc-macro server process, the protocol is currently strictly sequential
@@ -32,6 +33,7 @@ pub(crate) struct ProcMacroServerProcess {
3233
exited: OnceLock<AssertUnwindSafe<ServerError>>,
3334
}
3435

36+
/// Maintains the state of the proc-macro server process.
3537
#[derive(Debug)]
3638
struct ProcessSrvState {
3739
process: Process,
@@ -40,6 +42,7 @@ struct ProcessSrvState {
4042
}
4143

4244
impl ProcMacroServerProcess {
45+
/// Starts the proc-macro server and performs a version check
4346
pub(crate) fn run(
4447
process_path: &AbsPath,
4548
env: impl IntoIterator<Item = (impl AsRef<std::ffi::OsStr>, impl AsRef<std::ffi::OsStr>)>
@@ -85,14 +88,17 @@ impl ProcMacroServerProcess {
8588
}
8689
}
8790

91+
/// Returns the server error if the process has exited.
8892
pub(crate) fn exited(&self) -> Option<&ServerError> {
8993
self.exited.get().map(|it| &it.0)
9094
}
9195

96+
/// Retrieves the API version of the proc-macro server.
9297
pub(crate) fn version(&self) -> u32 {
9398
self.version
9499
}
95100

101+
/// Checks the API version of the running proc-macro server.
96102
fn version_check(&self) -> Result<u32, ServerError> {
97103
let request = Request::ApiVersionCheck {};
98104
let response = self.send_task(request)?;
@@ -103,6 +109,7 @@ impl ProcMacroServerProcess {
103109
}
104110
}
105111

112+
/// Enable support for rust-analyzer span mode if the server supports it.
106113
fn enable_rust_analyzer_spans(&self) -> Result<SpanMode, ServerError> {
107114
let request = Request::SetConfig(ServerConfig { span_mode: SpanMode::RustAnalyzer });
108115
let response = self.send_task(request)?;
@@ -113,6 +120,7 @@ impl ProcMacroServerProcess {
113120
}
114121
}
115122

123+
/// Finds proc-macros in a given dynamic library.
116124
pub(crate) fn find_proc_macros(
117125
&self,
118126
dylib_path: &AbsPath,
@@ -127,9 +135,10 @@ impl ProcMacroServerProcess {
127135
}
128136
}
129137

138+
/// Sends a request to the proc-macro server and waits for a response.
130139
pub(crate) fn send_task(&self, req: Request) -> Result<Response, ServerError> {
131-
if let Some(server_error) = self.exited.get() {
132-
return Err(server_error.0.clone());
140+
if let Some(server_error) = self.exited() {
141+
return Err(server_error.clone());
133142
}
134143

135144
let state = &mut *self.state.lock().unwrap();
@@ -177,12 +186,14 @@ impl ProcMacroServerProcess {
177186
}
178187
}
179188

189+
/// Manages the execution of the proc-macro server process.
180190
#[derive(Debug)]
181191
struct Process {
182192
child: JodChild,
183193
}
184194

185195
impl Process {
196+
/// Runs a new proc-macro server process with the specified environment variables.
186197
fn run(
187198
path: &AbsPath,
188199
env: impl IntoIterator<Item = (impl AsRef<std::ffi::OsStr>, impl AsRef<std::ffi::OsStr>)>,
@@ -191,6 +202,7 @@ impl Process {
191202
Ok(Process { child })
192203
}
193204

205+
/// Retrieves stdin and stdout handles for the process.
194206
fn stdio(&mut self) -> Option<(ChildStdin, BufReader<ChildStdout>)> {
195207
let stdin = self.child.stdin.take()?;
196208
let stdout = self.child.stdout.take()?;
@@ -200,6 +212,7 @@ impl Process {
200212
}
201213
}
202214

215+
/// Creates and configures a new child process for the proc-macro server.
203216
fn mk_child(
204217
path: &AbsPath,
205218
env: impl IntoIterator<Item = (impl AsRef<std::ffi::OsStr>, impl AsRef<std::ffi::OsStr>)>,
@@ -221,6 +234,7 @@ fn mk_child(
221234
cmd.spawn()
222235
}
223236

237+
/// Sends a request to the server and reads the response.
224238
fn send_request(
225239
mut writer: &mut impl Write,
226240
mut reader: &mut impl BufRead,

0 commit comments

Comments
 (0)