Skip to main content

js2rust_predicate/
chain.rs

1//! 链式访问的编译期检查(供 codegen 复用)。
2//!
3//! 本模块**不碰数据、不做求值**:输入是一条链的段序列加上每段的静态类型,
4//! 输出是 codegen 需要的三样东西——
5//!
6//! 1. **需要判空的段**:据此决定生成 `as_ref()?` 还是裸字段访问;
7//! 2. **与 JS 写法不一致的段**:可空容器上的访问没写 `?.`、非空容器多写了 `?.`、
8//!    变量键打在定型 struct 上……都是编译期就能拦下来的错误;
9//! 3. **这条链该叫什么名字**:确定性、可去重、命名冲突自动消解。
10//!
11//! 规则与《js2rust 定型 struct 链式访问翻译规范》一一对应,错误码沿用文档编号
12//! (`E_NONOPT_ON_OPTIONAL`、`E_DYN_KEY_ON_STRUCT` 等)。
13//!
14//! # 例
15//!
16//! ```text
17//! item.detail?.logistics_company     // detail: Option<Detail>
18//!
19//! Chain {
20//!     base: Base::Item,
21//!     base_ty: SegType::Present,
22//!     segs: [
23//!         Segment::field("detail", SegType::Optional, false),
24//!         Segment::field("logistics_company", SegType::Optional, true),
25//!     ],
26//! }
27//!
28//! plan(&chain).steps == [OptField("detail"), OptField("logistics_company")]
29//! plan(&chain).returns_option == true
30//! plan(&chain).diagnostics == []       // 叶段是 Option 不需要 `?.`
31//! ```
32//!
33//! 注意 `?.` 的归属:`a?.b` 里的 `?.` 记在**被访问的那一段** `b` 上,检查时比对
34//! 的是它的容器(上一段的类型)。
35//!
36//! 同一条链去掉 `?.` 就会得到一条错误(`Option` 字段后面还要下钻却没写可选链):
37//!
38//! ```text
39//! plan(&chain).diagnostics[0].code_str() == "E_NONOPT_ON_OPTIONAL"
40//! ```
41
42use std::collections::BTreeSet;
43use std::fmt;
44
45/// JS 数组下标上界(2^32):达到或超过它就不是数组索引,取值为 `undefined`。
46/// 同时防止 `f64 as usize` 在巨大常量上饱和到 `usize::MAX`。
47const MAX_ARRAY_INDEX: f64 = 4_294_967_296.0;
48
49/// 链的基座。
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
51pub enum Base<'s> {
52    /// `item`(当前行数据)
53    Item,
54    /// `params`
55    Params,
56    /// 局部绑定(`const`/`let`/`var` 的变量,或 `.some` 的回调参数),带上变量名,
57    /// 诊断与 `/// js:` 注释里就能显示 `x.b` 而不是占位符
58    Local(&'s str),
59}
60
61impl<'s> Base<'s> {
62    fn name(self) -> &'s str {
63        match self {
64            Base::Item => "item",
65            Base::Params => "params",
66            Base::Local(name) => name,
67        }
68    }
69}
70
71/// 变量下标的静态类型。
72#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
73pub enum IndexTy {
74    /// 整数型(`i64` 一类),转 `usize` 用 `try_from` 一次拦掉负值与溢出
75    I64,
76    /// 浮点型,必须额外做整性检查(`1.0` 是下标、`1.5` 是 undefined)
77    F64,
78}
79
80impl IndexTy {
81    fn key(self) -> &'static str {
82        match self {
83            IndexTy::I64 => "i64",
84            IndexTy::F64 => "f64",
85        }
86    }
87}
88
89/// 一个链段的形态。
90#[derive(Clone, Copy, Debug, PartialEq)]
91pub enum SegKind<'s> {
92    /// `.name`,或 `["name"]` 这种静态键(调用方在建模时已折叠成同一种)
93    Field(&'s str),
94    /// `[k]`,下标是字面量(已求值,保留浮点以便识别 `1.5` 这种非法下标)
95    ConstIndex(f64),
96    /// `[expr]`,下标是变量
97    VarIndex {
98        /// 变量名,只用于诊断文案与命名
99        name: &'s str,
100        /// 变量的静态类型
101        ty: IndexTy,
102    },
103}
104
105/// 段取到的值的类型。
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub enum SegType<'s> {
108    /// 一定有值(JSDoc 里非可选)
109    Present,
110    /// 可空:数据里可能缺键,或显式 `null`
111    Optional,
112    /// `Object.<string, T>` 字典,`&str` 是元素类型原文(用于检查是否混合类型)
113    Map(&'s str),
114    /// 可空字典 `Object.<string, T>|null`:访问语义同 [`SegType::Map`],
115    /// 但容器可空,后续非可选访问要以 `E_NONOPT_ON_OPTIONAL` 报错。
116    /// 单独成态是因为 `Map` 的可空性不能丢:丢了就等于放过一次真实的 TypeError。
117    OptMap(&'s str),
118    /// 推断不出:按"必有值"处理,且不因可空性报错
119    Unknown,
120}
121
122impl<'s> SegType<'s> {
123    /// 该段是否可能为 null/undefined。
124    pub fn is_nullable(self) -> bool {
125        matches!(self, SegType::Optional | SegType::OptMap(_))
126    }
127
128    /// 若是字典(可空或非空),返回元素类型原文。
129    pub fn map_value(self) -> Option<&'s str> {
130        match self {
131            SegType::Map(v) | SegType::OptMap(v) => Some(v),
132            _ => None,
133        }
134    }
135}
136
137/// 链上的一段。
138#[derive(Clone, Copy, Debug, PartialEq)]
139pub struct Segment<'s> {
140    /// 段的形态
141    pub kind: SegKind<'s>,
142    /// JS 里是否写了 `?.`(静态键也可写成 `?.["...]`,同样记为 true)
143    pub optional: bool,
144    /// 这一段取到的值的类型
145    pub ty: SegType<'s>,
146}
147
148impl<'s> Segment<'s> {
149    /// 字段段。
150    pub fn field(name: &'s str, ty: SegType<'s>, optional: bool) -> Self {
151        Self {
152            kind: SegKind::Field(name),
153            optional,
154            ty,
155        }
156    }
157
158    /// 字面量下标段。
159    pub fn const_index(k: f64, ty: SegType<'s>, optional: bool) -> Self {
160        Self {
161            kind: SegKind::ConstIndex(k),
162            optional,
163            ty,
164        }
165    }
166
167    /// 变量下标段。
168    pub fn var_index(name: &'s str, index_ty: IndexTy, ty: SegType<'s>, optional: bool) -> Self {
169        Self {
170            kind: SegKind::VarIndex { name, ty: index_ty },
171            optional,
172            ty,
173        }
174    }
175}
176
177/// 一条链:基座 + 若干段。
178#[derive(Clone, Copy, Debug, PartialEq)]
179pub struct Chain<'s> {
180    /// 基座
181    pub base: Base<'s>,
182    /// 基座本身的类型(`params` 声明为可选时是 `Optional`)
183    pub base_ty: SegType<'s>,
184    /// 段序列,按 JS 源码顺序
185    pub segs: &'s [Segment<'s>],
186}
187
188impl<'s> Chain<'s> {
189    /// 以 `item` 为基座、不可空的链。
190    pub fn item(segs: &'s [Segment<'s>]) -> Self {
191        Self {
192            base: Base::Item,
193            base_ty: SegType::Present,
194            segs,
195        }
196    }
197
198    /// 以局部绑定为基座(`const`/`let` 变量或 `.some` 的形参)。
199    pub fn local(name: &'s str, nullable: bool, segs: &'s [Segment<'s>]) -> Self {
200        Self {
201            base: Base::Local(name),
202            base_ty: if nullable {
203                SegType::Optional
204            } else {
205                SegType::Present
206            },
207            segs,
208        }
209    }
210
211    /// 以 `params` 为基座,并显式给出它是否可空。
212    pub fn params(nullable: bool, segs: &'s [Segment<'s>]) -> Self {
213        Self {
214            base: Base::Params,
215            base_ty: if nullable {
216                SegType::Optional
217            } else {
218                SegType::Present
219            },
220            segs,
221        }
222    }
223}
224
225/// 诊断级别。
226#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
227pub enum Severity {
228    /// 阻断生成
229    Error,
230    /// 不阻断,但应该清理
231    Warning,
232}
233
234/// 诊断码,与规范文档的编号一致。
235#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
236pub enum Code {
237    /// `Option` 段作基座/中间段,但 JS 没写 `?.`(`E_NONOPT_ON_OPTIONAL`)
238    NonOptOnOptional,
239    /// 变量键打在定型 struct 上(`E_DYN_KEY_ON_STRUCT`)
240    DynamicKeyOnStruct,
241    /// Map 上的数字常量下标无法用十进制 usize 表达(`E_MAP_NONCANON_INDEX`):
242    /// `-1` / `1.5` / 超大值在 JS 里是合法字符串键,但 `Step::Index` 会饱和/取整。
243    MapNonCanonicalIndex,
244    /// `Object.<string, T>` 的 `T` 不唯一(`E_MAP_VALUE_MIXED`)
245    MapValueMixed,
246    /// 链上出现非白名单调用(`E_CHAIN_HAS_CALL`)
247    ChainHasCall,
248    /// 合并模式下出现严格空值判别(`E_NULL_STRICT`)
249    NullStrict,
250    /// 命名消歧到上限仍冲突(`E_NAME_UNRESOLVED`)
251    NameCollisionUnresolved,
252    /// 非空字段却写了 `?.`(`W_REDUNDANT_CHAIN`)
253    RedundantOptionalChain,
254}
255
256impl Code {
257    /// 文档里的错误码字符串。
258    pub fn as_str(self) -> &'static str {
259        match self {
260            Code::NonOptOnOptional => "E_NONOPT_ON_OPTIONAL",
261            Code::DynamicKeyOnStruct => "E_DYN_KEY_ON_STRUCT",
262            Code::MapNonCanonicalIndex => "E_MAP_NONCANON_INDEX",
263            Code::MapValueMixed => "E_MAP_VALUE_MIXED",
264            Code::ChainHasCall => "E_CHAIN_HAS_CALL",
265            Code::NullStrict => "E_NULL_STRICT",
266            Code::NameCollisionUnresolved => "E_NAME_UNRESOLVED",
267            Code::RedundantOptionalChain => "W_REDUNDANT_CHAIN",
268        }
269    }
270
271    /// 级别。
272    pub fn severity(self) -> Severity {
273        match self {
274            Code::RedundantOptionalChain => Severity::Warning,
275            _ => Severity::Error,
276        }
277    }
278}
279
280/// 一条诊断。
281#[derive(Clone, Debug, PartialEq, Eq)]
282pub struct Diagnostic {
283    code: Code,
284    segment: Option<usize>,
285    offset: Option<usize>,
286    message: String,
287    suggestion: Option<String>,
288}
289
290impl Diagnostic {
291    /// 构造一条诊断。
292    pub fn new(code: Code, message: impl Into<String>) -> Self {
293        Self {
294            code,
295            segment: None,
296            offset: None,
297            message: message.into(),
298            suggestion: None,
299        }
300    }
301
302    /// 关联到链上的第几段。
303    #[must_use]
304    pub fn with_segment(mut self, segment: usize) -> Self {
305        self.segment = Some(segment);
306        self
307    }
308
309    /// 关联源码字节偏移(空值判别扫描用)。
310    #[must_use]
311    pub fn with_offset(mut self, offset: usize) -> Self {
312        self.offset = Some(offset);
313        self
314    }
315
316    /// 给出一条可直接贴给上游的整改建议。
317    #[must_use]
318    pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
319        self.suggestion = Some(suggestion.into());
320        self
321    }
322
323    /// 诊断码。
324    pub fn code(&self) -> Code {
325        self.code
326    }
327
328    /// 诊断码字符串。
329    pub fn code_str(&self) -> &'static str {
330        self.code.as_str()
331    }
332
333    /// 级别。
334    pub fn severity(&self) -> Severity {
335        self.code.severity()
336    }
337
338    /// 链上第几段(空值判别的诊断是 `None`)。
339    pub fn segment(&self) -> Option<usize> {
340        self.segment
341    }
342
343    /// 源码字节偏移。
344    pub fn offset(&self) -> Option<usize> {
345        self.offset
346    }
347
348    /// 人读的说明。
349    pub fn message(&self) -> &str {
350        &self.message
351    }
352
353    /// 整改建议。
354    pub fn suggestion(&self) -> Option<&str> {
355        self.suggestion.as_deref()
356    }
357}
358
359impl fmt::Display for Diagnostic {
360    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361        write!(f, "{}: {}", self.code.as_str(), self.message)?;
362        if let Some(s) = &self.suggestion {
363            write!(f, " 建议:{s}")?;
364        }
365        Ok(())
366    }
367}
368
369/// 生成计划里的一步:描述"这一段取到什么类型的值"。
370///
371/// `?` 前缀不在这里表达——它由**上一步**是否为 Option 决定,codegen 顺序渲染时
372/// 记账即可(见 `examples/chain_check.rs`)。
373#[derive(Clone, Copy, Debug, PartialEq, Eq)]
374pub enum Step<'s> {
375    /// 非空字段:`self.name`。容器是 `Map` 时改用 [`Step::MapField`]。
376    Field(&'s str),
377    /// 可空字段:`self.name.as_ref()`,取到 `Option<&T>`
378    OptField(&'s str),
379    /// `Map` 容器上的静态键:`m.get("name")`,恒为 `Option<&T>`。
380    /// `Step::Field` 文档旧称"Map 上退化成 `m.get`"却仍报 `is_option() == false`,
381    /// 与 `Index`/`VarIndex` 的 Option 语义冲突;单独成一步消除歧义。
382    MapField(&'s str),
383    /// 常量下标:`self.arr.get(k)`,取到 `Option<&T>`;
384    /// 容器是 `Map` 时按十进制字符串取键(`m["0"]`),由 codegen 按自身类型表决定
385    Index(usize),
386    /// 变量下标:`self.arr.get(idx)`,取到 `Option<&T>`
387    VarIndex(IndexTy),
388}
389
390impl Step<'_> {
391    /// 这一步取到的值是否为 `Option`(决定下一步要不要加 `?`)。
392    pub fn is_option(&self) -> bool {
393        !matches!(self, Step::Field(_))
394    }
395}
396
397/// 一条链的生成计划。
398#[derive(Clone, Debug, PartialEq)]
399pub struct ChainPlan<'s> {
400    steps: Vec<Step<'s>>,
401    returns_option: bool,
402    constant_undefined: bool,
403    diagnostics: Vec<Diagnostic>,
404}
405
406impl<'s> ChainPlan<'s> {
407    /// 逐步的生成指令,与段序列一一对应(`constant_undefined` 时会截断)。
408    pub fn steps(&self) -> &[Step<'s>] {
409        &self.steps
410    }
411
412    /// 是否应生成 `Option<&T>` 返回类型(链上任一段被判空过)。
413    pub fn returns_option(&self) -> bool {
414        self.returns_option
415    }
416
417    /// 整条链在 JS 里恒为 `undefined`(负下标、非整数常量下标),codegen 可折成 `None`。
418    pub fn is_constant_undefined(&self) -> bool {
419        self.constant_undefined
420    }
421
422    /// 诊断列表(错误与告警混排,按段序)。
423    pub fn diagnostics(&self) -> &[Diagnostic] {
424        &self.diagnostics
425    }
426
427    /// 是否存在阻断级诊断。
428    pub fn has_errors(&self) -> bool {
429        self.diagnostics
430            .iter()
431            .any(|d| d.severity() == Severity::Error)
432    }
433
434    /// 是否存在告警。
435    pub fn has_warnings(&self) -> bool {
436        self.diagnostics
437            .iter()
438            .any(|d| d.severity() == Severity::Warning)
439    }
440}
441
442/// 给一条链出生成计划。
443///
444/// 检查项(对应规范的章节):
445///
446/// - 容器可空(基座可空,或上一段类型是 `Option`)却没写 `?.`(1.5、2.3);
447/// - 叶段是 `Option`:允许,但整条链返回 `Option`(1.5、3.2);
448/// - 非空段写了 `?.`:放行 + 告警(1.5);
449/// - 负下标 / 非整数常量下标:折成常量 `undefined`(4.1);
450/// - 变量键打在定型 struct 上:错误;打在 `Map` 上:放行(4.3);
451/// - `Map` 元素类型混合:错误(4.3);
452/// - 空链(只有基座):`returns_option` 取基座可空性。
453pub fn plan<'s>(chain: &Chain<'s>) -> ChainPlan<'s> {
454    let mut steps = Vec::with_capacity(chain.segs.len());
455    let mut diagnostics = Vec::new();
456    // 空链就是基座本身:基座可空时它同样是 Option
457    let mut returns_option = chain.segs.is_empty() && chain.base_ty.is_nullable();
458    let mut constant_undefined = false;
459
460    for (i, seg) in chain.segs.iter().enumerate() {
461        // 本段要访问的容器:第 0 段是基座,其余是上一段取到的值
462        let container_ty = if i == 0 {
463            chain.base_ty
464        } else {
465            chain.segs[i - 1].ty
466        };
467        // 混合值类型的字典是契约错误,与访问形态无关(字段/常量下标/变量键都要报)。
468        if let Some(value) = container_ty.map_value() {
469            if let Some(d) = mixed_map_value(value) {
470                diagnostics.push(d.with_segment(i));
471            }
472        }
473        let container_nullable = container_ty.is_nullable();
474        // 负数、非整数或超出数组下标上界的常量在**数组**上恒为 undefined(4.1),
475        // 整条链可直接折成常量。但 `Object.<string, T>` 字典的键是字符串:
476        // `obj[-1]` / `obj[1.5]` 查的是 `"-1"` / `"1.5"`,是合法键,不能折掉。
477        let folds_undefined = match seg.kind {
478            SegKind::ConstIndex(k) => {
479                !matches!(container_ty, SegType::Map(_) | SegType::OptMap(_))
480                    && noncanonical_index(k)
481            }
482            _ => false,
483        };
484
485        // 可空性判定要排在折叠之前:折叠只说明"取到 undefined",而 JS 在容器为
486        // null/undefined 时会抛 TypeError——先折叠会把 `item.detail[-1]`(detail
487        // 可空却没写 `?.`)这类真实错误吞掉。
488        if container_nullable && !seg.optional {
489            diagnostics.push(
490                Diagnostic::new(
491                    Code::NonOptOnOptional,
492                    format!(
493                        "`{}` 的容器可空却没写可选链,缺失时会抛 TypeError",
494                        render_path(chain)
495                    ),
496                )
497                .with_segment(i)
498                .with_suggestion(format!("改为 {}", render_path_opt(chain, i))),
499            );
500        }
501        // 折叠掉的访问不会生成指令,`?.` 多余与否没有意义,不再告警
502        if seg.optional
503            && !container_nullable
504            && container_ty != SegType::Unknown
505            && !folds_undefined
506        {
507            diagnostics.push(
508                Diagnostic::new(
509                    Code::RedundantOptionalChain,
510                    format!("`{}` 的容器非空,`?.` 是多余的", render_path(chain)),
511                )
512                .with_segment(i)
513                .with_suggestion("去掉该段的 `?.`"),
514            );
515        }
516
517        if folds_undefined {
518            constant_undefined = true;
519            break;
520        }
521        if let SegKind::ConstIndex(k) = seg.kind {
522            // 数组上的非规范键已在上面的折叠分支里处理,这里只管字典键
523            if matches!(container_ty, SegType::Map(_) | SegType::OptMap(_)) && noncanonical_index(k)
524            {
525                // 非规范数字键必须走字符串形式;`Step::Index(usize)` 表达不了
526                diagnostics.push(
527                    Diagnostic::new(
528                        Code::MapNonCanonicalIndex,
529                        format!("字典上的数字键 `{k}` 不是规范数组下标,请改写成字符串键"),
530                    )
531                    .with_segment(i)
532                    .with_suggestion(format!("把 `[{k}]` 改成 `[\"{k}\"]`")),
533                );
534                // 不能生成 `Step::Index(k as usize)`:`-1 as usize` 会取到 0、
535                // `1e300 as usize` 饱和成 usize::MAX,都是指向另一个键的错误指令。
536                // 这是阻断级诊断,截断 steps 让忽略诊断的调用方也拿不到错误计划。
537                break;
538            }
539        }
540
541        match seg.kind {
542            SegKind::Field(name) => {
543                if container_ty.map_value().is_some() {
544                    // `m.get("name")` 恒为 Option,与同容器上的 ConstIndex/VarIndex 一致
545                    steps.push(Step::MapField(name));
546                    returns_option = true;
547                } else if seg.ty.is_nullable() {
548                    steps.push(Step::OptField(name));
549                } else {
550                    steps.push(Step::Field(name));
551                }
552            }
553            SegKind::ConstIndex(k) => {
554                steps.push(Step::Index(k as usize));
555                returns_option = true;
556            }
557            SegKind::VarIndex { name, ty } => {
558                // 变量键只对 Map 合法(4.3),容器类型取上一段
559                match container_ty {
560                    SegType::Map(_) | SegType::OptMap(_) => {}
561                    SegType::Unknown => {}
562                    _ => diagnostics.push(
563                        Diagnostic::new(
564                            Code::DynamicKeyOnStruct,
565                            format!(
566                                "变量键 `[{name}]` 打在定型 struct 上,只能在 `Object.<string, T>` 上使用"
567                            ),
568                        )
569                        .with_segment(i)
570                        .with_suggestion("补 JSDoc `Object.<string, T>`,或把键改成静态字段名"),
571                    ),
572                }
573                steps.push(Step::VarIndex(ty));
574                returns_option = true;
575            }
576        }
577
578        if container_nullable || seg.ty.is_nullable() {
579            returns_option = true;
580        }
581    }
582
583    ChainPlan {
584        steps,
585        returns_option,
586        constant_undefined,
587        diagnostics,
588    }
589}
590
591/// 常量下标是否落在"不是规范数组下标"的范围。
592///
593/// 数组上这类键恒为 `undefined`(整条链可折叠);字典上它们是合法的字符串键,
594/// 只是 `Step::Index(usize)` 表达不了,必须让调用方改写成字符串形式。
595/// 两处判定共用同一函数,避免"折了却没报 / 报了却没折"的错位。
596fn noncanonical_index(k: f64) -> bool {
597    k.is_nan() || k < 0.0 || k.fract() != 0.0 || k >= MAX_ARRAY_INDEX
598}
599
600/// 把一条链渲染成 JS 风格文本,用于诊断与 `/// js:` 文档注释。
601pub fn render_path(chain: &Chain<'_>) -> String {
602    render_path_inner(chain, None)
603}
604
605/// 同 [`render_path`],但把第 `idx` 段当作可选(整改建议里展示"应该长什么样")。
606fn render_path_opt(chain: &Chain<'_>, idx: usize) -> String {
607    render_path_inner(chain, Some(idx))
608}
609
610fn render_path_inner(chain: &Chain<'_>, force_optional: Option<usize>) -> String {
611    let mut out = escape_doc(chain.base.name());
612    for (i, seg) in chain.segs.iter().enumerate() {
613        let optional = seg.optional || force_optional == Some(i);
614        let dot = if optional { "?." } else { "." };
615        match seg.kind {
616            SegKind::Field(name) => {
617                out.push_str(dot);
618                out.push_str(&escape_doc(name));
619            }
620            SegKind::ConstIndex(k) => {
621                let bracket = if optional { "?.[" } else { "[" };
622                // 直接渲染原始 f64 文本:`k as i64` 对 1e300 会饱和成 i64::MAX,
623                // 诊断里显示的下标与实际键不符。
624                out.push_str(&format!("{bracket}{k}]"));
625            }
626            SegKind::VarIndex { name, .. } => {
627                let bracket = if optional { "?.[" } else { "[" };
628                out.push_str(&format!("{bracket}{}]", escape_doc(name)));
629            }
630        }
631    }
632    out
633}
634
635/// 字段名来自 `Segment::field` / `Segment::var_index` 的公开入参,可能是任意
636/// 字符串(含换行、控制字符)。`js_path` 会被调用方写进生成文件的 `/// js:`
637/// 行注释,不转义就能注入新的代码行。这里统一折成可见转义序列。
638fn escape_doc(s: &str) -> String {
639    let mut out = String::with_capacity(s.len());
640    for c in s.chars() {
641        match c {
642            '\n' => out.push_str("\\n"),
643            '\r' => out.push_str("\\r"),
644            '\t' => out.push_str("\\t"),
645            c if c.is_control() => {
646                use std::fmt::Write;
647                let _ = write!(out, "\\u{{{:x}}}", c as u32);
648            }
649            c => out.push(c),
650        }
651    }
652    out
653}
654
655/// 一条链生成的 accessor 名。
656#[derive(Clone, Debug, PartialEq, Eq)]
657pub struct GeneratedName {
658    /// Rust 函数名
659    pub fn_name: String,
660    /// 对应的 JS 路径(写进 `/// js:` 文档注释)
661    pub js_path: String,
662}
663
664impl GeneratedName {
665    /// Rust 函数名。
666    pub fn fn_name(&self) -> &str {
667        &self.fn_name
668    }
669
670    /// JS 路径。
671    pub fn js_path(&self) -> &str {
672        &self.js_path
673    }
674}
675
676/// 为一批链分配函数名:确定性、相同链去重、冲突自动消解。
677///
678/// 规则(规范 6.3):
679///
680/// 1. 基本名 = 各段名 `_` 连接(字段转 snake_case,常量下标 `i{k}`,变量下标 `at`);
681/// 2. 按"段序列"排序后依次发放,排前面的保留基本名;
682/// 3. 后到者追加 `__2`、`__3`…,最多到 `__6`,仍冲突则报 `E_NAME_UNRESOLVED`;
683/// 4. 命中保留字/派生方法名时先加 `_v` 后缀;
684/// 5. 段序列、可选标记与类型都相同(生成签名一致)的链共享同一个名字。
685///
686/// 输出顺序与输入一致,可安全用于生成 `accessors/<biz>.rs`。
687///
688/// 调用粒度是**一个 owner 类型一批**:不同 struct 上的同名 accessor 落在不同
689/// `impl` 块里,彼此不冲突;把多个类型混在一批会把本可复用的名字消歧成 `__2`。
690pub fn assign_names(chains: &[Chain<'_>]) -> Result<Vec<GeneratedName>, Diagnostic> {
691    let mut order: Vec<(String, usize)> = chains
692        .iter()
693        .enumerate()
694        .map(|(i, c)| (chain_key(c), i))
695        .collect();
696    order.sort();
697
698    let mut names: Vec<String> = vec![String::new(); chains.len()];
699    let mut paths: Vec<String> = vec![String::new(); chains.len()];
700    let mut used: BTreeSet<String> = BTreeSet::new();
701
702    let mut start = 0usize;
703    while start < order.len() {
704        let mut end = start + 1;
705        while end < order.len() && order[end].0 == order[start].0 {
706            end += 1;
707        }
708        let idx = order[start].1;
709        let name = fresh_name(
710            chains.get(idx).ok_or_else(|| {
711                Diagnostic::new(Code::NameCollisionUnresolved, "内部错误:链下标越界")
712            })?,
713            &used,
714        )?;
715        let path = render_path(&chains[idx]);
716        used.insert(name.clone());
717        for &(_, i) in &order[start..end] {
718            names[i] = name.clone();
719            paths[i] = path.clone();
720        }
721        start = end;
722    }
723
724    Ok(names
725        .into_iter()
726        .zip(paths)
727        .map(|(fn_name, js_path)| GeneratedName { fn_name, js_path })
728        .collect())
729}
730
731/// 去重键:基座 + 基座可空性 + 每段的形态、可选标记与类型。
732///
733/// 类型必须进键:`item.a.b` 在 `b: Option<T>` 与 `b: T` 下生成出来的函数
734/// 返回类型不同(`Option<&T>` vs `&T`),不能共用一个名字。
735fn chain_key(chain: &Chain<'_>) -> String {
736    // 基座种类必须进键:`Base::Local("item")` 与 `Base::Item` 的 `name()` 都是 "item",
737    // 但前者是局部绑定、后者是行数据,签名与 js_path 都不同,不能当成同一条链去重。
738    let mut out = String::new();
739    match chain.base {
740        Base::Item => out.push_str("I:"),
741        Base::Params => out.push_str("P:"),
742        Base::Local(name) => {
743            out.push_str("L:");
744            out.push_str(&format!("{}:", name.len()));
745            out.push_str(name);
746            out.push(':');
747        }
748    }
749    out.push_str(if chain.base_ty.is_nullable() {
750        "opt"
751    } else {
752        "req"
753    });
754    // 基座类型进键:`item.a` 在基座为 Map / 普通 struct 时诊断与生成语义不同。
755    push_type_key(&mut out, chain.base_ty);
756    for seg in chain.segs {
757        out.push('|');
758        if seg.optional {
759            out.push('?');
760        }
761        push_type_key(&mut out, seg.ty);
762        match seg.kind {
763            SegKind::Field(name) => {
764                out.push('.');
765                // 长度前缀:字段名可能含 `|` 等分隔符,裸拼接会让两条不同链撞键
766                // (`Field("a|r.b")` 与 `Field("a")+Field("b")` 曾同键)。
767                out.push_str(&format!("{}:", name.len()));
768                out.push_str(name);
769            }
770            SegKind::ConstIndex(k) => {
771                out.push('#');
772                out.push_str(&format!("{k}"));
773            }
774            SegKind::VarIndex { name, ty } => {
775                out.push('$');
776                out.push_str(&format!("{}:", name.len()));
777                out.push_str(name);
778                out.push(':');
779                out.push_str(ty.key());
780            }
781        }
782    }
783    out
784}
785
786/// 类型的紧凑表示(写进去重键):`r` / `o` / `u` / `m(T)` / `M(T)`(可空字典)。
787fn push_type_key(out: &mut String, ty: SegType<'_>) {
788    match ty {
789        SegType::Present => out.push('r'),
790        SegType::Optional => out.push('o'),
791        SegType::Unknown => out.push('u'),
792        SegType::Map(value) => push_map_key(out, 'm', value),
793        SegType::OptMap(value) => push_map_key(out, 'M', value),
794    }
795}
796
797/// 字典键:`m(T)` 非空、`M(T)` 可空,值类型带长度前缀。
798fn push_map_key(out: &mut String, tag: char, value: &str) {
799    out.push(tag);
800    out.push('(');
801    // 值类型名同样要长度前缀:它来自 JSDoc,可含 `)`、`|` 等分隔符,
802    // 裸拼接能注入后面的段键,使两条不同链同键同名。
803    out.push_str(&format!("{}:", value.len()));
804    out.push_str(value);
805    out.push(')');
806}
807
808fn fresh_name(chain: &Chain<'_>, used: &BTreeSet<String>) -> Result<String, Diagnostic> {
809    let mut base = base_name(chain);
810    if reserved(&base) {
811        base.push_str("_v");
812    }
813    if !used.contains(&base) {
814        return Ok(base);
815    }
816    for n in 2..=6u32 {
817        let candidate = format!("{base}__{n}");
818        if !used.contains(&candidate) {
819            return Ok(candidate);
820        }
821    }
822    Err(Diagnostic::new(
823        Code::NameCollisionUnresolved,
824        format!("`{base}` 的命名冲突已消歧到 `__6`,请人工指定函数名"),
825    ))
826}
827
828fn base_name(chain: &Chain<'_>) -> String {
829    if chain.segs.is_empty() {
830        // 空段链也要规范化:`.some(_ => _)` 这类回调形参作基座时,
831        // `_`/`$`/`1bad`/空串都是非法 Rust 标识符(保留字由 fresh_name 加后缀)。
832        let raw = chain.base.name();
833        let mut out = snake(raw);
834        if out.is_empty() || out == "_" || out.as_bytes().first().is_some_and(u8::is_ascii_digit) {
835            out.insert_str(0, "f_");
836        }
837        return out;
838    }
839    let mut out = String::new();
840    for (i, seg) in chain.segs.iter().enumerate() {
841        if i > 0 {
842            out.push('_');
843        }
844        match seg.kind {
845            SegKind::Field(name) => out.push_str(&snake(name)),
846            // 只有真实数组下标才进名字:`1e300 as u64` 会饱和成 u64::MAX,
847            // 与 `[18446744073709551615]` 撞名;超出上界与负数统一记 `i_invalid`
848            // (与 `plan` 折叠成常量 undefined 用同一个判定)。
849            SegKind::ConstIndex(k) if !noncanonical_index(k) => {
850                out.push_str(&format!("i{}", k as u64));
851            }
852            SegKind::ConstIndex(_) => out.push_str("i_invalid"),
853            SegKind::VarIndex { .. } => out.push_str("at"),
854        }
855    }
856    // `_` 在 Rust 2024 是保留标识符(`fn _() {}` 编译失败);单个非 ASCII 字符
857    // 经 `snake` 折成 `_` 同理。统一加前缀。
858    if out.is_empty() || out == "_" || out.as_bytes().first().is_some_and(u8::is_ascii_digit) {
859        out.insert_str(0, "f_");
860    }
861    out
862}
863
864/// camelCase / PascalCase / 全大写缩写 → snake_case;非标识符字符折成 `_`。
865///
866/// 只有「上个字母是小写/数字」或「大写字母后跟小写字母(缩写边界)」才插下划线,
867/// 因此 `fooBAR` → `foo_bar`、`XMLHttpRequest` → `xml_http_request`。
868fn snake(s: &str) -> String {
869    let chars: Vec<char> = s.chars().collect();
870    let mut out = String::with_capacity(s.len() + 4);
871    for (i, &c) in chars.iter().enumerate() {
872        if c.is_ascii_uppercase() {
873            let prev = i.checked_sub(1).map(|j| chars[j]);
874            let next = chars.get(i + 1).copied();
875            let boundary = i > 0
876                && (prev.is_some_and(|p| p.is_ascii_lowercase() || p.is_ascii_digit())
877                    || (prev.is_some_and(|p| p.is_ascii_uppercase())
878                        && next.is_some_and(|n| n.is_ascii_lowercase())));
879            if boundary {
880                out.push('_');
881            }
882            out.push(c.to_ascii_lowercase());
883        } else if c.is_ascii_alphanumeric() || c == '_' {
884            out.push(c);
885        } else {
886            out.push('_');
887        }
888    }
889    out
890}
891
892/// 保留字与派生方法名:命中就加 `_v`,避免与 `Clone::clone` 之类撞上。
893fn reserved(name: &str) -> bool {
894    const RESERVED: &[&str] = &[
895        // Rust 关键字
896        "as",
897        "async",
898        "await",
899        "break",
900        "const",
901        "continue",
902        "crate",
903        "dyn",
904        "else",
905        "enum",
906        "extern",
907        "false",
908        "fn",
909        "for",
910        "if",
911        "impl",
912        "in",
913        "let",
914        "loop",
915        "match",
916        "mod",
917        "move",
918        "mut",
919        "pub",
920        "ref",
921        "return",
922        "self",
923        "static",
924        "struct",
925        "super",
926        "trait",
927        "true",
928        "type",
929        "unsafe",
930        "use",
931        "where",
932        "while",
933        "yield",
934        // 派生 trait 方法
935        "clone",
936        "eq",
937        "ne",
938        "cmp",
939        "partial_cmp",
940        "hash",
941        "fmt",
942        "default",
943        // 常见固有方法名
944        "new",
945        "from",
946        "into",
947        "try_from",
948        "borrow",
949        "deref",
950        "index",
951        "get",
952        "iter",
953        "len",
954        "is_empty",
955        "to_string",
956        "serialize",
957        "deserialize",
958        // Rust 2018/2021 的未来保留字与 edition 2024 新增保留字:
959        // 这些名字不能作为 fn 名,漏掉会让 codegen 生成的代码编译失败
960        "Self",
961        "abstract",
962        "become",
963        "box",
964        "do",
965        "final",
966        "macro",
967        "override",
968        "priv",
969        "typeof",
970        "unsized",
971        "virtual",
972        "try",
973        "gen",
974    ];
975    RESERVED.contains(&name)
976}
977
978/// 白名单方法(规范 2.5)。
979#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
980pub enum WhitelistedMethod {
981    /// `.includes(x)`
982    Includes,
983    /// `.indexOf(x)`
984    IndexOf,
985    /// `.some(x => ...)`
986    Some,
987    /// `.startsWith(x)`
988    StartsWith,
989    /// `.endsWith(x)`
990    EndsWith,
991    /// `.length`(属性,不是调用;这里统一按白名单入口判定)
992    Length,
993}
994
995/// 判定方法调用,不在白名单时直接给出 [`Code::ChainHasCall`] 诊断。
996///
997/// codegen 侧通常只需要 `if let Ok(m) = check_method(name) { ... } else { 报错 }`。
998pub fn check_method(name: &str) -> Result<WhitelistedMethod, Diagnostic> {
999    whitelisted_method(name).ok_or_else(|| {
1000        Diagnostic::new(
1001            Code::ChainHasCall,
1002            format!("方法 `{name}` 不在白名单内,链上只允许纯读取方法"),
1003        )
1004        .with_suggestion(
1005            "改用白名单方法(includes/indexOf/some/startsWith/endsWith),或把这部分移到业务层",
1006        )
1007    })
1008}
1009
1010/// 判定一个方法名是否在白名单内。
1011///
1012/// 不在白名单的方法应当生成 `E_CHAIN_HAS_CALL`,而不是"尽力翻译"——
1013/// 有分配或大小写/本地化语义的方法会同时破坏性能模型与语义模型。
1014pub fn whitelisted_method(name: &str) -> Option<WhitelistedMethod> {
1015    Some(match name {
1016        "includes" => WhitelistedMethod::Includes,
1017        "indexOf" => WhitelistedMethod::IndexOf,
1018        "some" => WhitelistedMethod::Some,
1019        "startsWith" => WhitelistedMethod::StartsWith,
1020        "endsWith" => WhitelistedMethod::EndsWith,
1021        "length" => WhitelistedMethod::Length,
1022        _ => return None,
1023    })
1024}
1025
1026/// `Object.<string, T>` 的解析结果。
1027#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1028pub struct MapType<'s> {
1029    value: &'s str,
1030    nullable: bool,
1031}
1032
1033impl<'s> MapType<'s> {
1034    /// 元素类型原文。
1035    pub fn value(&self) -> &'s str {
1036        self.value
1037    }
1038
1039    /// 字典本身是否可为 `null`(`Object.<string, T>|null`)。
1040    pub fn is_nullable(&self) -> bool {
1041        self.nullable
1042    }
1043
1044    /// 转成链段类型:可空字典给 [`SegType::OptMap`],否则 [`SegType::Map`]。
1045    pub fn seg_type(&self) -> SegType<'s> {
1046        if self.nullable {
1047            SegType::OptMap(self.value)
1048        } else {
1049            SegType::Map(self.value)
1050        }
1051    }
1052}
1053
1054/// 从 JSDoc 类型串里识别字典类型(规范 4.3)。
1055///
1056/// 接受这些写法:
1057///
1058/// - `Object.<string, string>`
1059/// - `Object<string, number>`(无空格、无点)
1060/// - `{[k: string]: Foo}`
1061/// - 上面任意一种再加顶层 `| null` / `| undefined` / `| void`(判为可空字典)
1062///
1063/// 返回:
1064///
1065/// - `Ok(None)`:不是字典(键不是 `string`,不是对象类型,或联合了别的类型);
1066/// - `Ok(Some(..))`:字典,元素类型唯一;
1067/// - `Err(..)`:字典但元素类型混合(`E_MAP_VALUE_MIXED`)。
1068///
1069/// 注意 `Object.<string, string>|null` 这类写法**不能**在剥 `>` 之前做判断:
1070/// 结尾是 `null` 而不是 `>`,`strip_suffix('>')` 会静默失败,把 `string>|null`
1071/// 当成元素类型(可空性丢失、值类型变成垃圾串)。所以先按顶层 `|` 拆联合。
1072pub fn jsdoc_map(jsdoc: &str) -> Result<Option<MapType<'_>>, Diagnostic> {
1073    let (t, nullable) = strip_wrappers_and_union(jsdoc.trim());
1074
1075    let (key, value) = if let Some(rest) = object_generic(t) {
1076        // 联合成员已剥离,这里的结尾必须是 `>`;不是就说明类型串本身残缺,
1077        // 与其猜一个值类型,不如判成"不是字典"。
1078        let Some(rest) = rest.strip_suffix('>') else {
1079            return Ok(None);
1080        };
1081        match split_top_level(rest) {
1082            Some((k, v)) => (k, v),
1083            None => return Ok(None),
1084        }
1085    } else if let Some(rest) = t.strip_prefix('[') {
1086        // `[k: string]: V`
1087        let Some((head, tail)) = rest.split_once(']') else {
1088            return Ok(None);
1089        };
1090        let Some((_, key_ty)) = head.split_once(':') else {
1091            return Ok(None);
1092        };
1093        let tail = tail.strip_prefix(':').map_or("", str::trim);
1094        (key_ty, tail)
1095    } else {
1096        return Ok(None);
1097    };
1098
1099    if !key.trim().eq_ignore_ascii_case("string") {
1100        return Ok(None);
1101    }
1102    let value = peel_parens(value.trim());
1103    if value.is_empty() || !brackets_balanced(value) {
1104        return Ok(None);
1105    }
1106    // `Object.<string, null>` / `undefined` 没有可生成的元素类型,判成"不是字典"
1107    if matches!(
1108        value.to_ascii_lowercase().as_str(),
1109        "null" | "undefined" | "void"
1110    ) {
1111        return Ok(None);
1112    }
1113    // 元素类型自身的顶层 `|`(`Object.<string, A|B>`)是唯一的 T,必须报错;
1114    // 这里不能先拆联合,否则会把 `A|B` 的 `|` 当成"可空"处理。
1115    // 括号会遮蔽这个 `|`(`Object.<string, (A|B)>`),所以先剥括号再判。
1116    if has_top_level_separator(value) {
1117        return Err(mixed(value));
1118    }
1119    Ok(Some(MapType { value, nullable }))
1120}
1121
1122/// 逐层剥掉 `{...}` 包裹与顶层 `| null` / `| undefined` / `| void`。
1123///
1124/// 两种包裹会互相遮挡(`{Object.<string,T>|null}`),所以最多迭代三轮。
1125fn strip_wrappers_and_union(mut t: &str) -> (&str, bool) {
1126    let mut nullable = false;
1127    for _ in 0..3 {
1128        let inner = strip_outer_braces(t);
1129        let stripped = inner != t;
1130        t = inner;
1131        let (ty, nul) = split_nullable_union(t);
1132        let unioned = !std::ptr::eq(ty, t);
1133        if unioned {
1134            nullable |= nul;
1135            t = ty;
1136        }
1137        if !stripped && !unioned {
1138            break;
1139        }
1140    }
1141    (t, nullable)
1142}
1143
1144/// 首尾是成对的 `{}` 或 `()` 时剥一层。
1145///
1146/// JSDoc 里带括号的联合很常见:`{(Object.<string, string>|null)}`。
1147fn strip_outer_braces(s: &str) -> &str {
1148    for (open, close) in [('{', '}'), ('(', ')')] {
1149        if let Some(inner) = s.strip_prefix(open).and_then(|x| x.strip_suffix(close)) {
1150            // `{a} | {b}` 的首 `{` 与尾 `}` 并不配对,剥了会破坏结构
1151            let mut depth = 0i32;
1152            for c in inner.chars() {
1153                if c == open {
1154                    depth += 1;
1155                } else if c == close {
1156                    depth -= 1;
1157                    if depth < 0 {
1158                        return s;
1159                    }
1160                }
1161            }
1162            if depth == 0 {
1163                return inner.trim();
1164            }
1165        }
1166    }
1167    s
1168}
1169
1170/// 顶层 `|` 拆联合:只剩一个非空成员时返回 (该成员, true),否则原样返回。
1171fn split_nullable_union(s: &str) -> (&str, bool) {
1172    let mut depth = 0i32;
1173    let mut start = 0usize;
1174    let mut members: Vec<&str> = Vec::new();
1175    for (i, c) in s.char_indices() {
1176        match c {
1177            '{' | '[' | '(' | '<' => depth += 1,
1178            '}' | ']' | ')' | '>' => depth -= 1,
1179            '|' if depth == 0 => {
1180                members.push(s[start..i].trim());
1181                start = i + 1;
1182            }
1183            _ => {}
1184        }
1185    }
1186    if members.is_empty() {
1187        return (s, false);
1188    }
1189    members.push(s[start..].trim());
1190    let mut non_null = members.iter().copied().filter(|m| {
1191        !matches!(
1192            m.to_ascii_lowercase().as_str(),
1193            "null" | "undefined" | "void"
1194        )
1195    });
1196    let (Some(only), None) = (non_null.next(), non_null.next()) else {
1197        // 多个非空成员(`Object.<string,A>|Object.<string,B>`)不是单一字典
1198        return (s, false);
1199    };
1200    if only.is_empty() {
1201        return (s, false);
1202    }
1203    (only, true)
1204}
1205
1206fn object_generic(s: &str) -> Option<&str> {
1207    ["Object.<", "Object<", "object.<", "object<"]
1208        .iter()
1209        .find_map(|p| s.strip_prefix(p))
1210}
1211
1212/// `<>` 是否成对且不到负深度。
1213fn brackets_balanced(s: &str) -> bool {
1214    let mut depth = 0i32;
1215    for c in s.chars() {
1216        match c {
1217            '<' => depth += 1,
1218            '>' => {
1219                depth -= 1;
1220                if depth < 0 {
1221                    return false;
1222                }
1223            }
1224            _ => {}
1225        }
1226    }
1227    depth == 0
1228}
1229
1230fn mixed(value: &str) -> Diagnostic {
1231    Diagnostic::new(
1232        Code::MapValueMixed,
1233        format!("`Object.<string, {value}>` 的元素类型不唯一,`Map<String, T>` 要求单一 T"),
1234    )
1235    .with_suggestion("拆成两个字段,或把元素类型收窄成具体类型")
1236}
1237
1238/// 剥掉成对的包裹括号(只剥 `()`,`{}` 是对象字面量,不能动)。
1239fn peel_parens(mut s: &str) -> &str {
1240    loop {
1241        let inner = strip_outer_braces(s);
1242        // strip_outer_braces 也可能剥 `{}`;这里只接受剥掉括号的结果
1243        if inner != s && s.starts_with('(') && s.ends_with(')') {
1244            s = inner;
1245        } else {
1246            return s;
1247        }
1248    }
1249}
1250
1251/// 在顶层逗号处切分(尊重 `{}`/`[]`/`()`/`<>` 的嵌套)。
1252fn split_top_level(s: &str) -> Option<(&str, &str)> {
1253    let mut depth = 0i32;
1254    for (i, c) in s.char_indices() {
1255        match c {
1256            '{' | '[' | '(' | '<' => depth += 1,
1257            '}' | ']' | ')' | '>' => depth -= 1,
1258            ',' if depth == 0 => return Some((&s[..i], &s[i + 1..])),
1259            _ => {}
1260        }
1261    }
1262    None
1263}
1264
1265/// 顶层是否有 `|` 或 `,`(混合类型或元组)。
1266fn has_top_level_separator(s: &str) -> bool {
1267    let mut depth = 0i32;
1268    for c in s.chars() {
1269        match c {
1270            '{' | '[' | '(' | '<' => depth += 1,
1271            '}' | ']' | ')' | '>' => depth -= 1,
1272            '|' | ',' if depth == 0 => return true,
1273            _ => {}
1274        }
1275    }
1276    false
1277}
1278
1279/// `Map` 元素类型文本是否混合(供 `plan` 复用)。
1280fn mixed_map_value(value: &str) -> Option<Diagnostic> {
1281    if has_top_level_separator(value) {
1282        Some(mixed(value))
1283    } else {
1284        None
1285    }
1286}
1287
1288#[cfg(test)]
1289mod tests {
1290    use super::*;
1291
1292    fn seg(name: &'static str, ty: SegType<'static>, optional: bool) -> Segment<'static> {
1293        Segment::field(name, ty, optional)
1294    }
1295
1296    #[test]
1297    fn present_chain_needs_no_option() {
1298        let segs = [
1299            seg("status", SegType::Present, false),
1300            seg("status_id", SegType::Present, false),
1301        ];
1302        let c = Chain::item(&segs);
1303        let p = plan(&c);
1304        assert_eq!(
1305            p.steps(),
1306            &[Step::Field("status"), Step::Field("status_id")]
1307        );
1308        assert!(!p.returns_option());
1309        assert!(p.diagnostics().is_empty());
1310    }
1311
1312    #[test]
1313    fn optional_middle_requires_chain_operator() {
1314        let segs = [
1315            seg("detail", SegType::Optional, false),
1316            seg("info", SegType::Present, false),
1317        ];
1318        let p = plan(&Chain::item(&segs));
1319        assert_eq!(p.diagnostics().len(), 1);
1320        assert_eq!(p.diagnostics()[0].code(), Code::NonOptOnOptional);
1321        // `?.` 属于"被访问的那一段",所以错误报在 info 上
1322        assert_eq!(p.diagnostics()[0].segment(), Some(1));
1323        assert!(
1324            p.diagnostics()[0]
1325                .suggestion()
1326                .is_some_and(|s| s.contains("item.detail?.info"))
1327        );
1328    }
1329
1330    #[test]
1331    fn optional_middle_with_operator_is_fine() {
1332        let segs = [
1333            seg("detail", SegType::Optional, false),
1334            seg("info", SegType::Present, true),
1335        ];
1336        let p = plan(&Chain::item(&segs));
1337        assert_eq!(p.steps(), &[Step::OptField("detail"), Step::Field("info")]);
1338        assert!(p.returns_option());
1339        assert!(p.diagnostics().is_empty());
1340    }
1341
1342    #[test]
1343    fn optional_leaf_is_allowed_without_operator() {
1344        let segs = [seg("code", SegType::Optional, false)];
1345        let p = plan(&Chain::item(&segs));
1346        assert!(p.returns_option());
1347        assert!(p.diagnostics().is_empty(), "叶段可空是正常形态");
1348    }
1349
1350    #[test]
1351    fn redundant_operator_is_a_warning() {
1352        let segs = [
1353            seg("status", SegType::Present, false),
1354            seg("status_id", SegType::Present, true),
1355        ];
1356        let p = plan(&Chain::item(&segs));
1357        assert_eq!(p.diagnostics()[0].code(), Code::RedundantOptionalChain);
1358        assert_eq!(p.diagnostics()[0].severity(), Severity::Warning);
1359        assert!(!p.has_errors());
1360    }
1361
1362    #[test]
1363    fn nullable_base_requires_operator_on_first_segment() {
1364        let segs = [seg("code", SegType::Present, false)];
1365        let p = plan(&Chain::params(true, &segs));
1366        assert_eq!(p.diagnostics()[0].code(), Code::NonOptOnOptional);
1367        assert!(
1368            p.diagnostics()[0]
1369                .suggestion()
1370                .is_some_and(|s| s.contains("params?.code"))
1371        );
1372    }
1373
1374    #[test]
1375    fn negative_and_fractional_const_index_fold_to_undefined() {
1376        let neg = [Segment::const_index(-1.0, SegType::Present, true)];
1377        let p = plan(&Chain::item(&neg));
1378        assert!(p.is_constant_undefined());
1379        assert!(p.steps().is_empty());
1380
1381        let frac = [Segment::const_index(1.5, SegType::Present, false)];
1382        assert!(plan(&Chain::item(&frac)).is_constant_undefined());
1383
1384        let ok = [Segment::const_index(3.0, SegType::Present, false)];
1385        let p = plan(&Chain::item(&ok));
1386        assert_eq!(p.steps(), &[Step::Index(3)]);
1387
1388        // 超出 JS 数组下标上界:不能饱和成 usize::MAX
1389        let huge = [Segment::const_index(1e300, SegType::Present, false)];
1390        let p = plan(&Chain::item(&huge));
1391        assert!(p.is_constant_undefined());
1392        assert!(p.steps().is_empty());
1393    }
1394
1395    #[test]
1396    fn map_noncanonical_numeric_key_is_an_error_not_undefined() {
1397        for k in [-1.0, 1.5, 1e300] {
1398            let segs = [
1399                seg("tags", SegType::Map("string"), false),
1400                Segment::const_index(k, SegType::Present, false),
1401            ];
1402            let p = plan(&Chain::item(&segs));
1403            assert!(!p.is_constant_undefined(), "map key {k}");
1404            assert!(p.has_errors(), "map key {k}");
1405            assert_eq!(
1406                p.diagnostics()[0].code(),
1407                Code::MapNonCanonicalIndex,
1408                "map key {k}"
1409            );
1410        }
1411        // 规范数字键仍走 Index
1412        let ok = [
1413            seg("tags", SegType::Map("string"), false),
1414            Segment::const_index(2.0, SegType::Present, false),
1415        ];
1416        let p = plan(&Chain::item(&ok));
1417        assert!(!p.has_errors());
1418        assert_eq!(p.steps()[1], Step::Index(2));
1419    }
1420
1421    #[test]
1422    fn dynamic_key_on_struct_is_error_but_on_map_is_fine() {
1423        let map_segs = [
1424            seg("tags", SegType::Map("string"), false),
1425            Segment::var_index("k", IndexTy::I64, SegType::Present, false),
1426        ];
1427        let p = plan(&Chain::item(&map_segs));
1428        assert!(p.diagnostics().is_empty());
1429        assert_eq!(p.steps()[1], Step::VarIndex(IndexTy::I64));
1430
1431        let struct_segs = [
1432            seg("detail", SegType::Present, false),
1433            Segment::var_index("k", IndexTy::I64, SegType::Present, false),
1434        ];
1435        let p = plan(&Chain::item(&struct_segs));
1436        assert_eq!(p.diagnostics()[0].code(), Code::DynamicKeyOnStruct);
1437    }
1438
1439    #[test]
1440    fn map_value_mixed_is_reported() {
1441        let segs = [
1442            seg("m", SegType::Map("string | number"), false),
1443            Segment::var_index("k", IndexTy::I64, SegType::Present, false),
1444        ];
1445        let p = plan(&Chain::item(&segs));
1446        assert_eq!(p.diagnostics()[0].code(), Code::MapValueMixed);
1447    }
1448
1449    #[test]
1450    fn names_are_deterministic_and_deduped() {
1451        let a1 = [
1452            seg("a", SegType::Present, false),
1453            seg("b", SegType::Present, false),
1454        ];
1455        let a2 = [seg("a_b", SegType::Present, false)];
1456        let dup = [
1457            seg("a", SegType::Present, false),
1458            seg("b", SegType::Present, false),
1459        ];
1460        let chains = [Chain::item(&a1), Chain::item(&a2), Chain::item(&dup)];
1461        let names = assign_names(&chains).unwrap();
1462        // 排序按去重键字典序:段名带长度前缀后,`a.b`(`1:a|1:b`)排在
1463        // `a_b`(`3:a_b`)之前,前者先拿到基本名
1464        assert_eq!(names[0].fn_name(), "a_b");
1465        assert_eq!(names[1].fn_name(), "a_b__2");
1466        // 完全相同的链共享一个函数
1467        assert_eq!(names[2].fn_name(), names[0].fn_name());
1468        assert_eq!(names[0].js_path(), "item.a.b");
1469    }
1470
1471    #[test]
1472    fn reserved_names_get_suffix() {
1473        let segs = [seg("type", SegType::Present, false)];
1474        let names = assign_names(&[Chain::item(&segs)]).unwrap();
1475        assert_eq!(names[0].fn_name(), "type_v");
1476
1477        let clone_segs = [seg("clone", SegType::Present, false)];
1478        let names = assign_names(&[Chain::item(&clone_segs)]).unwrap();
1479        assert_eq!(names[0].fn_name(), "clone_v");
1480    }
1481
1482    #[test]
1483    fn camel_case_becomes_snake() {
1484        for (field, want) in [
1485            ("orderProductName", "order_product_name"),
1486            ("fooBAR", "foo_bar"),
1487            ("XMLHttpRequest", "xml_http_request"),
1488            ("a_b", "a_b"),
1489        ] {
1490            let segs = [seg(field, SegType::Present, false)];
1491            let names = assign_names(&[Chain::item(&segs)]).unwrap();
1492            assert_eq!(names[0].fn_name(), want, "字段 {field}");
1493        }
1494    }
1495
1496    #[test]
1497    fn underscore_and_non_identifier_fields_get_prefix() {
1498        for field in ["_", "$", "α", "€", ""] {
1499            let segs = [seg(field, SegType::Present, false)];
1500            let names = assign_names(&[Chain::item(&segs)]).unwrap();
1501            let name = names[0].fn_name();
1502            assert_ne!(name, "_", "字段 {field}");
1503            // 生成名必须是 Rust 合法标识符:非空、非 `_`、首字符非数字
1504            assert!(
1505                name.starts_with('f') || name.starts_with('_'),
1506                "字段 {field} → {name}"
1507            );
1508            assert!(name.len() > 1, "字段 {field}");
1509        }
1510    }
1511
1512    #[test]
1513    fn distinct_field_names_do_not_share_name_key() {
1514        // `Field("a|r.b")` 与两段 `a` `b` 旧实现撞键,共享函数名
1515        let piped = [seg("a|r.b", SegType::Present, false)];
1516        let two = [
1517            seg("a", SegType::Present, false),
1518            seg("b", SegType::Present, false),
1519        ];
1520        let names = assign_names(&[Chain::item(&piped), Chain::item(&two)]).unwrap();
1521        assert_ne!(names[0].fn_name(), names[1].fn_name());
1522    }
1523
1524    #[test]
1525    fn rust_2024_reserved_names_get_suffix() {
1526        for field in ["gen", "try", "box", "typeof", "do", "macro"] {
1527            let segs = [seg(field, SegType::Present, false)];
1528            let names = assign_names(&[Chain::item(&segs)]).unwrap();
1529            assert_eq!(names[0].fn_name(), format!("{field}_v"), "字段 {field}");
1530        }
1531    }
1532
1533    #[test]
1534    fn var_index_is_named_at() {
1535        let segs = [Segment::var_index(
1536            "i",
1537            IndexTy::I64,
1538            SegType::Present,
1539            false,
1540        )];
1541        let names = assign_names(&[Chain::item(&segs)]).unwrap();
1542        assert_eq!(names[0].fn_name(), "at");
1543        assert_eq!(names[0].js_path(), "item[i]");
1544    }
1545
1546    #[test]
1547    fn nullability_is_part_of_the_name_key() {
1548        // `b` 可空与不可空生成的返回类型不同,不能共用一个名字
1549        let opt = [
1550            seg("a", SegType::Present, false),
1551            seg("b", SegType::Optional, false),
1552        ];
1553        let req = [
1554            seg("a", SegType::Present, false),
1555            seg("b", SegType::Present, false),
1556        ];
1557        let names = assign_names(&[Chain::item(&opt), Chain::item(&req)]).unwrap();
1558        assert_ne!(names[0].fn_name(), names[1].fn_name());
1559
1560        // 段名、可选标记、类型都相同才算同一条链
1561        let dup = [
1562            seg("a", SegType::Present, false),
1563            seg("b", SegType::Optional, false),
1564        ];
1565        let names = assign_names(&[Chain::item(&opt), Chain::item(&dup)]).unwrap();
1566        assert_eq!(names[0].fn_name(), names[1].fn_name());
1567    }
1568
1569    #[test]
1570    fn mixed_bases_never_share_a_name() {
1571        let segs = [seg("a", SegType::Present, false)];
1572        let chains = [
1573            Chain::item(&segs),
1574            Chain::params(true, &segs),
1575            Chain::local("x", false, &segs),
1576        ];
1577        let names = assign_names(&chains).unwrap();
1578        assert_ne!(names[0].fn_name(), names[1].fn_name());
1579        assert_ne!(names[1].fn_name(), names[2].fn_name());
1580        assert_eq!(names[2].js_path(), "x.a");
1581    }
1582
1583    #[test]
1584    fn empty_chain_follows_base_nullability() {
1585        let empty: &[Segment<'_>] = &[];
1586        assert!(!plan(&Chain::item(empty)).returns_option());
1587        assert!(plan(&Chain::params(true, empty)).returns_option());
1588        assert!(plan(&Chain::local("x", true, empty)).returns_option());
1589    }
1590
1591    #[test]
1592    fn method_check_returns_a_diagnostic() {
1593        assert_eq!(check_method("includes"), Ok(WhitelistedMethod::Includes));
1594        let err = check_method("toUpperCase").unwrap_err();
1595        assert_eq!(err.code(), Code::ChainHasCall);
1596        assert_eq!(err.code_str(), "E_CHAIN_HAS_CALL");
1597        assert!(err.suggestion().is_some());
1598    }
1599
1600    #[test]
1601    fn local_base_renders_its_variable_name() {
1602        let segs = [
1603            seg("a", SegType::Optional, false),
1604            seg("b", SegType::Present, false),
1605        ];
1606        let chain = Chain::local("row", false, &segs);
1607        assert_eq!(render_path(&chain), "row.a.b");
1608        assert_eq!(
1609            plan(&chain).diagnostics()[0].suggestion(),
1610            Some("改为 row.a?.b")
1611        );
1612        assert_eq!(assign_names(&[chain]).unwrap()[0].fn_name(), "a_b");
1613    }
1614
1615    #[test]
1616    fn jsdoc_map_forms() {
1617        assert_eq!(
1618            jsdoc_map("Object.<string, string>")
1619                .unwrap()
1620                .map(|m| m.value()),
1621            Some("string")
1622        );
1623        assert_eq!(
1624            jsdoc_map("{Object<string, number>}")
1625                .unwrap()
1626                .map(|m| m.value()),
1627            Some("number")
1628        );
1629        assert_eq!(
1630            jsdoc_map("{[k: string]: Foo}").unwrap().map(|m| m.value()),
1631            Some("Foo")
1632        );
1633        // 键不是 string:不当作字典
1634        assert!(jsdoc_map("Object.<number, string>").unwrap().is_none());
1635        // 元素类型混合:报错
1636        let e = jsdoc_map("Object.<string, string|number>").unwrap_err();
1637        assert_eq!(e.code(), Code::MapValueMixed);
1638        // 嵌套的逗号不算混合
1639        assert_eq!(
1640            jsdoc_map("Object.<string, {a: number, b: string}>")
1641                .unwrap()
1642                .map(|m| m.value()),
1643            Some("{a: number, b: string}")
1644        );
1645    }
1646
1647    #[test]
1648    fn whitelist_entries() {
1649        assert_eq!(
1650            whitelisted_method("includes"),
1651            Some(WhitelistedMethod::Includes)
1652        );
1653        assert_eq!(whitelisted_method("toLowerCase"), None);
1654        // 未知方法调用应报 E_CHAIN_HAS_CALL
1655        assert_eq!(Code::ChainHasCall.as_str(), "E_CHAIN_HAS_CALL");
1656    }
1657
1658    #[test]
1659    fn render_path_marks_optional_segments() {
1660        let segs = [
1661            seg("detail", SegType::Optional, false),
1662            Segment::const_index(0.0, SegType::Present, true),
1663            seg("name", SegType::Present, false),
1664        ];
1665        assert_eq!(render_path(&Chain::item(&segs)), "item.detail?.[0].name");
1666    }
1667
1668    #[test]
1669    fn local_base_collisions_and_invalid_names() {
1670        // Base::Local("item") 与 Base::Item 的 name() 相同,去重键必须区分来源
1671        let segs = [seg("foo", SegType::Present, false)];
1672        let names =
1673            assign_names(&[Chain::item(&segs), Chain::local("item", false, &segs)]).unwrap();
1674        assert_ne!(names[0].fn_name(), names[1].fn_name());
1675
1676        // 空段链的 Local 名也要走标识符规范化(`.some(_ => _)` 的回调形参)
1677        for (raw, want) in [("_", "f__"), ("$", "f__"), ("1bad", "f_1bad"), ("", "f_")] {
1678            let empty = [];
1679            let got = assign_names(&[Chain::local(raw, false, &empty)]).unwrap();
1680            assert_eq!(got[0].fn_name(), want, "local({raw:?})");
1681        }
1682    }
1683
1684    #[test]
1685    fn map_noncanonical_index_truncates_steps() {
1686        // 非规范键只保留诊断,不能生成饱和的 Step::Index
1687        let segs = [
1688            seg("m", SegType::Map("string"), false),
1689            Segment::const_index(1e300, SegType::Present, false),
1690        ];
1691        let p = plan(&Chain::item(&segs));
1692        assert!(p.has_errors());
1693        assert_eq!(p.steps(), &[Step::Field("m")]);
1694    }
1695
1696    #[test]
1697    fn field_on_map_returns_option() {
1698        let segs = [
1699            seg("tags", SegType::Map("string"), false),
1700            seg("foo", SegType::Present, false),
1701        ];
1702        let p = plan(&Chain::item(&segs));
1703        assert_eq!(p.steps()[1], Step::MapField("foo"));
1704        assert!(p.steps()[1].is_option());
1705        assert!(p.returns_option());
1706    }
1707
1708    #[test]
1709    fn folded_index_does_not_hide_optional_type_error() {
1710        // `item.detail[-1]`:detail 可空却没写 `?.`,JS 会抛 TypeError。
1711        // 折叠成常量 undefined 不能把这个错误吞掉,所以可空性判定排在折叠之前。
1712        let segs = [
1713            seg("detail", SegType::Optional, false),
1714            Segment::const_index(-1.0, SegType::Present, false),
1715        ];
1716        let p = plan(&Chain::item(&segs));
1717        assert!(p.is_constant_undefined());
1718        assert!(p.has_errors());
1719        assert_eq!(p.diagnostics()[0].code(), Code::NonOptOnOptional);
1720
1721        // 写了 `?.` 就没有 TypeError,折叠后也不再报"`?.` 多余"
1722        let ok = [
1723            seg("detail", SegType::Optional, false),
1724            Segment::const_index(-1.0, SegType::Present, true),
1725        ];
1726        let p = plan(&Chain::item(&ok));
1727        assert!(p.is_constant_undefined());
1728        assert!(!p.has_warnings());
1729        assert!(p.diagnostics().is_empty());
1730    }
1731
1732    #[test]
1733    fn index_names_use_real_array_bounds() {
1734        // `1e300 as u64` 饱和成 u64::MAX,会与 `[18446744073709551615]` 撞名
1735        let big = [Segment::const_index(1e300, SegType::Present, false)];
1736        let real = [Segment::const_index(
1737            18446744073709551615.0,
1738            SegType::Present,
1739            false,
1740        )];
1741        let names = assign_names(&[Chain::item(&big), Chain::item(&real)]).unwrap();
1742        assert_eq!(names[0].fn_name(), "i_invalid");
1743        assert_eq!(names[1].fn_name(), "i_invalid__2");
1744
1745        let zero = [Segment::const_index(0.0, SegType::Present, false)];
1746        assert_eq!(
1747            assign_names(&[Chain::item(&zero)]).unwrap()[0].fn_name(),
1748            "i0"
1749        );
1750        let top = [Segment::const_index(
1751            MAX_ARRAY_INDEX,
1752            SegType::Present,
1753            false,
1754        )];
1755        assert_eq!(
1756            assign_names(&[Chain::item(&top)]).unwrap()[0].fn_name(),
1757            "i_invalid"
1758        );
1759    }
1760
1761    #[test]
1762    fn map_value_name_cannot_inject_dedup_key() {
1763        // JSDoc 值类型可含 `)`/`|`,裸拼接会让两条不同链撞键、同名
1764        let a_segs = [seg("y)", SegType::Present, false)];
1765        let b_segs: [Segment; 0] = [];
1766        let a = Chain {
1767            base: Base::Item,
1768            base_ty: SegType::Map("x"),
1769            segs: &a_segs,
1770        };
1771        let b = Chain {
1772            base: Base::Item,
1773            base_ty: SegType::Map("x)|r.2:y"),
1774            segs: &b_segs,
1775        };
1776        let names = assign_names(&[a, b]).unwrap();
1777        assert_ne!(names[0].fn_name(), names[1].fn_name());
1778    }
1779
1780    #[test]
1781    fn mixed_map_value_is_diagnosed_for_every_access_shape() {
1782        for segs in [
1783            vec![
1784                seg("m", SegType::Map("string | number"), false),
1785                seg("foo", SegType::Present, false),
1786            ],
1787            vec![
1788                seg("m", SegType::Map("string | number"), false),
1789                Segment::const_index(0.0, SegType::Present, false),
1790            ],
1791            vec![
1792                seg("m", SegType::Map("string | number"), false),
1793                Segment::var_index("k", IndexTy::I64, SegType::Present, false),
1794            ],
1795        ] {
1796            let p = plan(&Chain::item(&segs));
1797            assert!(
1798                p.diagnostics()
1799                    .iter()
1800                    .any(|d| d.code() == Code::MapValueMixed),
1801                "{segs:?}"
1802            );
1803        }
1804    }
1805}