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 = 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 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#[derive(Clone, Debug, PartialEq, Eq)]
637pub struct GeneratedName {
638 pub fn_name: String,
640 pub js_path: String,
642}
643
644impl GeneratedName {
645 pub fn fn_name(&self) -> &str {
647 &self.fn_name
648 }
649
650 pub fn js_path(&self) -> &str {
652 &self.js_path
653 }
654}
655
656pub 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
711fn chain_key(chain: &Chain<'_>) -> String {
716 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 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 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
766fn 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
777fn push_map_key(out: &mut String, tag: char, value: &str) {
779 out.push(tag);
780 out.push('(');
781 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 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 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 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
844fn 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
872fn reserved(name: &str) -> bool {
874 const RESERVED: &[&str] = &[
875 "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 "clone",
916 "eq",
917 "ne",
918 "cmp",
919 "partial_cmp",
920 "hash",
921 "fmt",
922 "default",
923 "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 "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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
960pub enum WhitelistedMethod {
961 Includes,
963 IndexOf,
965 Some,
967 StartsWith,
969 EndsWith,
971 Length,
973}
974
975pub 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
990pub 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1008pub struct MapType<'s> {
1009 value: &'s str,
1010 nullable: bool,
1011}
1012
1013impl<'s> MapType<'s> {
1014 pub fn value(&self) -> &'s str {
1016 self.value
1017 }
1018
1019 pub fn is_nullable(&self) -> bool {
1021 self.nullable
1022 }
1023
1024 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
1034pub 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 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 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 if matches!(
1088 value.to_ascii_lowercase().as_str(),
1089 "null" | "undefined" | "void"
1090 ) {
1091 return Ok(None);
1092 }
1093 if has_top_level_separator(value) {
1097 return Err(mixed(value));
1098 }
1099 Ok(Some(MapType { value, nullable }))
1100}
1101
1102fn 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
1124fn 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 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
1150fn 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 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
1192fn 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
1218fn peel_parens(mut s: &str) -> &str {
1220 loop {
1221 let inner = strip_outer_braces(s);
1222 if inner != s && s.starts_with('(') && s.ends_with(')') {
1224 s = inner;
1225 } else {
1226 return s;
1227 }
1228 }
1229}
1230
1231fn 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
1245fn 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
1259fn 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 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 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 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 assert_eq!(names[0].fn_name(), "a_b");
1445 assert_eq!(names[1].fn_name(), "a_b__2");
1446 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 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 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 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 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 assert!(jsdoc_map("Object.<number, string>").unwrap().is_none());
1615 let e = jsdoc_map("Object.<string, string|number>").unwrap_err();
1617 assert_eq!(e.code(), Code::MapValueMixed);
1618 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 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 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 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 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 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 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 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 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}