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 = String::from(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(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}{name}]"));
629            }
630        }
631    }
632    out
633}
634
635/// 一条链生成的 accessor 名。
636#[derive(Clone, Debug, PartialEq, Eq)]
637pub struct GeneratedName {
638    /// Rust 函数名
639    pub fn_name: String,
640    /// 对应的 JS 路径(写进 `/// js:` 文档注释)
641    pub js_path: String,
642}
643
644impl GeneratedName {
645    /// Rust 函数名。
646    pub fn fn_name(&self) -> &str {
647        &self.fn_name
648    }
649
650    /// JS 路径。
651    pub fn js_path(&self) -> &str {
652        &self.js_path
653    }
654}
655
656/// 为一批链分配函数名:确定性、相同链去重、冲突自动消解。
657///
658/// 规则(规范 6.3):
659///
660/// 1. 基本名 = 各段名 `_` 连接(字段转 snake_case,常量下标 `i{k}`,变量下标 `at`);
661/// 2. 按"段序列"排序后依次发放,排前面的保留基本名;
662/// 3. 后到者追加 `__2`、`__3`…,最多到 `__6`,仍冲突则报 `E_NAME_UNRESOLVED`;
663/// 4. 命中保留字/派生方法名时先加 `_v` 后缀;
664/// 5. 段序列、可选标记与类型都相同(生成签名一致)的链共享同一个名字。
665///
666/// 输出顺序与输入一致,可安全用于生成 `accessors/<biz>.rs`。
667///
668/// 调用粒度是**一个 owner 类型一批**:不同 struct 上的同名 accessor 落在不同
669/// `impl` 块里,彼此不冲突;把多个类型混在一批会把本可复用的名字消歧成 `__2`。
670pub fn assign_names(chains: &[Chain<'_>]) -> Result<Vec<GeneratedName>, Diagnostic> {
671    let mut order: Vec<(String, usize)> = chains
672        .iter()
673        .enumerate()
674        .map(|(i, c)| (chain_key(c), i))
675        .collect();
676    order.sort();
677
678    let mut names: Vec<String> = vec![String::new(); chains.len()];
679    let mut paths: Vec<String> = vec![String::new(); chains.len()];
680    let mut used: BTreeSet<String> = BTreeSet::new();
681
682    let mut start = 0usize;
683    while start < order.len() {
684        let mut end = start + 1;
685        while end < order.len() && order[end].0 == order[start].0 {
686            end += 1;
687        }
688        let idx = order[start].1;
689        let name = fresh_name(
690            chains.get(idx).ok_or_else(|| {
691                Diagnostic::new(Code::NameCollisionUnresolved, "内部错误:链下标越界")
692            })?,
693            &used,
694        )?;
695        let path = render_path(&chains[idx]);
696        used.insert(name.clone());
697        for &(_, i) in &order[start..end] {
698            names[i] = name.clone();
699            paths[i] = path.clone();
700        }
701        start = end;
702    }
703
704    Ok(names
705        .into_iter()
706        .zip(paths)
707        .map(|(fn_name, js_path)| GeneratedName { fn_name, js_path })
708        .collect())
709}
710
711/// 去重键:基座 + 基座可空性 + 每段的形态、可选标记与类型。
712///
713/// 类型必须进键:`item.a.b` 在 `b: Option<T>` 与 `b: T` 下生成出来的函数
714/// 返回类型不同(`Option<&T>` vs `&T`),不能共用一个名字。
715fn chain_key(chain: &Chain<'_>) -> String {
716    // 基座种类必须进键:`Base::Local("item")` 与 `Base::Item` 的 `name()` 都是 "item",
717    // 但前者是局部绑定、后者是行数据,签名与 js_path 都不同,不能当成同一条链去重。
718    let mut out = String::new();
719    match chain.base {
720        Base::Item => out.push_str("I:"),
721        Base::Params => out.push_str("P:"),
722        Base::Local(name) => {
723            out.push_str("L:");
724            out.push_str(&format!("{}:", name.len()));
725            out.push_str(name);
726            out.push(':');
727        }
728    }
729    out.push_str(if chain.base_ty.is_nullable() {
730        "opt"
731    } else {
732        "req"
733    });
734    // 基座类型进键:`item.a` 在基座为 Map / 普通 struct 时诊断与生成语义不同。
735    push_type_key(&mut out, chain.base_ty);
736    for seg in chain.segs {
737        out.push('|');
738        if seg.optional {
739            out.push('?');
740        }
741        push_type_key(&mut out, seg.ty);
742        match seg.kind {
743            SegKind::Field(name) => {
744                out.push('.');
745                // 长度前缀:字段名可能含 `|` 等分隔符,裸拼接会让两条不同链撞键
746                // (`Field("a|r.b")` 与 `Field("a")+Field("b")` 曾同键)。
747                out.push_str(&format!("{}:", name.len()));
748                out.push_str(name);
749            }
750            SegKind::ConstIndex(k) => {
751                out.push('#');
752                out.push_str(&format!("{k}"));
753            }
754            SegKind::VarIndex { name, ty } => {
755                out.push('$');
756                out.push_str(&format!("{}:", name.len()));
757                out.push_str(name);
758                out.push(':');
759                out.push_str(ty.key());
760            }
761        }
762    }
763    out
764}
765
766/// 类型的紧凑表示(写进去重键):`r` / `o` / `u` / `m(T)` / `M(T)`(可空字典)。
767fn push_type_key(out: &mut String, ty: SegType<'_>) {
768    match ty {
769        SegType::Present => out.push('r'),
770        SegType::Optional => out.push('o'),
771        SegType::Unknown => out.push('u'),
772        SegType::Map(value) => push_map_key(out, 'm', value),
773        SegType::OptMap(value) => push_map_key(out, 'M', value),
774    }
775}
776
777/// 字典键:`m(T)` 非空、`M(T)` 可空,值类型带长度前缀。
778fn push_map_key(out: &mut String, tag: char, value: &str) {
779    out.push(tag);
780    out.push('(');
781    // 值类型名同样要长度前缀:它来自 JSDoc,可含 `)`、`|` 等分隔符,
782    // 裸拼接能注入后面的段键,使两条不同链同键同名。
783    out.push_str(&format!("{}:", value.len()));
784    out.push_str(value);
785    out.push(')');
786}
787
788fn fresh_name(chain: &Chain<'_>, used: &BTreeSet<String>) -> Result<String, Diagnostic> {
789    let mut base = base_name(chain);
790    if reserved(&base) {
791        base.push_str("_v");
792    }
793    if !used.contains(&base) {
794        return Ok(base);
795    }
796    for n in 2..=6u32 {
797        let candidate = format!("{base}__{n}");
798        if !used.contains(&candidate) {
799            return Ok(candidate);
800        }
801    }
802    Err(Diagnostic::new(
803        Code::NameCollisionUnresolved,
804        format!("`{base}` 的命名冲突已消歧到 `__6`,请人工指定函数名"),
805    ))
806}
807
808fn base_name(chain: &Chain<'_>) -> String {
809    if chain.segs.is_empty() {
810        // 空段链也要规范化:`.some(_ => _)` 这类回调形参作基座时,
811        // `_`/`$`/`1bad`/空串都是非法 Rust 标识符(保留字由 fresh_name 加后缀)。
812        let raw = chain.base.name();
813        let mut out = snake(raw);
814        if out.is_empty() || out == "_" || out.as_bytes().first().is_some_and(u8::is_ascii_digit) {
815            out.insert_str(0, "f_");
816        }
817        return out;
818    }
819    let mut out = String::new();
820    for (i, seg) in chain.segs.iter().enumerate() {
821        if i > 0 {
822            out.push('_');
823        }
824        match seg.kind {
825            SegKind::Field(name) => out.push_str(&snake(name)),
826            // 只有真实数组下标才进名字:`1e300 as u64` 会饱和成 u64::MAX,
827            // 与 `[18446744073709551615]` 撞名;超出上界与负数统一记 `i_invalid`
828            // (与 `plan` 折叠成常量 undefined 用同一个判定)。
829            SegKind::ConstIndex(k) if !noncanonical_index(k) => {
830                out.push_str(&format!("i{}", k as u64));
831            }
832            SegKind::ConstIndex(_) => out.push_str("i_invalid"),
833            SegKind::VarIndex { .. } => out.push_str("at"),
834        }
835    }
836    // `_` 在 Rust 2024 是保留标识符(`fn _() {}` 编译失败);单个非 ASCII 字符
837    // 经 `snake` 折成 `_` 同理。统一加前缀。
838    if out.is_empty() || out == "_" || out.as_bytes().first().is_some_and(u8::is_ascii_digit) {
839        out.insert_str(0, "f_");
840    }
841    out
842}
843
844/// camelCase / PascalCase / 全大写缩写 → snake_case;非标识符字符折成 `_`。
845///
846/// 只有「上个字母是小写/数字」或「大写字母后跟小写字母(缩写边界)」才插下划线,
847/// 因此 `fooBAR` → `foo_bar`、`XMLHttpRequest` → `xml_http_request`。
848fn snake(s: &str) -> String {
849    let chars: Vec<char> = s.chars().collect();
850    let mut out = String::with_capacity(s.len() + 4);
851    for (i, &c) in chars.iter().enumerate() {
852        if c.is_ascii_uppercase() {
853            let prev = i.checked_sub(1).map(|j| chars[j]);
854            let next = chars.get(i + 1).copied();
855            let boundary = i > 0
856                && (prev.is_some_and(|p| p.is_ascii_lowercase() || p.is_ascii_digit())
857                    || (prev.is_some_and(|p| p.is_ascii_uppercase())
858                        && next.is_some_and(|n| n.is_ascii_lowercase())));
859            if boundary {
860                out.push('_');
861            }
862            out.push(c.to_ascii_lowercase());
863        } else if c.is_ascii_alphanumeric() || c == '_' {
864            out.push(c);
865        } else {
866            out.push('_');
867        }
868    }
869    out
870}
871
872/// 保留字与派生方法名:命中就加 `_v`,避免与 `Clone::clone` 之类撞上。
873fn reserved(name: &str) -> bool {
874    const RESERVED: &[&str] = &[
875        // Rust 关键字
876        "as",
877        "async",
878        "await",
879        "break",
880        "const",
881        "continue",
882        "crate",
883        "dyn",
884        "else",
885        "enum",
886        "extern",
887        "false",
888        "fn",
889        "for",
890        "if",
891        "impl",
892        "in",
893        "let",
894        "loop",
895        "match",
896        "mod",
897        "move",
898        "mut",
899        "pub",
900        "ref",
901        "return",
902        "self",
903        "static",
904        "struct",
905        "super",
906        "trait",
907        "true",
908        "type",
909        "unsafe",
910        "use",
911        "where",
912        "while",
913        "yield",
914        // 派生 trait 方法
915        "clone",
916        "eq",
917        "ne",
918        "cmp",
919        "partial_cmp",
920        "hash",
921        "fmt",
922        "default",
923        // 常见固有方法名
924        "new",
925        "from",
926        "into",
927        "try_from",
928        "borrow",
929        "deref",
930        "index",
931        "get",
932        "iter",
933        "len",
934        "is_empty",
935        "to_string",
936        "serialize",
937        "deserialize",
938        // Rust 2018/2021 的未来保留字与 edition 2024 新增保留字:
939        // 这些名字不能作为 fn 名,漏掉会让 codegen 生成的代码编译失败
940        "Self",
941        "abstract",
942        "become",
943        "box",
944        "do",
945        "final",
946        "macro",
947        "override",
948        "priv",
949        "typeof",
950        "unsized",
951        "virtual",
952        "try",
953        "gen",
954    ];
955    RESERVED.contains(&name)
956}
957
958/// 白名单方法(规范 2.5)。
959#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
960pub enum WhitelistedMethod {
961    /// `.includes(x)`
962    Includes,
963    /// `.indexOf(x)`
964    IndexOf,
965    /// `.some(x => ...)`
966    Some,
967    /// `.startsWith(x)`
968    StartsWith,
969    /// `.endsWith(x)`
970    EndsWith,
971    /// `.length`(属性,不是调用;这里统一按白名单入口判定)
972    Length,
973}
974
975/// 判定方法调用,不在白名单时直接给出 [`Code::ChainHasCall`] 诊断。
976///
977/// codegen 侧通常只需要 `if let Ok(m) = check_method(name) { ... } else { 报错 }`。
978pub fn check_method(name: &str) -> Result<WhitelistedMethod, Diagnostic> {
979    whitelisted_method(name).ok_or_else(|| {
980        Diagnostic::new(
981            Code::ChainHasCall,
982            format!("方法 `{name}` 不在白名单内,链上只允许纯读取方法"),
983        )
984        .with_suggestion(
985            "改用白名单方法(includes/indexOf/some/startsWith/endsWith),或把这部分移到业务层",
986        )
987    })
988}
989
990/// 判定一个方法名是否在白名单内。
991///
992/// 不在白名单的方法应当生成 `E_CHAIN_HAS_CALL`,而不是"尽力翻译"——
993/// 有分配或大小写/本地化语义的方法会同时破坏性能模型与语义模型。
994pub fn whitelisted_method(name: &str) -> Option<WhitelistedMethod> {
995    Some(match name {
996        "includes" => WhitelistedMethod::Includes,
997        "indexOf" => WhitelistedMethod::IndexOf,
998        "some" => WhitelistedMethod::Some,
999        "startsWith" => WhitelistedMethod::StartsWith,
1000        "endsWith" => WhitelistedMethod::EndsWith,
1001        "length" => WhitelistedMethod::Length,
1002        _ => return None,
1003    })
1004}
1005
1006/// `Object.<string, T>` 的解析结果。
1007#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1008pub struct MapType<'s> {
1009    value: &'s str,
1010    nullable: bool,
1011}
1012
1013impl<'s> MapType<'s> {
1014    /// 元素类型原文。
1015    pub fn value(&self) -> &'s str {
1016        self.value
1017    }
1018
1019    /// 字典本身是否可为 `null`(`Object.<string, T>|null`)。
1020    pub fn is_nullable(&self) -> bool {
1021        self.nullable
1022    }
1023
1024    /// 转成链段类型:可空字典给 [`SegType::OptMap`],否则 [`SegType::Map`]。
1025    pub fn seg_type(&self) -> SegType<'s> {
1026        if self.nullable {
1027            SegType::OptMap(self.value)
1028        } else {
1029            SegType::Map(self.value)
1030        }
1031    }
1032}
1033
1034/// 从 JSDoc 类型串里识别字典类型(规范 4.3)。
1035///
1036/// 接受这些写法:
1037///
1038/// - `Object.<string, string>`
1039/// - `Object<string, number>`(无空格、无点)
1040/// - `{[k: string]: Foo}`
1041/// - 上面任意一种再加顶层 `| null` / `| undefined` / `| void`(判为可空字典)
1042///
1043/// 返回:
1044///
1045/// - `Ok(None)`:不是字典(键不是 `string`,不是对象类型,或联合了别的类型);
1046/// - `Ok(Some(..))`:字典,元素类型唯一;
1047/// - `Err(..)`:字典但元素类型混合(`E_MAP_VALUE_MIXED`)。
1048///
1049/// 注意 `Object.<string, string>|null` 这类写法**不能**在剥 `>` 之前做判断:
1050/// 结尾是 `null` 而不是 `>`,`strip_suffix('>')` 会静默失败,把 `string>|null`
1051/// 当成元素类型(可空性丢失、值类型变成垃圾串)。所以先按顶层 `|` 拆联合。
1052pub fn jsdoc_map(jsdoc: &str) -> Result<Option<MapType<'_>>, Diagnostic> {
1053    let (t, nullable) = strip_wrappers_and_union(jsdoc.trim());
1054
1055    let (key, value) = if let Some(rest) = object_generic(t) {
1056        // 联合成员已剥离,这里的结尾必须是 `>`;不是就说明类型串本身残缺,
1057        // 与其猜一个值类型,不如判成"不是字典"。
1058        let Some(rest) = rest.strip_suffix('>') else {
1059            return Ok(None);
1060        };
1061        match split_top_level(rest) {
1062            Some((k, v)) => (k, v),
1063            None => return Ok(None),
1064        }
1065    } else if let Some(rest) = t.strip_prefix('[') {
1066        // `[k: string]: V`
1067        let Some((head, tail)) = rest.split_once(']') else {
1068            return Ok(None);
1069        };
1070        let Some((_, key_ty)) = head.split_once(':') else {
1071            return Ok(None);
1072        };
1073        let tail = tail.strip_prefix(':').map_or("", str::trim);
1074        (key_ty, tail)
1075    } else {
1076        return Ok(None);
1077    };
1078
1079    if !key.trim().eq_ignore_ascii_case("string") {
1080        return Ok(None);
1081    }
1082    let value = peel_parens(value.trim());
1083    if value.is_empty() || !brackets_balanced(value) {
1084        return Ok(None);
1085    }
1086    // `Object.<string, null>` / `undefined` 没有可生成的元素类型,判成"不是字典"
1087    if matches!(
1088        value.to_ascii_lowercase().as_str(),
1089        "null" | "undefined" | "void"
1090    ) {
1091        return Ok(None);
1092    }
1093    // 元素类型自身的顶层 `|`(`Object.<string, A|B>`)是唯一的 T,必须报错;
1094    // 这里不能先拆联合,否则会把 `A|B` 的 `|` 当成"可空"处理。
1095    // 括号会遮蔽这个 `|`(`Object.<string, (A|B)>`),所以先剥括号再判。
1096    if has_top_level_separator(value) {
1097        return Err(mixed(value));
1098    }
1099    Ok(Some(MapType { value, nullable }))
1100}
1101
1102/// 逐层剥掉 `{...}` 包裹与顶层 `| null` / `| undefined` / `| void`。
1103///
1104/// 两种包裹会互相遮挡(`{Object.<string,T>|null}`),所以最多迭代三轮。
1105fn strip_wrappers_and_union(mut t: &str) -> (&str, bool) {
1106    let mut nullable = false;
1107    for _ in 0..3 {
1108        let inner = strip_outer_braces(t);
1109        let stripped = inner != t;
1110        t = inner;
1111        let (ty, nul) = split_nullable_union(t);
1112        let unioned = !std::ptr::eq(ty, t);
1113        if unioned {
1114            nullable |= nul;
1115            t = ty;
1116        }
1117        if !stripped && !unioned {
1118            break;
1119        }
1120    }
1121    (t, nullable)
1122}
1123
1124/// 首尾是成对的 `{}` 或 `()` 时剥一层。
1125///
1126/// JSDoc 里带括号的联合很常见:`{(Object.<string, string>|null)}`。
1127fn strip_outer_braces(s: &str) -> &str {
1128    for (open, close) in [('{', '}'), ('(', ')')] {
1129        if let Some(inner) = s.strip_prefix(open).and_then(|x| x.strip_suffix(close)) {
1130            // `{a} | {b}` 的首 `{` 与尾 `}` 并不配对,剥了会破坏结构
1131            let mut depth = 0i32;
1132            for c in inner.chars() {
1133                if c == open {
1134                    depth += 1;
1135                } else if c == close {
1136                    depth -= 1;
1137                    if depth < 0 {
1138                        return s;
1139                    }
1140                }
1141            }
1142            if depth == 0 {
1143                return inner.trim();
1144            }
1145        }
1146    }
1147    s
1148}
1149
1150/// 顶层 `|` 拆联合:只剩一个非空成员时返回 (该成员, true),否则原样返回。
1151fn split_nullable_union(s: &str) -> (&str, bool) {
1152    let mut depth = 0i32;
1153    let mut start = 0usize;
1154    let mut members: Vec<&str> = Vec::new();
1155    for (i, c) in s.char_indices() {
1156        match c {
1157            '{' | '[' | '(' | '<' => depth += 1,
1158            '}' | ']' | ')' | '>' => depth -= 1,
1159            '|' if depth == 0 => {
1160                members.push(s[start..i].trim());
1161                start = i + 1;
1162            }
1163            _ => {}
1164        }
1165    }
1166    if members.is_empty() {
1167        return (s, false);
1168    }
1169    members.push(s[start..].trim());
1170    let mut non_null = members.iter().copied().filter(|m| {
1171        !matches!(
1172            m.to_ascii_lowercase().as_str(),
1173            "null" | "undefined" | "void"
1174        )
1175    });
1176    let (Some(only), None) = (non_null.next(), non_null.next()) else {
1177        // 多个非空成员(`Object.<string,A>|Object.<string,B>`)不是单一字典
1178        return (s, false);
1179    };
1180    if only.is_empty() {
1181        return (s, false);
1182    }
1183    (only, true)
1184}
1185
1186fn object_generic(s: &str) -> Option<&str> {
1187    ["Object.<", "Object<", "object.<", "object<"]
1188        .iter()
1189        .find_map(|p| s.strip_prefix(p))
1190}
1191
1192/// `<>` 是否成对且不到负深度。
1193fn brackets_balanced(s: &str) -> bool {
1194    let mut depth = 0i32;
1195    for c in s.chars() {
1196        match c {
1197            '<' => depth += 1,
1198            '>' => {
1199                depth -= 1;
1200                if depth < 0 {
1201                    return false;
1202                }
1203            }
1204            _ => {}
1205        }
1206    }
1207    depth == 0
1208}
1209
1210fn mixed(value: &str) -> Diagnostic {
1211    Diagnostic::new(
1212        Code::MapValueMixed,
1213        format!("`Object.<string, {value}>` 的元素类型不唯一,`Map<String, T>` 要求单一 T"),
1214    )
1215    .with_suggestion("拆成两个字段,或把元素类型收窄成具体类型")
1216}
1217
1218/// 剥掉成对的包裹括号(只剥 `()`,`{}` 是对象字面量,不能动)。
1219fn peel_parens(mut s: &str) -> &str {
1220    loop {
1221        let inner = strip_outer_braces(s);
1222        // strip_outer_braces 也可能剥 `{}`;这里只接受剥掉括号的结果
1223        if inner != s && s.starts_with('(') && s.ends_with(')') {
1224            s = inner;
1225        } else {
1226            return s;
1227        }
1228    }
1229}
1230
1231/// 在顶层逗号处切分(尊重 `{}`/`[]`/`()`/`<>` 的嵌套)。
1232fn split_top_level(s: &str) -> Option<(&str, &str)> {
1233    let mut depth = 0i32;
1234    for (i, c) in s.char_indices() {
1235        match c {
1236            '{' | '[' | '(' | '<' => depth += 1,
1237            '}' | ']' | ')' | '>' => depth -= 1,
1238            ',' if depth == 0 => return Some((&s[..i], &s[i + 1..])),
1239            _ => {}
1240        }
1241    }
1242    None
1243}
1244
1245/// 顶层是否有 `|` 或 `,`(混合类型或元组)。
1246fn has_top_level_separator(s: &str) -> bool {
1247    let mut depth = 0i32;
1248    for c in s.chars() {
1249        match c {
1250            '{' | '[' | '(' | '<' => depth += 1,
1251            '}' | ']' | ')' | '>' => depth -= 1,
1252            '|' | ',' if depth == 0 => return true,
1253            _ => {}
1254        }
1255    }
1256    false
1257}
1258
1259/// `Map` 元素类型文本是否混合(供 `plan` 复用)。
1260fn mixed_map_value(value: &str) -> Option<Diagnostic> {
1261    if has_top_level_separator(value) {
1262        Some(mixed(value))
1263    } else {
1264        None
1265    }
1266}
1267
1268#[cfg(test)]
1269mod tests {
1270    use super::*;
1271
1272    fn seg(name: &'static str, ty: SegType<'static>, optional: bool) -> Segment<'static> {
1273        Segment::field(name, ty, optional)
1274    }
1275
1276    #[test]
1277    fn present_chain_needs_no_option() {
1278        let segs = [
1279            seg("status", SegType::Present, false),
1280            seg("status_id", SegType::Present, false),
1281        ];
1282        let c = Chain::item(&segs);
1283        let p = plan(&c);
1284        assert_eq!(
1285            p.steps(),
1286            &[Step::Field("status"), Step::Field("status_id")]
1287        );
1288        assert!(!p.returns_option());
1289        assert!(p.diagnostics().is_empty());
1290    }
1291
1292    #[test]
1293    fn optional_middle_requires_chain_operator() {
1294        let segs = [
1295            seg("detail", SegType::Optional, false),
1296            seg("info", SegType::Present, false),
1297        ];
1298        let p = plan(&Chain::item(&segs));
1299        assert_eq!(p.diagnostics().len(), 1);
1300        assert_eq!(p.diagnostics()[0].code(), Code::NonOptOnOptional);
1301        // `?.` 属于"被访问的那一段",所以错误报在 info 上
1302        assert_eq!(p.diagnostics()[0].segment(), Some(1));
1303        assert!(
1304            p.diagnostics()[0]
1305                .suggestion()
1306                .is_some_and(|s| s.contains("item.detail?.info"))
1307        );
1308    }
1309
1310    #[test]
1311    fn optional_middle_with_operator_is_fine() {
1312        let segs = [
1313            seg("detail", SegType::Optional, false),
1314            seg("info", SegType::Present, true),
1315        ];
1316        let p = plan(&Chain::item(&segs));
1317        assert_eq!(p.steps(), &[Step::OptField("detail"), Step::Field("info")]);
1318        assert!(p.returns_option());
1319        assert!(p.diagnostics().is_empty());
1320    }
1321
1322    #[test]
1323    fn optional_leaf_is_allowed_without_operator() {
1324        let segs = [seg("code", SegType::Optional, false)];
1325        let p = plan(&Chain::item(&segs));
1326        assert!(p.returns_option());
1327        assert!(p.diagnostics().is_empty(), "叶段可空是正常形态");
1328    }
1329
1330    #[test]
1331    fn redundant_operator_is_a_warning() {
1332        let segs = [
1333            seg("status", SegType::Present, false),
1334            seg("status_id", SegType::Present, true),
1335        ];
1336        let p = plan(&Chain::item(&segs));
1337        assert_eq!(p.diagnostics()[0].code(), Code::RedundantOptionalChain);
1338        assert_eq!(p.diagnostics()[0].severity(), Severity::Warning);
1339        assert!(!p.has_errors());
1340    }
1341
1342    #[test]
1343    fn nullable_base_requires_operator_on_first_segment() {
1344        let segs = [seg("code", SegType::Present, false)];
1345        let p = plan(&Chain::params(true, &segs));
1346        assert_eq!(p.diagnostics()[0].code(), Code::NonOptOnOptional);
1347        assert!(
1348            p.diagnostics()[0]
1349                .suggestion()
1350                .is_some_and(|s| s.contains("params?.code"))
1351        );
1352    }
1353
1354    #[test]
1355    fn negative_and_fractional_const_index_fold_to_undefined() {
1356        let neg = [Segment::const_index(-1.0, SegType::Present, true)];
1357        let p = plan(&Chain::item(&neg));
1358        assert!(p.is_constant_undefined());
1359        assert!(p.steps().is_empty());
1360
1361        let frac = [Segment::const_index(1.5, SegType::Present, false)];
1362        assert!(plan(&Chain::item(&frac)).is_constant_undefined());
1363
1364        let ok = [Segment::const_index(3.0, SegType::Present, false)];
1365        let p = plan(&Chain::item(&ok));
1366        assert_eq!(p.steps(), &[Step::Index(3)]);
1367
1368        // 超出 JS 数组下标上界:不能饱和成 usize::MAX
1369        let huge = [Segment::const_index(1e300, SegType::Present, false)];
1370        let p = plan(&Chain::item(&huge));
1371        assert!(p.is_constant_undefined());
1372        assert!(p.steps().is_empty());
1373    }
1374
1375    #[test]
1376    fn map_noncanonical_numeric_key_is_an_error_not_undefined() {
1377        for k in [-1.0, 1.5, 1e300] {
1378            let segs = [
1379                seg("tags", SegType::Map("string"), false),
1380                Segment::const_index(k, SegType::Present, false),
1381            ];
1382            let p = plan(&Chain::item(&segs));
1383            assert!(!p.is_constant_undefined(), "map key {k}");
1384            assert!(p.has_errors(), "map key {k}");
1385            assert_eq!(
1386                p.diagnostics()[0].code(),
1387                Code::MapNonCanonicalIndex,
1388                "map key {k}"
1389            );
1390        }
1391        // 规范数字键仍走 Index
1392        let ok = [
1393            seg("tags", SegType::Map("string"), false),
1394            Segment::const_index(2.0, SegType::Present, false),
1395        ];
1396        let p = plan(&Chain::item(&ok));
1397        assert!(!p.has_errors());
1398        assert_eq!(p.steps()[1], Step::Index(2));
1399    }
1400
1401    #[test]
1402    fn dynamic_key_on_struct_is_error_but_on_map_is_fine() {
1403        let map_segs = [
1404            seg("tags", SegType::Map("string"), false),
1405            Segment::var_index("k", IndexTy::I64, SegType::Present, false),
1406        ];
1407        let p = plan(&Chain::item(&map_segs));
1408        assert!(p.diagnostics().is_empty());
1409        assert_eq!(p.steps()[1], Step::VarIndex(IndexTy::I64));
1410
1411        let struct_segs = [
1412            seg("detail", SegType::Present, false),
1413            Segment::var_index("k", IndexTy::I64, SegType::Present, false),
1414        ];
1415        let p = plan(&Chain::item(&struct_segs));
1416        assert_eq!(p.diagnostics()[0].code(), Code::DynamicKeyOnStruct);
1417    }
1418
1419    #[test]
1420    fn map_value_mixed_is_reported() {
1421        let segs = [
1422            seg("m", SegType::Map("string | number"), false),
1423            Segment::var_index("k", IndexTy::I64, SegType::Present, false),
1424        ];
1425        let p = plan(&Chain::item(&segs));
1426        assert_eq!(p.diagnostics()[0].code(), Code::MapValueMixed);
1427    }
1428
1429    #[test]
1430    fn names_are_deterministic_and_deduped() {
1431        let a1 = [
1432            seg("a", SegType::Present, false),
1433            seg("b", SegType::Present, false),
1434        ];
1435        let a2 = [seg("a_b", SegType::Present, false)];
1436        let dup = [
1437            seg("a", SegType::Present, false),
1438            seg("b", SegType::Present, false),
1439        ];
1440        let chains = [Chain::item(&a1), Chain::item(&a2), Chain::item(&dup)];
1441        let names = assign_names(&chains).unwrap();
1442        // 排序按去重键字典序:段名带长度前缀后,`a.b`(`1:a|1:b`)排在
1443        // `a_b`(`3:a_b`)之前,前者先拿到基本名
1444        assert_eq!(names[0].fn_name(), "a_b");
1445        assert_eq!(names[1].fn_name(), "a_b__2");
1446        // 完全相同的链共享一个函数
1447        assert_eq!(names[2].fn_name(), names[0].fn_name());
1448        assert_eq!(names[0].js_path(), "item.a.b");
1449    }
1450
1451    #[test]
1452    fn reserved_names_get_suffix() {
1453        let segs = [seg("type", SegType::Present, false)];
1454        let names = assign_names(&[Chain::item(&segs)]).unwrap();
1455        assert_eq!(names[0].fn_name(), "type_v");
1456
1457        let clone_segs = [seg("clone", SegType::Present, false)];
1458        let names = assign_names(&[Chain::item(&clone_segs)]).unwrap();
1459        assert_eq!(names[0].fn_name(), "clone_v");
1460    }
1461
1462    #[test]
1463    fn camel_case_becomes_snake() {
1464        for (field, want) in [
1465            ("orderProductName", "order_product_name"),
1466            ("fooBAR", "foo_bar"),
1467            ("XMLHttpRequest", "xml_http_request"),
1468            ("a_b", "a_b"),
1469        ] {
1470            let segs = [seg(field, SegType::Present, false)];
1471            let names = assign_names(&[Chain::item(&segs)]).unwrap();
1472            assert_eq!(names[0].fn_name(), want, "字段 {field}");
1473        }
1474    }
1475
1476    #[test]
1477    fn underscore_and_non_identifier_fields_get_prefix() {
1478        for field in ["_", "$", "α", "€", ""] {
1479            let segs = [seg(field, SegType::Present, false)];
1480            let names = assign_names(&[Chain::item(&segs)]).unwrap();
1481            let name = names[0].fn_name();
1482            assert_ne!(name, "_", "字段 {field}");
1483            // 生成名必须是 Rust 合法标识符:非空、非 `_`、首字符非数字
1484            assert!(
1485                name.starts_with('f') || name.starts_with('_'),
1486                "字段 {field} → {name}"
1487            );
1488            assert!(name.len() > 1, "字段 {field}");
1489        }
1490    }
1491
1492    #[test]
1493    fn distinct_field_names_do_not_share_name_key() {
1494        // `Field("a|r.b")` 与两段 `a` `b` 旧实现撞键,共享函数名
1495        let piped = [seg("a|r.b", SegType::Present, false)];
1496        let two = [
1497            seg("a", SegType::Present, false),
1498            seg("b", SegType::Present, false),
1499        ];
1500        let names = assign_names(&[Chain::item(&piped), Chain::item(&two)]).unwrap();
1501        assert_ne!(names[0].fn_name(), names[1].fn_name());
1502    }
1503
1504    #[test]
1505    fn rust_2024_reserved_names_get_suffix() {
1506        for field in ["gen", "try", "box", "typeof", "do", "macro"] {
1507            let segs = [seg(field, SegType::Present, false)];
1508            let names = assign_names(&[Chain::item(&segs)]).unwrap();
1509            assert_eq!(names[0].fn_name(), format!("{field}_v"), "字段 {field}");
1510        }
1511    }
1512
1513    #[test]
1514    fn var_index_is_named_at() {
1515        let segs = [Segment::var_index(
1516            "i",
1517            IndexTy::I64,
1518            SegType::Present,
1519            false,
1520        )];
1521        let names = assign_names(&[Chain::item(&segs)]).unwrap();
1522        assert_eq!(names[0].fn_name(), "at");
1523        assert_eq!(names[0].js_path(), "item[i]");
1524    }
1525
1526    #[test]
1527    fn nullability_is_part_of_the_name_key() {
1528        // `b` 可空与不可空生成的返回类型不同,不能共用一个名字
1529        let opt = [
1530            seg("a", SegType::Present, false),
1531            seg("b", SegType::Optional, false),
1532        ];
1533        let req = [
1534            seg("a", SegType::Present, false),
1535            seg("b", SegType::Present, false),
1536        ];
1537        let names = assign_names(&[Chain::item(&opt), Chain::item(&req)]).unwrap();
1538        assert_ne!(names[0].fn_name(), names[1].fn_name());
1539
1540        // 段名、可选标记、类型都相同才算同一条链
1541        let dup = [
1542            seg("a", SegType::Present, false),
1543            seg("b", SegType::Optional, false),
1544        ];
1545        let names = assign_names(&[Chain::item(&opt), Chain::item(&dup)]).unwrap();
1546        assert_eq!(names[0].fn_name(), names[1].fn_name());
1547    }
1548
1549    #[test]
1550    fn mixed_bases_never_share_a_name() {
1551        let segs = [seg("a", SegType::Present, false)];
1552        let chains = [
1553            Chain::item(&segs),
1554            Chain::params(true, &segs),
1555            Chain::local("x", false, &segs),
1556        ];
1557        let names = assign_names(&chains).unwrap();
1558        assert_ne!(names[0].fn_name(), names[1].fn_name());
1559        assert_ne!(names[1].fn_name(), names[2].fn_name());
1560        assert_eq!(names[2].js_path(), "x.a");
1561    }
1562
1563    #[test]
1564    fn empty_chain_follows_base_nullability() {
1565        let empty: &[Segment<'_>] = &[];
1566        assert!(!plan(&Chain::item(empty)).returns_option());
1567        assert!(plan(&Chain::params(true, empty)).returns_option());
1568        assert!(plan(&Chain::local("x", true, empty)).returns_option());
1569    }
1570
1571    #[test]
1572    fn method_check_returns_a_diagnostic() {
1573        assert_eq!(check_method("includes"), Ok(WhitelistedMethod::Includes));
1574        let err = check_method("toUpperCase").unwrap_err();
1575        assert_eq!(err.code(), Code::ChainHasCall);
1576        assert_eq!(err.code_str(), "E_CHAIN_HAS_CALL");
1577        assert!(err.suggestion().is_some());
1578    }
1579
1580    #[test]
1581    fn local_base_renders_its_variable_name() {
1582        let segs = [
1583            seg("a", SegType::Optional, false),
1584            seg("b", SegType::Present, false),
1585        ];
1586        let chain = Chain::local("row", false, &segs);
1587        assert_eq!(render_path(&chain), "row.a.b");
1588        assert_eq!(
1589            plan(&chain).diagnostics()[0].suggestion(),
1590            Some("改为 row.a?.b")
1591        );
1592        assert_eq!(assign_names(&[chain]).unwrap()[0].fn_name(), "a_b");
1593    }
1594
1595    #[test]
1596    fn jsdoc_map_forms() {
1597        assert_eq!(
1598            jsdoc_map("Object.<string, string>")
1599                .unwrap()
1600                .map(|m| m.value()),
1601            Some("string")
1602        );
1603        assert_eq!(
1604            jsdoc_map("{Object<string, number>}")
1605                .unwrap()
1606                .map(|m| m.value()),
1607            Some("number")
1608        );
1609        assert_eq!(
1610            jsdoc_map("{[k: string]: Foo}").unwrap().map(|m| m.value()),
1611            Some("Foo")
1612        );
1613        // 键不是 string:不当作字典
1614        assert!(jsdoc_map("Object.<number, string>").unwrap().is_none());
1615        // 元素类型混合:报错
1616        let e = jsdoc_map("Object.<string, string|number>").unwrap_err();
1617        assert_eq!(e.code(), Code::MapValueMixed);
1618        // 嵌套的逗号不算混合
1619        assert_eq!(
1620            jsdoc_map("Object.<string, {a: number, b: string}>")
1621                .unwrap()
1622                .map(|m| m.value()),
1623            Some("{a: number, b: string}")
1624        );
1625    }
1626
1627    #[test]
1628    fn whitelist_entries() {
1629        assert_eq!(
1630            whitelisted_method("includes"),
1631            Some(WhitelistedMethod::Includes)
1632        );
1633        assert_eq!(whitelisted_method("toLowerCase"), None);
1634        // 未知方法调用应报 E_CHAIN_HAS_CALL
1635        assert_eq!(Code::ChainHasCall.as_str(), "E_CHAIN_HAS_CALL");
1636    }
1637
1638    #[test]
1639    fn render_path_marks_optional_segments() {
1640        let segs = [
1641            seg("detail", SegType::Optional, false),
1642            Segment::const_index(0.0, SegType::Present, true),
1643            seg("name", SegType::Present, false),
1644        ];
1645        assert_eq!(render_path(&Chain::item(&segs)), "item.detail?.[0].name");
1646    }
1647
1648    #[test]
1649    fn local_base_collisions_and_invalid_names() {
1650        // Base::Local("item") 与 Base::Item 的 name() 相同,去重键必须区分来源
1651        let segs = [seg("foo", SegType::Present, false)];
1652        let names =
1653            assign_names(&[Chain::item(&segs), Chain::local("item", false, &segs)]).unwrap();
1654        assert_ne!(names[0].fn_name(), names[1].fn_name());
1655
1656        // 空段链的 Local 名也要走标识符规范化(`.some(_ => _)` 的回调形参)
1657        for (raw, want) in [("_", "f__"), ("$", "f__"), ("1bad", "f_1bad"), ("", "f_")] {
1658            let empty = [];
1659            let got = assign_names(&[Chain::local(raw, false, &empty)]).unwrap();
1660            assert_eq!(got[0].fn_name(), want, "local({raw:?})");
1661        }
1662    }
1663
1664    #[test]
1665    fn map_noncanonical_index_truncates_steps() {
1666        // 非规范键只保留诊断,不能生成饱和的 Step::Index
1667        let segs = [
1668            seg("m", SegType::Map("string"), false),
1669            Segment::const_index(1e300, SegType::Present, false),
1670        ];
1671        let p = plan(&Chain::item(&segs));
1672        assert!(p.has_errors());
1673        assert_eq!(p.steps(), &[Step::Field("m")]);
1674    }
1675
1676    #[test]
1677    fn field_on_map_returns_option() {
1678        let segs = [
1679            seg("tags", SegType::Map("string"), false),
1680            seg("foo", SegType::Present, false),
1681        ];
1682        let p = plan(&Chain::item(&segs));
1683        assert_eq!(p.steps()[1], Step::MapField("foo"));
1684        assert!(p.steps()[1].is_option());
1685        assert!(p.returns_option());
1686    }
1687
1688    #[test]
1689    fn folded_index_does_not_hide_optional_type_error() {
1690        // `item.detail[-1]`:detail 可空却没写 `?.`,JS 会抛 TypeError。
1691        // 折叠成常量 undefined 不能把这个错误吞掉,所以可空性判定排在折叠之前。
1692        let segs = [
1693            seg("detail", SegType::Optional, false),
1694            Segment::const_index(-1.0, SegType::Present, false),
1695        ];
1696        let p = plan(&Chain::item(&segs));
1697        assert!(p.is_constant_undefined());
1698        assert!(p.has_errors());
1699        assert_eq!(p.diagnostics()[0].code(), Code::NonOptOnOptional);
1700
1701        // 写了 `?.` 就没有 TypeError,折叠后也不再报"`?.` 多余"
1702        let ok = [
1703            seg("detail", SegType::Optional, false),
1704            Segment::const_index(-1.0, SegType::Present, true),
1705        ];
1706        let p = plan(&Chain::item(&ok));
1707        assert!(p.is_constant_undefined());
1708        assert!(!p.has_warnings());
1709        assert!(p.diagnostics().is_empty());
1710    }
1711
1712    #[test]
1713    fn index_names_use_real_array_bounds() {
1714        // `1e300 as u64` 饱和成 u64::MAX,会与 `[18446744073709551615]` 撞名
1715        let big = [Segment::const_index(1e300, SegType::Present, false)];
1716        let real = [Segment::const_index(
1717            18446744073709551615.0,
1718            SegType::Present,
1719            false,
1720        )];
1721        let names = assign_names(&[Chain::item(&big), Chain::item(&real)]).unwrap();
1722        assert_eq!(names[0].fn_name(), "i_invalid");
1723        assert_eq!(names[1].fn_name(), "i_invalid__2");
1724
1725        let zero = [Segment::const_index(0.0, SegType::Present, false)];
1726        assert_eq!(
1727            assign_names(&[Chain::item(&zero)]).unwrap()[0].fn_name(),
1728            "i0"
1729        );
1730        let top = [Segment::const_index(
1731            MAX_ARRAY_INDEX,
1732            SegType::Present,
1733            false,
1734        )];
1735        assert_eq!(
1736            assign_names(&[Chain::item(&top)]).unwrap()[0].fn_name(),
1737            "i_invalid"
1738        );
1739    }
1740
1741    #[test]
1742    fn map_value_name_cannot_inject_dedup_key() {
1743        // JSDoc 值类型可含 `)`/`|`,裸拼接会让两条不同链撞键、同名
1744        let a_segs = [seg("y)", SegType::Present, false)];
1745        let b_segs: [Segment; 0] = [];
1746        let a = Chain {
1747            base: Base::Item,
1748            base_ty: SegType::Map("x"),
1749            segs: &a_segs,
1750        };
1751        let b = Chain {
1752            base: Base::Item,
1753            base_ty: SegType::Map("x)|r.2:y"),
1754            segs: &b_segs,
1755        };
1756        let names = assign_names(&[a, b]).unwrap();
1757        assert_ne!(names[0].fn_name(), names[1].fn_name());
1758    }
1759
1760    #[test]
1761    fn mixed_map_value_is_diagnosed_for_every_access_shape() {
1762        for segs in [
1763            vec![
1764                seg("m", SegType::Map("string | number"), false),
1765                seg("foo", SegType::Present, false),
1766            ],
1767            vec![
1768                seg("m", SegType::Map("string | number"), false),
1769                Segment::const_index(0.0, SegType::Present, false),
1770            ],
1771            vec![
1772                seg("m", SegType::Map("string | number"), false),
1773                Segment::var_index("k", IndexTy::I64, SegType::Present, false),
1774            ],
1775        ] {
1776            let p = plan(&Chain::item(&segs));
1777            assert!(
1778                p.diagnostics()
1779                    .iter()
1780                    .any(|d| d.code() == Code::MapValueMixed),
1781                "{segs:?}"
1782            );
1783        }
1784    }
1785}