xirang_macro/lib.rs
1//! Face field normalisation for the authoring macros.
2//! 为作者侧宏归一化注册面字段。
3//!
4//! A `macro_rules!` matcher can only fail with "no rules expected `...`", and it
5//! cannot reorder fields, cannot compare field names, and cannot attach a span
6//! to a message of its own. This front end receives the author's tokens with
7//! their spans, so it accepts `,` or `;` separators, a forgotten separator and
8//! any field order, and still reports an unknown or repeated field on the exact
9//! token that carries it.
10//! `macro_rules!` 匹配失败只会说 "no rules expected `...`",既不能重排字段、不能
11//! 比较字段名,也无法把自己的消息挂到具体 token 上。本前端拿到的是带 span 的作者
12//! token,因此接受 `,`/`;`、漏写分隔符与任意顺序,并把"未知字段/重复字段"精确报在
13//! 出问题的那个 token 上。
14//!
15//! Splitting is shared with the build-time reader (`split_face_fields`): the
16//! compiler and the build step must read one declaration the same way, so they
17//! use the same tolerant splitter.
18//! 切分逻辑与构建期读取器共用(`split_face_fields`):编译器与构建步骤必须对同一份
19//! 声明读出一致的字段,因此两者使用同一个宽容切分器。
20//!
21//! The normalised declaration goes back through `__xirang_object!`, the
22//! exported entry point of the runtime crate, so the collector mode the caller
23//! chose survives the round trip. This front end is only reached when
24//! `__control_object!`'s single arm has already declined the declaration — a
25//! field out of order, `;` separators, a misspelled name — so a well-formed face
26//! expands exactly as it did before.
27//! 归一化后的声明经 `__xirang_object!`(运行时 crate 的公开入口)回到宏阶梯,
28//! 调用方选择的 collector 模式因此得以保留。只有当 `__control_object!` 那唯一一条 arm
29//! 不接受时(字段顺序不同、用 `;` 分隔、字段名拼错)才会走到本前端,因此合法注册面的展开
30//! 与从前完全一致。
31//!
32//! The proc-macro entry points plus `normalise` stay on this page; the mirror
33//! emitter lives in `mirror` and the field/argument parsing helpers in
34//! `front_end`.
35//! 过程宏入口与 `normalise` 留在本页;镜像发射器位于 `mirror`,字段 / 参数解析辅助
36//! 函数位于 `front_end`。
37
38// The published surface must be readable on docs.rs without leaving the page,
39// so the lint is on for the whole crate; `clippy -D warnings` makes a new
40// undocumented public item a failure.
41// 发布表面必须能在 docs.rs 上不跳页读懂,因此 lint 开在整个 crate 上;
42// `clippy -D warnings` 会让新增的、没有文档的公开项变成失败。
43#![warn(missing_docs)]
44
45use proc_macro::TokenStream;
46use proc_macro2::{Delimiter, Group, Ident, Spacing, Span, TokenStream as Tokens, TokenTree};
47
48use xirang_kernel::lexicon;
49
50use xirang_kernel::registry_core::declaration::FACE_FIELD_ORDER;
51use xirang_kernel::registry_core::syntax::split_face_fields;
52
53use crate::front_end::{Field, error_at, punct, render, splice, split_semicolons};
54
55#[path = "front_end.rs"]
56mod front_end;
57/// Rewrite one face declaration's field list into its accepted order, with
58/// tolerant separators and spanned diagnostics.
59/// 把一条注册面声明的字段列表改写成它接受的顺序,容忍分隔符差异并给出带 span 的诊断。
60///
61/// The macro is the compile-time front end of the kernel's face grammar: it
62/// parses the same tokens the authoring parser does, so the compiler and the
63/// tooling reject exactly the same declarations.
64/// 本宏是内核注册面语法的编译期前端:它解析与创作解析器相同的 token,因此编译器与工具
65/// 拒绝的是完全相同的声明。
66#[proc_macro]
67pub fn face_fields(input: TokenStream) -> TokenStream {
68 normalise(Tokens::from(input))
69 .unwrap_or_else(|error| error)
70 .into()
71}
72
73/// The `registry_rule` a face gets when it does not write one.
74/// 注册面没有写 `registry_rule` 时得到什么。
75///
76/// The input is `<fallback> ; <needs_registry> ; <author expression?>`. The
77/// author's expression always wins. A face that owns a registry
78/// (`needs_registry: true`) takes the **canonical sibling rule** — the rule
79/// module the authoring layout keeps beside the face folder — and every other
80/// face keeps the permissive fallback the declarative layer passes in.
81/// 输入是 `<fallback> ; <needs_registry> ; <作者表达式?>`。作者写下的表达式永远最优先。
82/// 拥有注册机的面(`needs_registry: true`)取**同目录规范规则**——创作布局放在注册面
83/// 目录旁的那个规则模块——其余注册面保留声明层传进来的宽松默认值。
84///
85/// The path is relative (`super::registry_rule`) on purpose, and that is why this
86/// has to be a proc macro: a folder face file is loaded as the inner module of
87/// its folder, so the rule module is its *sibling*, and `module_path!()` is a
88/// string that cannot become a path. Tokens built here carry `Span::call_site()`,
89/// so the relative path resolves in the author's own module.
90/// 路径是相对的(`super::registry_rule`)而不是绝对的,这也正是它必须是过程宏的原因:
91/// 文件夹注册面文件被载入为其文件夹的内层模块,因此规则模块是它的**兄弟**;而
92/// `module_path!()` 是字符串,无法变成路径。这里生成的 token 带 `Span::call_site()`,
93/// 因此相对路径在作者自己的模块里解析。
94#[proc_macro]
95pub fn face_rule_or(input: TokenStream) -> TokenStream {
96 let mut parts = split_semicolons(Tokens::from(input)).into_iter();
97 let fallback = parts.next().unwrap_or_default();
98 let needs_registry = parts.next().unwrap_or_default();
99 let authored = parts.next().unwrap_or_default();
100 if !authored.is_empty() {
101 return authored.into();
102 }
103 let owns_registry = needs_registry
104 .into_iter()
105 .map(|token| token.to_string())
106 .collect::<String>();
107 if owns_registry == "true" {
108 // The IDE arm this used to carry is gone with the mirror (step ⑤ of A2e): the cfg splice existed
109 // only so an editor's crate-root shadow could still compile a nested face's derived rule path.
110 // `rustc` has always taken the real path, so removing the arm changes nothing it compiles.
111 // 它过去带的 IDE 那一支已随镜像一并退役(A2e 第⑤步):那条 cfg 拼接只为让编辑器看到的 crate 根
112 // 影子仍能编译嵌套面的推导规则路径。`rustc` 一直走真实路径,因此去掉该支不改变它编译的任何东西。
113 // A `let` rather than a `use`: the binding is a struct's associated constant, and `use` cannot
114 // import one. A `let` binding in a const initializer needs no type annotation, which is what keeps
115 // this template free of a type the resolver would have to name.
116 // 用 `let` 而不是 `use`:绑定的是结构体的关联常量,而 `use` 导不进来。const 初始化器里的 `let`
117 // 绑定不需要类型标注,这正是让模板不必说出一个解析器无从命名的类型的原因。
118 let template: Tokens =
119 "{ let __xirang_rule = super::registry_rule::REGISTRATION_RULE; __xirang_rule }"
120 .parse()
121 .expect("the derived rule template is static");
122 return splice(template, "__XIRANG_IDE_FALLBACK", &fallback).into();
123 }
124 fallback.into()
125}
126
127/// Labels for the traits a face declares, derived from the paths it wrote.
128/// 注册面声明实现的 trait 标签,从其写下的路径派生。
129///
130/// `face_trait_labels_or!([path, …]; [label, …])` answers with the last path
131/// segment of every path when at least one path was given, and with the labels
132/// verbatim when none was. That is the same rule the authoring applier
133/// (`apply_trait_label`) already implements, so the file form and the compiled
134/// form cannot answer "which interfaces does this face implement" differently —
135/// and a face that states a compiler-checked path never has to state the label
136/// twice.
137/// `face_trait_labels_or!([路径, …]; [标签, …])`:只要给出至少一个路径,就用每个路径的
138/// 最后一段作答;一个路径都没有时,原样交回标签。这与创作应用器
139/// (`apply_trait_label`)已经实现的规则相同,因此文件形式与编译形式对"本注册面实现了
140/// 哪些接口"不可能给出不同答案——写了参与编译检查的路径的注册面也不必再写一遍标签。
141#[proc_macro]
142pub fn face_trait_labels_or(input: TokenStream) -> TokenStream {
143 let mut parts = split_semicolons(Tokens::from(input)).into_iter();
144 let paths = parts.next().unwrap_or_default();
145 let labels = parts.next().unwrap_or_default();
146 let derived = bracket_items(&paths)
147 .and_then(|items| items.iter().map(last_segment).collect::<Option<Vec<_>>>())
148 .filter(|names| !names.is_empty());
149 let Some(derived) = derived else {
150 // No compiler-checked path: the author's labels stand as written, which
151 // is what `__string_list!` produced before this macro existed.
152 // 没有参与编译检查的路径:作者的标签原样成立,这正是本宏出现之前
153 // `__string_list!` 产出的东西。
154 let fallback = format!("&{labels}");
155 return fallback
156 .parse::<Tokens>()
157 .map_or_else(|_| labels.into(), TokenStream::from);
158 };
159 let literal = format!(
160 "&[{}]",
161 derived
162 .iter()
163 .map(|name| format!("{name:?}"))
164 .collect::<Vec<_>>()
165 .join(", ")
166 );
167 literal
168 .parse::<Tokens>()
169 .map_or_else(|_| labels.into(), TokenStream::from)
170}
171
172/// The comma-separated items of the first bracketed group, if there is one.
173/// 第一个方括号分组里以逗号分隔的条目(若有)。
174fn bracket_items(tokens: &Tokens) -> Option<Vec<Tokens>> {
175 let group = tokens.clone().into_iter().find_map(|token| match token {
176 TokenTree::Group(group) if group.delimiter() == Delimiter::Bracket => Some(group),
177 _ => None,
178 })?;
179 let mut items = vec![Tokens::new()];
180 for token in group.stream() {
181 let separator = matches!(&token, TokenTree::Punct(punct) if punct.as_char() == ',');
182 if separator {
183 items.push(Tokens::new());
184 } else {
185 items.last_mut()?.extend([token]);
186 }
187 }
188 Some(items.into_iter().filter(|item| !item.is_empty()).collect())
189}
190
191/// The last `::`-separated segment of a path, when it is a plain identifier.
192/// 路径最后一段 `::` 之后的名字,且它必须是普通标识符。
193fn last_segment(path: &Tokens) -> Option<String> {
194 let text = path.to_string().replace(' ', "");
195 let name = text.rsplit("::").next()?.to_owned();
196 let mut characters = name.chars();
197 let first = characters.next()?;
198 if !(first.is_alphabetic() || first == '_')
199 || !characters.all(|c| c.is_alphanumeric() || c == '_')
200 {
201 return None;
202 }
203 Some(name)
204}
205
206/// Which macro the normalised declaration goes back to.
207/// 归一化后的声明要回到哪个宏。
208#[derive(Clone, Copy, PartialEq, Eq)]
209enum Target {
210 /// The generated host aliases' path.
211 /// 生成的宿主别名那条路。
212 Control,
213 /// `external_object!`, whose matcher names the source file first.
214 /// `external_object!`——它的 matcher 首要指出源文件。
215 External,
216}
217
218pub(crate) fn normalise(input: Tokens) -> Result<Tokens, Tokens> {
219 let mut list = input.into_iter().collect::<Vec<_>>();
220 let mut target = Target::Control;
221 if let (Some(TokenTree::Punct(at)), Some(TokenTree::Ident(name))) = (list.first(), list.get(1))
222 && at.as_char() == '@'
223 {
224 target = match name.to_string().as_str() {
225 "control" => Target::Control,
226 "external" => Target::External,
227 other => {
228 return Err(error_at(
229 name.span(),
230 format!("unknown face field target `{other}`"),
231 ));
232 }
233 };
234 list.drain(0..2);
235 }
236 let input = list.into_iter().collect::<Tokens>();
237 let original = input.to_string();
238 let mut collector: Option<TokenTree> = None;
239 let mut fields: Vec<Field> = Vec::new();
240 for field in split_face_fields(input) {
241 let tokens = field.into_iter().collect::<Vec<_>>();
242 let Some(TokenTree::Ident(name)) = tokens.first().cloned() else {
243 let span = tokens.first().map_or_else(Span::call_site, TokenTree::span);
244 return Err(error_at(
245 span,
246 format!("expected a face field name, found `{}`", render(&tokens)),
247 ));
248 };
249 match tokens.get(1) {
250 Some(TokenTree::Punct(colon)) if colon.as_char() == ':' => {}
251 _ => {
252 return Err(error_at(
253 name.span(),
254 format!("expected `:` after face field `{name}`"),
255 ));
256 }
257 }
258 if tokens.len() == 2 {
259 return Err(error_at(
260 name.span(),
261 format!("face field `{name}` has no value"),
262 ));
263 }
264 if name == "source" && target == Target::Control {
265 return Err(error_at(
266 name.span(),
267 "`source` belongs to `external_object!`; a generated host alias records \
268 the file itself"
269 .to_owned(),
270 ));
271 }
272 if name == lexicon::FACE_FIELD_COLLECTOR {
273 if collector.is_some() {
274 return Err(error_at(
275 name.span(),
276 "face field `collector` is given twice".to_owned(),
277 ));
278 }
279 collector = Some(tokens[2].clone());
280 continue;
281 }
282 fields.push(Field {
283 key: name.to_string(),
284 span: name.span(),
285 tokens: tokens.into_iter().collect(),
286 });
287 }
288
289 let position = FACE_FIELD_ORDER
290 .iter()
291 .enumerate()
292 .map(|(index, key)| (*key, index))
293 .collect::<std::collections::BTreeMap<_, _>>();
294 let mut seen: Vec<&str> = Vec::with_capacity(fields.len());
295 for field in &fields {
296 if !position.contains_key(field.key.as_str()) {
297 return Err(error_at(
298 field.span,
299 format!(
300 "unknown face field `{}`; expected one of: {}",
301 field.key,
302 FACE_FIELD_ORDER.join(", ")
303 ),
304 ));
305 }
306 if seen.contains(&field.key.as_str()) {
307 return Err(error_at(
308 field.span,
309 format!("face field `{}` is given twice", field.key),
310 ));
311 }
312 seen.push(&field.key);
313 }
314 let Some(collector) = collector else {
315 return Err(error_at(
316 Span::call_site(),
317 "a face declaration must carry `collector:`".to_owned(),
318 ));
319 };
320 fields.sort_by_key(|field| position[field.key.as_str()]);
321
322 let mut body = Tokens::new();
323 body.extend([
324 TokenTree::Ident(Ident::new(lexicon::FACE_FIELD_COLLECTOR, Span::call_site())),
325 punct(':', Spacing::Alone),
326 collector,
327 punct(',', Spacing::Alone),
328 ]);
329 for field in &fields {
330 body.extend(field.tokens.clone());
331 body.extend([punct(',', Spacing::Alone)]);
332 }
333 if target == Target::Control && body.to_string() == original {
334 // Reordering and re-emitting produced this very token stream, so another
335 // round would only recurse: the declaration already is in the accepted
336 // order and still did not match, which means a field's shape is wrong.
337 // 重排与重发得到的正是这串 token,再走一轮只会递归:声明已在接受顺序上却仍未
338 // 匹配,说明某个字段的写法不对。
339 return Err(error_at(
340 Span::call_site(),
341 "these face fields are in the accepted order but the declaration still did not match; \
342 check each field's shape against the field list in the macro's documentation"
343 .to_owned(),
344 ));
345 }
346
347 let mut output = Tokens::new();
348 output.extend([
349 punct(':', Spacing::Joint),
350 punct(':', Spacing::Alone),
351 TokenTree::Ident(Ident::new(lexicon::RUN_METHOD_CRATE, Span::call_site())),
352 punct(':', Spacing::Joint),
353 punct(':', Spacing::Alone),
354 TokenTree::Ident(Ident::new(
355 match target {
356 Target::Control => "__xirang_object",
357 Target::External => "__external_object",
358 },
359 Span::call_site(),
360 )),
361 punct('!', Spacing::Alone),
362 TokenTree::Group(Group::new(Delimiter::Brace, body)),
363 ]);
364 Ok(output)
365}
366
367#[path = "native.rs"]
368mod native;
369
370/// Register a native Rust Soil const without an editor-only mirror.
371/// 注册原生 Rust Soil 常量,不生成编辑器专用镜像。
372#[proc_macro_attribute]
373pub fn soil(args: TokenStream, input: TokenStream) -> TokenStream {
374 let input = Tokens::from(input);
375 match native::expand(args.into(), input.clone()) {
376 Ok(output) => output.into(),
377 Err(error) => {
378 // Keep the real incomplete declaration visible to ordinary Rust completion.
379 // 保留真实的未完成声明,让普通 Rust 补全仍能看到它。
380 let diagnostic = error.to_compile_error();
381 quote::quote!(#input #diagnostic).into()
382 }
383 }
384}
385
386/// Compatibility entry for the original `xirang_macro::face` attribute.
387/// 原 `xirang_macro::face` 属性的兼容入口。
388#[doc(hidden)]
389#[proc_macro_attribute]
390pub fn face(args: TokenStream, input: TokenStream) -> TokenStream {
391 soil(args, input)
392}
393
394/// Check trait implementations and return their registration labels.
395/// 检查 trait 实现并返回注册标签。
396#[proc_macro]
397pub fn contracts(input: TokenStream) -> TokenStream {
398 match xirang_kernel::syntax::contract_paths(input.into()) {
399 Ok((ty, paths)) => {
400 let labels = paths
401 .iter()
402 .map(|p| p.segments.last().unwrap().ident.to_string())
403 .collect::<Vec<_>>();
404 quote::quote!({
405 fn __check<T: #(#paths)+*>() {}
406 let _ = __check::<#ty>;
407 &[#(#labels),*]
408 })
409 .into()
410 }
411 Err(error) => error.to_compile_error().into(),
412 }
413}