1use std::collections::BTreeSet;
43use std::fmt;
44
45const MAX_ARRAY_INDEX: f64 = 4_294_967_296.0;
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
51pub enum Base<'s> {
52 Item,
54 Params,
56 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
73pub enum IndexTy {
74 I64,
76 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#[derive(Clone, Copy, Debug, PartialEq)]
91pub enum SegKind<'s> {
92 Field(&'s str),
94 ConstIndex(f64),
96 VarIndex {
98 name: &'s str,
100 ty: IndexTy,
102 },
103}
104
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub enum SegType<'s> {
108 Present,
110 Optional,
112 Map(&'s str),
114 OptMap(&'s str),
118 Unknown,
120}
121
122impl<'s> SegType<'s> {
123 pub fn is_nullable(self) -> bool {
125 matches!(self, SegType::Optional | SegType::OptMap(_))
126 }
127
128 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#[derive(Clone, Copy, Debug, PartialEq)]
139pub struct Segment<'s> {
140 pub kind: SegKind<'s>,
142 pub optional: bool,
144 pub ty: SegType<'s>,
146}
147
148impl<'s> Segment<'s> {
149 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 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 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#[derive(Clone, Copy, Debug, PartialEq)]
179pub struct Chain<'s> {
180 pub base: Base<'s>,
182 pub base_ty: SegType<'s>,
184 pub segs: &'s [Segment<'s>],
186}
187
188impl<'s> Chain<'s> {
189 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 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
227pub enum Severity {
228 Error,
230 Warning,
232}
233
234#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
236pub enum Code {
237 NonOptOnOptional,
239 DynamicKeyOnStruct,
241 MapNonCanonicalIndex,
244 MapValueMixed,
246 ChainHasCall,
248 NullStrict,
250 NameCollisionUnresolved,
252 RedundantOptionalChain,
254}
255
256impl Code {
257 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 pub fn severity(self) -> Severity {
273 match self {
274 Code::RedundantOptionalChain => Severity::Warning,
275 _ => Severity::Error,
276 }
277 }
278}
279
280#[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 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 #[must_use]
304 pub fn with_segment(mut self, segment: usize) -> Self {
305 self.segment = Some(segment);
306 self
307 }
308
309 #[must_use]
311 pub fn with_offset(mut self, offset: usize) -> Self {
312 self.offset = Some(offset);
313 self
314 }
315
316 #[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 pub fn code(&self) -> Code {
325 self.code
326 }
327
328 pub fn code_str(&self) -> &'static str {
330 self.code.as_str()
331 }
332
333 pub fn severity(&self) -> Severity {
335 self.code.severity()
336 }
337
338 pub fn segment(&self) -> Option<usize> {
340 self.segment
341 }
342
343 pub fn offset(&self) -> Option<usize> {
345 self.offset
346 }
347
348 pub fn message(&self) -> &str {
350 &self.message
351 }
352
353 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
374pub enum Step<'s> {
375 Field(&'s str),
377 OptField(&'s str),
379 MapField(&'s str),
383 Index(usize),
386 VarIndex(IndexTy),
388}
389
390impl Step<'_> {
391 pub fn is_option(&self) -> bool {
393 !matches!(self, Step::Field(_))
394 }
395}
396
397#[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 pub fn steps(&self) -> &[Step<'s>] {
409 &self.steps
410 }
411
412 pub fn returns_option(&self) -> bool {
414 self.returns_option
415 }
416
417 pub fn is_constant_undefined(&self) -> bool {
419 self.constant_undefined
420 }
421
422 pub fn diagnostics(&self) -> &[Diagnostic] {
424 &self.diagnostics
425 }
426
427 pub fn has_errors(&self) -> bool {
429 self.diagnostics
430 .iter()
431 .any(|d| d.severity() == Severity::Error)
432 }
433
434 pub fn has_warnings(&self) -> bool {
436 self.diagnostics
437 .iter()
438 .any(|d| d.severity() == Severity::Warning)
439 }
440}
441
442pub 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 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 let container_ty = if i == 0 {
463 chain.base_ty
464 } else {
465 chain.segs[i - 1].ty
466 };
467 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 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 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 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 if matches!(container_ty, SegType::Map(_) | SegType::OptMap(_)) && noncanonical_index(k)
524 {
525 diagnostics.push(
527 Diagnostic::new(
528 Code::MapNonCanonicalIndex,
529 format!("字典上的数字键 `{k}` 不是规范数组下标,请改写成字符串键"),
530 )
531 .with_segment(i)
532 .with_suggestion(format!("把 `[{k}]` 改成 `[\"{k}\"]`")),
533 );
534 break;
538 }
539 }
540
541 match seg.kind {
542 SegKind::Field(name) => {
543 if container_ty.map_value().is_some() {
544 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 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
591fn noncanonical_index(k: f64) -> bool {
597 k.is_nan() || k < 0.0 || k.fract() != 0.0 || k >= MAX_ARRAY_INDEX
598}
599
600pub fn render_path(chain: &Chain<'_>) -> String {
602 render_path_inner(chain, None)
603}
604
605fn 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 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
635fn 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#[derive(Clone, Debug, PartialEq, Eq)]
657pub struct GeneratedName {
658 pub fn_name: String,
660 pub js_path: String,
662}
663
664impl GeneratedName {
665 pub fn fn_name(&self) -> &str {
667 &self.fn_name
668 }
669
670 pub fn js_path(&self) -> &str {
672 &self.js_path
673 }
674}
675
676pub 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
731fn chain_key(chain: &Chain<'_>) -> String {
736 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 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 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
786fn 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
797fn push_map_key(out: &mut String, tag: char, value: &str) {
799 out.push(tag);
800 out.push('(');
801 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 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 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 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
864fn 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
892fn reserved(name: &str) -> bool {
894 const RESERVED: &[&str] = &[
895 "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 "clone",
936 "eq",
937 "ne",
938 "cmp",
939 "partial_cmp",
940 "hash",
941 "fmt",
942 "default",
943 "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 "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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
980pub enum WhitelistedMethod {
981 Includes,
983 IndexOf,
985 Some,
987 StartsWith,
989 EndsWith,
991 Length,
993}
994
995pub 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
1010pub 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1028pub struct MapType<'s> {
1029 value: &'s str,
1030 nullable: bool,
1031}
1032
1033impl<'s> MapType<'s> {
1034 pub fn value(&self) -> &'s str {
1036 self.value
1037 }
1038
1039 pub fn is_nullable(&self) -> bool {
1041 self.nullable
1042 }
1043
1044 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
1054pub 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 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 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 if matches!(
1108 value.to_ascii_lowercase().as_str(),
1109 "null" | "undefined" | "void"
1110 ) {
1111 return Ok(None);
1112 }
1113 if has_top_level_separator(value) {
1117 return Err(mixed(value));
1118 }
1119 Ok(Some(MapType { value, nullable }))
1120}
1121
1122fn 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
1144fn 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 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
1170fn 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 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
1212fn 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
1238fn peel_parens(mut s: &str) -> &str {
1240 loop {
1241 let inner = strip_outer_braces(s);
1242 if inner != s && s.starts_with('(') && s.ends_with(')') {
1244 s = inner;
1245 } else {
1246 return s;
1247 }
1248 }
1249}
1250
1251fn 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
1265fn 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
1279fn 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 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 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 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 assert_eq!(names[0].fn_name(), "a_b");
1465 assert_eq!(names[1].fn_name(), "a_b__2");
1466 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 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 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 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 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 assert!(jsdoc_map("Object.<number, string>").unwrap().is_none());
1635 let e = jsdoc_map("Object.<string, string|number>").unwrap_err();
1637 assert_eq!(e.code(), Code::MapValueMixed);
1638 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 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 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 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 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 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 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 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 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}