use std::collections::BTreeSet;
use std::fmt;
const MAX_ARRAY_INDEX: f64 = 4_294_967_296.0;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Base<'s> {
Item,
Params,
Local(&'s str),
}
impl<'s> Base<'s> {
fn name(self) -> &'s str {
match self {
Base::Item => "item",
Base::Params => "params",
Base::Local(name) => name,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum IndexTy {
I64,
F64,
}
impl IndexTy {
fn key(self) -> &'static str {
match self {
IndexTy::I64 => "i64",
IndexTy::F64 => "f64",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SegKind<'s> {
Field(&'s str),
ConstIndex(f64),
VarIndex {
name: &'s str,
ty: IndexTy,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SegType<'s> {
Present,
Optional,
Map(&'s str),
OptMap(&'s str),
Unknown,
}
impl<'s> SegType<'s> {
pub fn is_nullable(self) -> bool {
matches!(self, SegType::Optional | SegType::OptMap(_))
}
pub fn map_value(self) -> Option<&'s str> {
match self {
SegType::Map(v) | SegType::OptMap(v) => Some(v),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Segment<'s> {
pub kind: SegKind<'s>,
pub optional: bool,
pub ty: SegType<'s>,
}
impl<'s> Segment<'s> {
pub fn field(name: &'s str, ty: SegType<'s>, optional: bool) -> Self {
Self {
kind: SegKind::Field(name),
optional,
ty,
}
}
pub fn const_index(k: f64, ty: SegType<'s>, optional: bool) -> Self {
Self {
kind: SegKind::ConstIndex(k),
optional,
ty,
}
}
pub fn var_index(name: &'s str, index_ty: IndexTy, ty: SegType<'s>, optional: bool) -> Self {
Self {
kind: SegKind::VarIndex { name, ty: index_ty },
optional,
ty,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Chain<'s> {
pub base: Base<'s>,
pub base_ty: SegType<'s>,
pub segs: &'s [Segment<'s>],
}
impl<'s> Chain<'s> {
pub fn item(segs: &'s [Segment<'s>]) -> Self {
Self {
base: Base::Item,
base_ty: SegType::Present,
segs,
}
}
pub fn local(name: &'s str, nullable: bool, segs: &'s [Segment<'s>]) -> Self {
Self {
base: Base::Local(name),
base_ty: if nullable {
SegType::Optional
} else {
SegType::Present
},
segs,
}
}
pub fn params(nullable: bool, segs: &'s [Segment<'s>]) -> Self {
Self {
base: Base::Params,
base_ty: if nullable {
SegType::Optional
} else {
SegType::Present
},
segs,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Severity {
Error,
Warning,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Code {
NonOptOnOptional,
DynamicKeyOnStruct,
MapNonCanonicalIndex,
MapValueMixed,
ChainHasCall,
NullStrict,
NameCollisionUnresolved,
RedundantOptionalChain,
}
impl Code {
pub fn as_str(self) -> &'static str {
match self {
Code::NonOptOnOptional => "E_NONOPT_ON_OPTIONAL",
Code::DynamicKeyOnStruct => "E_DYN_KEY_ON_STRUCT",
Code::MapNonCanonicalIndex => "E_MAP_NONCANON_INDEX",
Code::MapValueMixed => "E_MAP_VALUE_MIXED",
Code::ChainHasCall => "E_CHAIN_HAS_CALL",
Code::NullStrict => "E_NULL_STRICT",
Code::NameCollisionUnresolved => "E_NAME_UNRESOLVED",
Code::RedundantOptionalChain => "W_REDUNDANT_CHAIN",
}
}
pub fn severity(self) -> Severity {
match self {
Code::RedundantOptionalChain => Severity::Warning,
_ => Severity::Error,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Diagnostic {
code: Code,
segment: Option<usize>,
offset: Option<usize>,
message: String,
suggestion: Option<String>,
}
impl Diagnostic {
pub fn new(code: Code, message: impl Into<String>) -> Self {
Self {
code,
segment: None,
offset: None,
message: message.into(),
suggestion: None,
}
}
#[must_use]
pub fn with_segment(mut self, segment: usize) -> Self {
self.segment = Some(segment);
self
}
#[must_use]
pub fn with_offset(mut self, offset: usize) -> Self {
self.offset = Some(offset);
self
}
#[must_use]
pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
self.suggestion = Some(suggestion.into());
self
}
pub fn code(&self) -> Code {
self.code
}
pub fn code_str(&self) -> &'static str {
self.code.as_str()
}
pub fn severity(&self) -> Severity {
self.code.severity()
}
pub fn segment(&self) -> Option<usize> {
self.segment
}
pub fn offset(&self) -> Option<usize> {
self.offset
}
pub fn message(&self) -> &str {
&self.message
}
pub fn suggestion(&self) -> Option<&str> {
self.suggestion.as_deref()
}
}
impl fmt::Display for Diagnostic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.code.as_str(), self.message)?;
if let Some(s) = &self.suggestion {
write!(f, " 建议:{s}")?;
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Step<'s> {
Field(&'s str),
OptField(&'s str),
MapField(&'s str),
Index(usize),
VarIndex(IndexTy),
}
impl Step<'_> {
pub fn is_option(&self) -> bool {
!matches!(self, Step::Field(_))
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ChainPlan<'s> {
steps: Vec<Step<'s>>,
returns_option: bool,
constant_undefined: bool,
diagnostics: Vec<Diagnostic>,
}
impl<'s> ChainPlan<'s> {
pub fn steps(&self) -> &[Step<'s>] {
&self.steps
}
pub fn returns_option(&self) -> bool {
self.returns_option
}
pub fn is_constant_undefined(&self) -> bool {
self.constant_undefined
}
pub fn diagnostics(&self) -> &[Diagnostic] {
&self.diagnostics
}
pub fn has_errors(&self) -> bool {
self.diagnostics
.iter()
.any(|d| d.severity() == Severity::Error)
}
pub fn has_warnings(&self) -> bool {
self.diagnostics
.iter()
.any(|d| d.severity() == Severity::Warning)
}
}
pub fn plan<'s>(chain: &Chain<'s>) -> ChainPlan<'s> {
let mut steps = Vec::with_capacity(chain.segs.len());
let mut diagnostics = Vec::new();
let mut returns_option = chain.segs.is_empty() && chain.base_ty.is_nullable();
let mut constant_undefined = false;
for (i, seg) in chain.segs.iter().enumerate() {
let container_ty = if i == 0 {
chain.base_ty
} else {
chain.segs[i - 1].ty
};
if let Some(value) = container_ty.map_value() {
if let Some(d) = mixed_map_value(value) {
diagnostics.push(d.with_segment(i));
}
}
let container_nullable = container_ty.is_nullable();
let folds_undefined = match seg.kind {
SegKind::ConstIndex(k) => {
!matches!(container_ty, SegType::Map(_) | SegType::OptMap(_))
&& noncanonical_index(k)
}
_ => false,
};
if container_nullable && !seg.optional {
diagnostics.push(
Diagnostic::new(
Code::NonOptOnOptional,
format!(
"`{}` 的容器可空却没写可选链,缺失时会抛 TypeError",
render_path(chain)
),
)
.with_segment(i)
.with_suggestion(format!("改为 {}", render_path_opt(chain, i))),
);
}
if seg.optional
&& !container_nullable
&& container_ty != SegType::Unknown
&& !folds_undefined
{
diagnostics.push(
Diagnostic::new(
Code::RedundantOptionalChain,
format!("`{}` 的容器非空,`?.` 是多余的", render_path(chain)),
)
.with_segment(i)
.with_suggestion("去掉该段的 `?.`"),
);
}
if folds_undefined {
constant_undefined = true;
break;
}
if let SegKind::ConstIndex(k) = seg.kind {
if matches!(container_ty, SegType::Map(_) | SegType::OptMap(_)) && noncanonical_index(k)
{
diagnostics.push(
Diagnostic::new(
Code::MapNonCanonicalIndex,
format!("字典上的数字键 `{k}` 不是规范数组下标,请改写成字符串键"),
)
.with_segment(i)
.with_suggestion(format!("把 `[{k}]` 改成 `[\"{k}\"]`")),
);
break;
}
}
match seg.kind {
SegKind::Field(name) => {
if container_ty.map_value().is_some() {
steps.push(Step::MapField(name));
returns_option = true;
} else if seg.ty.is_nullable() {
steps.push(Step::OptField(name));
} else {
steps.push(Step::Field(name));
}
}
SegKind::ConstIndex(k) => {
steps.push(Step::Index(k as usize));
returns_option = true;
}
SegKind::VarIndex { name, ty } => {
match container_ty {
SegType::Map(_) | SegType::OptMap(_) => {}
SegType::Unknown => {}
_ => diagnostics.push(
Diagnostic::new(
Code::DynamicKeyOnStruct,
format!(
"变量键 `[{name}]` 打在定型 struct 上,只能在 `Object.<string, T>` 上使用"
),
)
.with_segment(i)
.with_suggestion("补 JSDoc `Object.<string, T>`,或把键改成静态字段名"),
),
}
steps.push(Step::VarIndex(ty));
returns_option = true;
}
}
if container_nullable || seg.ty.is_nullable() {
returns_option = true;
}
}
ChainPlan {
steps,
returns_option,
constant_undefined,
diagnostics,
}
}
fn noncanonical_index(k: f64) -> bool {
k.is_nan() || k < 0.0 || k.fract() != 0.0 || k >= MAX_ARRAY_INDEX
}
pub fn render_path(chain: &Chain<'_>) -> String {
render_path_inner(chain, None)
}
fn render_path_opt(chain: &Chain<'_>, idx: usize) -> String {
render_path_inner(chain, Some(idx))
}
fn render_path_inner(chain: &Chain<'_>, force_optional: Option<usize>) -> String {
let mut out = String::from(chain.base.name());
for (i, seg) in chain.segs.iter().enumerate() {
let optional = seg.optional || force_optional == Some(i);
let dot = if optional { "?." } else { "." };
match seg.kind {
SegKind::Field(name) => {
out.push_str(dot);
out.push_str(name);
}
SegKind::ConstIndex(k) => {
let bracket = if optional { "?.[" } else { "[" };
out.push_str(&format!("{bracket}{k}]"));
}
SegKind::VarIndex { name, .. } => {
let bracket = if optional { "?.[" } else { "[" };
out.push_str(&format!("{bracket}{name}]"));
}
}
}
out
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GeneratedName {
pub fn_name: String,
pub js_path: String,
}
impl GeneratedName {
pub fn fn_name(&self) -> &str {
&self.fn_name
}
pub fn js_path(&self) -> &str {
&self.js_path
}
}
pub fn assign_names(chains: &[Chain<'_>]) -> Result<Vec<GeneratedName>, Diagnostic> {
let mut order: Vec<(String, usize)> = chains
.iter()
.enumerate()
.map(|(i, c)| (chain_key(c), i))
.collect();
order.sort();
let mut names: Vec<String> = vec![String::new(); chains.len()];
let mut paths: Vec<String> = vec![String::new(); chains.len()];
let mut used: BTreeSet<String> = BTreeSet::new();
let mut start = 0usize;
while start < order.len() {
let mut end = start + 1;
while end < order.len() && order[end].0 == order[start].0 {
end += 1;
}
let idx = order[start].1;
let name = fresh_name(
chains.get(idx).ok_or_else(|| {
Diagnostic::new(Code::NameCollisionUnresolved, "内部错误:链下标越界")
})?,
&used,
)?;
let path = render_path(&chains[idx]);
used.insert(name.clone());
for &(_, i) in &order[start..end] {
names[i] = name.clone();
paths[i] = path.clone();
}
start = end;
}
Ok(names
.into_iter()
.zip(paths)
.map(|(fn_name, js_path)| GeneratedName { fn_name, js_path })
.collect())
}
fn chain_key(chain: &Chain<'_>) -> String {
let mut out = String::new();
match chain.base {
Base::Item => out.push_str("I:"),
Base::Params => out.push_str("P:"),
Base::Local(name) => {
out.push_str("L:");
out.push_str(&format!("{}:", name.len()));
out.push_str(name);
out.push(':');
}
}
out.push_str(if chain.base_ty.is_nullable() {
"opt"
} else {
"req"
});
push_type_key(&mut out, chain.base_ty);
for seg in chain.segs {
out.push('|');
if seg.optional {
out.push('?');
}
push_type_key(&mut out, seg.ty);
match seg.kind {
SegKind::Field(name) => {
out.push('.');
out.push_str(&format!("{}:", name.len()));
out.push_str(name);
}
SegKind::ConstIndex(k) => {
out.push('#');
out.push_str(&format!("{k}"));
}
SegKind::VarIndex { name, ty } => {
out.push('$');
out.push_str(&format!("{}:", name.len()));
out.push_str(name);
out.push(':');
out.push_str(ty.key());
}
}
}
out
}
fn push_type_key(out: &mut String, ty: SegType<'_>) {
match ty {
SegType::Present => out.push('r'),
SegType::Optional => out.push('o'),
SegType::Unknown => out.push('u'),
SegType::Map(value) => push_map_key(out, 'm', value),
SegType::OptMap(value) => push_map_key(out, 'M', value),
}
}
fn push_map_key(out: &mut String, tag: char, value: &str) {
out.push(tag);
out.push('(');
out.push_str(&format!("{}:", value.len()));
out.push_str(value);
out.push(')');
}
fn fresh_name(chain: &Chain<'_>, used: &BTreeSet<String>) -> Result<String, Diagnostic> {
let mut base = base_name(chain);
if reserved(&base) {
base.push_str("_v");
}
if !used.contains(&base) {
return Ok(base);
}
for n in 2..=6u32 {
let candidate = format!("{base}__{n}");
if !used.contains(&candidate) {
return Ok(candidate);
}
}
Err(Diagnostic::new(
Code::NameCollisionUnresolved,
format!("`{base}` 的命名冲突已消歧到 `__6`,请人工指定函数名"),
))
}
fn base_name(chain: &Chain<'_>) -> String {
if chain.segs.is_empty() {
let raw = chain.base.name();
let mut out = snake(raw);
if out.is_empty() || out == "_" || out.as_bytes().first().is_some_and(u8::is_ascii_digit) {
out.insert_str(0, "f_");
}
return out;
}
let mut out = String::new();
for (i, seg) in chain.segs.iter().enumerate() {
if i > 0 {
out.push('_');
}
match seg.kind {
SegKind::Field(name) => out.push_str(&snake(name)),
SegKind::ConstIndex(k) if !noncanonical_index(k) => {
out.push_str(&format!("i{}", k as u64));
}
SegKind::ConstIndex(_) => out.push_str("i_invalid"),
SegKind::VarIndex { .. } => out.push_str("at"),
}
}
if out.is_empty() || out == "_" || out.as_bytes().first().is_some_and(u8::is_ascii_digit) {
out.insert_str(0, "f_");
}
out
}
fn snake(s: &str) -> String {
let chars: Vec<char> = s.chars().collect();
let mut out = String::with_capacity(s.len() + 4);
for (i, &c) in chars.iter().enumerate() {
if c.is_ascii_uppercase() {
let prev = i.checked_sub(1).map(|j| chars[j]);
let next = chars.get(i + 1).copied();
let boundary = i > 0
&& (prev.is_some_and(|p| p.is_ascii_lowercase() || p.is_ascii_digit())
|| (prev.is_some_and(|p| p.is_ascii_uppercase())
&& next.is_some_and(|n| n.is_ascii_lowercase())));
if boundary {
out.push('_');
}
out.push(c.to_ascii_lowercase());
} else if c.is_ascii_alphanumeric() || c == '_' {
out.push(c);
} else {
out.push('_');
}
}
out
}
fn reserved(name: &str) -> bool {
const RESERVED: &[&str] = &[
"as",
"async",
"await",
"break",
"const",
"continue",
"crate",
"dyn",
"else",
"enum",
"extern",
"false",
"fn",
"for",
"if",
"impl",
"in",
"let",
"loop",
"match",
"mod",
"move",
"mut",
"pub",
"ref",
"return",
"self",
"static",
"struct",
"super",
"trait",
"true",
"type",
"unsafe",
"use",
"where",
"while",
"yield",
"clone",
"eq",
"ne",
"cmp",
"partial_cmp",
"hash",
"fmt",
"default",
"new",
"from",
"into",
"try_from",
"borrow",
"deref",
"index",
"get",
"iter",
"len",
"is_empty",
"to_string",
"serialize",
"deserialize",
"Self",
"abstract",
"become",
"box",
"do",
"final",
"macro",
"override",
"priv",
"typeof",
"unsized",
"virtual",
"try",
"gen",
];
RESERVED.contains(&name)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WhitelistedMethod {
Includes,
IndexOf,
Some,
StartsWith,
EndsWith,
Length,
}
pub fn check_method(name: &str) -> Result<WhitelistedMethod, Diagnostic> {
whitelisted_method(name).ok_or_else(|| {
Diagnostic::new(
Code::ChainHasCall,
format!("方法 `{name}` 不在白名单内,链上只允许纯读取方法"),
)
.with_suggestion(
"改用白名单方法(includes/indexOf/some/startsWith/endsWith),或把这部分移到业务层",
)
})
}
pub fn whitelisted_method(name: &str) -> Option<WhitelistedMethod> {
Some(match name {
"includes" => WhitelistedMethod::Includes,
"indexOf" => WhitelistedMethod::IndexOf,
"some" => WhitelistedMethod::Some,
"startsWith" => WhitelistedMethod::StartsWith,
"endsWith" => WhitelistedMethod::EndsWith,
"length" => WhitelistedMethod::Length,
_ => return None,
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MapType<'s> {
value: &'s str,
nullable: bool,
}
impl<'s> MapType<'s> {
pub fn value(&self) -> &'s str {
self.value
}
pub fn is_nullable(&self) -> bool {
self.nullable
}
pub fn seg_type(&self) -> SegType<'s> {
if self.nullable {
SegType::OptMap(self.value)
} else {
SegType::Map(self.value)
}
}
}
pub fn jsdoc_map(jsdoc: &str) -> Result<Option<MapType<'_>>, Diagnostic> {
let (t, nullable) = strip_wrappers_and_union(jsdoc.trim());
let (key, value) = if let Some(rest) = object_generic(t) {
let Some(rest) = rest.strip_suffix('>') else {
return Ok(None);
};
match split_top_level(rest) {
Some((k, v)) => (k, v),
None => return Ok(None),
}
} else if let Some(rest) = t.strip_prefix('[') {
let Some((head, tail)) = rest.split_once(']') else {
return Ok(None);
};
let Some((_, key_ty)) = head.split_once(':') else {
return Ok(None);
};
let tail = tail.strip_prefix(':').map_or("", str::trim);
(key_ty, tail)
} else {
return Ok(None);
};
if !key.trim().eq_ignore_ascii_case("string") {
return Ok(None);
}
let value = peel_parens(value.trim());
if value.is_empty() || !brackets_balanced(value) {
return Ok(None);
}
if matches!(
value.to_ascii_lowercase().as_str(),
"null" | "undefined" | "void"
) {
return Ok(None);
}
if has_top_level_separator(value) {
return Err(mixed(value));
}
Ok(Some(MapType { value, nullable }))
}
fn strip_wrappers_and_union(mut t: &str) -> (&str, bool) {
let mut nullable = false;
for _ in 0..3 {
let inner = strip_outer_braces(t);
let stripped = inner != t;
t = inner;
let (ty, nul) = split_nullable_union(t);
let unioned = !std::ptr::eq(ty, t);
if unioned {
nullable |= nul;
t = ty;
}
if !stripped && !unioned {
break;
}
}
(t, nullable)
}
fn strip_outer_braces(s: &str) -> &str {
for (open, close) in [('{', '}'), ('(', ')')] {
if let Some(inner) = s.strip_prefix(open).and_then(|x| x.strip_suffix(close)) {
let mut depth = 0i32;
for c in inner.chars() {
if c == open {
depth += 1;
} else if c == close {
depth -= 1;
if depth < 0 {
return s;
}
}
}
if depth == 0 {
return inner.trim();
}
}
}
s
}
fn split_nullable_union(s: &str) -> (&str, bool) {
let mut depth = 0i32;
let mut start = 0usize;
let mut members: Vec<&str> = Vec::new();
for (i, c) in s.char_indices() {
match c {
'{' | '[' | '(' | '<' => depth += 1,
'}' | ']' | ')' | '>' => depth -= 1,
'|' if depth == 0 => {
members.push(s[start..i].trim());
start = i + 1;
}
_ => {}
}
}
if members.is_empty() {
return (s, false);
}
members.push(s[start..].trim());
let mut non_null = members.iter().copied().filter(|m| {
!matches!(
m.to_ascii_lowercase().as_str(),
"null" | "undefined" | "void"
)
});
let (Some(only), None) = (non_null.next(), non_null.next()) else {
return (s, false);
};
if only.is_empty() {
return (s, false);
}
(only, true)
}
fn object_generic(s: &str) -> Option<&str> {
["Object.<", "Object<", "object.<", "object<"]
.iter()
.find_map(|p| s.strip_prefix(p))
}
fn brackets_balanced(s: &str) -> bool {
let mut depth = 0i32;
for c in s.chars() {
match c {
'<' => depth += 1,
'>' => {
depth -= 1;
if depth < 0 {
return false;
}
}
_ => {}
}
}
depth == 0
}
fn mixed(value: &str) -> Diagnostic {
Diagnostic::new(
Code::MapValueMixed,
format!("`Object.<string, {value}>` 的元素类型不唯一,`Map<String, T>` 要求单一 T"),
)
.with_suggestion("拆成两个字段,或把元素类型收窄成具体类型")
}
fn peel_parens(mut s: &str) -> &str {
loop {
let inner = strip_outer_braces(s);
if inner != s && s.starts_with('(') && s.ends_with(')') {
s = inner;
} else {
return s;
}
}
}
fn split_top_level(s: &str) -> Option<(&str, &str)> {
let mut depth = 0i32;
for (i, c) in s.char_indices() {
match c {
'{' | '[' | '(' | '<' => depth += 1,
'}' | ']' | ')' | '>' => depth -= 1,
',' if depth == 0 => return Some((&s[..i], &s[i + 1..])),
_ => {}
}
}
None
}
fn has_top_level_separator(s: &str) -> bool {
let mut depth = 0i32;
for c in s.chars() {
match c {
'{' | '[' | '(' | '<' => depth += 1,
'}' | ']' | ')' | '>' => depth -= 1,
'|' | ',' if depth == 0 => return true,
_ => {}
}
}
false
}
fn mixed_map_value(value: &str) -> Option<Diagnostic> {
if has_top_level_separator(value) {
Some(mixed(value))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
fn seg(name: &'static str, ty: SegType<'static>, optional: bool) -> Segment<'static> {
Segment::field(name, ty, optional)
}
#[test]
fn present_chain_needs_no_option() {
let segs = [
seg("status", SegType::Present, false),
seg("status_id", SegType::Present, false),
];
let c = Chain::item(&segs);
let p = plan(&c);
assert_eq!(
p.steps(),
&[Step::Field("status"), Step::Field("status_id")]
);
assert!(!p.returns_option());
assert!(p.diagnostics().is_empty());
}
#[test]
fn optional_middle_requires_chain_operator() {
let segs = [
seg("detail", SegType::Optional, false),
seg("info", SegType::Present, false),
];
let p = plan(&Chain::item(&segs));
assert_eq!(p.diagnostics().len(), 1);
assert_eq!(p.diagnostics()[0].code(), Code::NonOptOnOptional);
assert_eq!(p.diagnostics()[0].segment(), Some(1));
assert!(
p.diagnostics()[0]
.suggestion()
.is_some_and(|s| s.contains("item.detail?.info"))
);
}
#[test]
fn optional_middle_with_operator_is_fine() {
let segs = [
seg("detail", SegType::Optional, false),
seg("info", SegType::Present, true),
];
let p = plan(&Chain::item(&segs));
assert_eq!(p.steps(), &[Step::OptField("detail"), Step::Field("info")]);
assert!(p.returns_option());
assert!(p.diagnostics().is_empty());
}
#[test]
fn optional_leaf_is_allowed_without_operator() {
let segs = [seg("code", SegType::Optional, false)];
let p = plan(&Chain::item(&segs));
assert!(p.returns_option());
assert!(p.diagnostics().is_empty(), "叶段可空是正常形态");
}
#[test]
fn redundant_operator_is_a_warning() {
let segs = [
seg("status", SegType::Present, false),
seg("status_id", SegType::Present, true),
];
let p = plan(&Chain::item(&segs));
assert_eq!(p.diagnostics()[0].code(), Code::RedundantOptionalChain);
assert_eq!(p.diagnostics()[0].severity(), Severity::Warning);
assert!(!p.has_errors());
}
#[test]
fn nullable_base_requires_operator_on_first_segment() {
let segs = [seg("code", SegType::Present, false)];
let p = plan(&Chain::params(true, &segs));
assert_eq!(p.diagnostics()[0].code(), Code::NonOptOnOptional);
assert!(
p.diagnostics()[0]
.suggestion()
.is_some_and(|s| s.contains("params?.code"))
);
}
#[test]
fn negative_and_fractional_const_index_fold_to_undefined() {
let neg = [Segment::const_index(-1.0, SegType::Present, true)];
let p = plan(&Chain::item(&neg));
assert!(p.is_constant_undefined());
assert!(p.steps().is_empty());
let frac = [Segment::const_index(1.5, SegType::Present, false)];
assert!(plan(&Chain::item(&frac)).is_constant_undefined());
let ok = [Segment::const_index(3.0, SegType::Present, false)];
let p = plan(&Chain::item(&ok));
assert_eq!(p.steps(), &[Step::Index(3)]);
let huge = [Segment::const_index(1e300, SegType::Present, false)];
let p = plan(&Chain::item(&huge));
assert!(p.is_constant_undefined());
assert!(p.steps().is_empty());
}
#[test]
fn map_noncanonical_numeric_key_is_an_error_not_undefined() {
for k in [-1.0, 1.5, 1e300] {
let segs = [
seg("tags", SegType::Map("string"), false),
Segment::const_index(k, SegType::Present, false),
];
let p = plan(&Chain::item(&segs));
assert!(!p.is_constant_undefined(), "map key {k}");
assert!(p.has_errors(), "map key {k}");
assert_eq!(
p.diagnostics()[0].code(),
Code::MapNonCanonicalIndex,
"map key {k}"
);
}
let ok = [
seg("tags", SegType::Map("string"), false),
Segment::const_index(2.0, SegType::Present, false),
];
let p = plan(&Chain::item(&ok));
assert!(!p.has_errors());
assert_eq!(p.steps()[1], Step::Index(2));
}
#[test]
fn dynamic_key_on_struct_is_error_but_on_map_is_fine() {
let map_segs = [
seg("tags", SegType::Map("string"), false),
Segment::var_index("k", IndexTy::I64, SegType::Present, false),
];
let p = plan(&Chain::item(&map_segs));
assert!(p.diagnostics().is_empty());
assert_eq!(p.steps()[1], Step::VarIndex(IndexTy::I64));
let struct_segs = [
seg("detail", SegType::Present, false),
Segment::var_index("k", IndexTy::I64, SegType::Present, false),
];
let p = plan(&Chain::item(&struct_segs));
assert_eq!(p.diagnostics()[0].code(), Code::DynamicKeyOnStruct);
}
#[test]
fn map_value_mixed_is_reported() {
let segs = [
seg("m", SegType::Map("string | number"), false),
Segment::var_index("k", IndexTy::I64, SegType::Present, false),
];
let p = plan(&Chain::item(&segs));
assert_eq!(p.diagnostics()[0].code(), Code::MapValueMixed);
}
#[test]
fn names_are_deterministic_and_deduped() {
let a1 = [
seg("a", SegType::Present, false),
seg("b", SegType::Present, false),
];
let a2 = [seg("a_b", SegType::Present, false)];
let dup = [
seg("a", SegType::Present, false),
seg("b", SegType::Present, false),
];
let chains = [Chain::item(&a1), Chain::item(&a2), Chain::item(&dup)];
let names = assign_names(&chains).unwrap();
assert_eq!(names[0].fn_name(), "a_b");
assert_eq!(names[1].fn_name(), "a_b__2");
assert_eq!(names[2].fn_name(), names[0].fn_name());
assert_eq!(names[0].js_path(), "item.a.b");
}
#[test]
fn reserved_names_get_suffix() {
let segs = [seg("type", SegType::Present, false)];
let names = assign_names(&[Chain::item(&segs)]).unwrap();
assert_eq!(names[0].fn_name(), "type_v");
let clone_segs = [seg("clone", SegType::Present, false)];
let names = assign_names(&[Chain::item(&clone_segs)]).unwrap();
assert_eq!(names[0].fn_name(), "clone_v");
}
#[test]
fn camel_case_becomes_snake() {
for (field, want) in [
("orderProductName", "order_product_name"),
("fooBAR", "foo_bar"),
("XMLHttpRequest", "xml_http_request"),
("a_b", "a_b"),
] {
let segs = [seg(field, SegType::Present, false)];
let names = assign_names(&[Chain::item(&segs)]).unwrap();
assert_eq!(names[0].fn_name(), want, "字段 {field}");
}
}
#[test]
fn underscore_and_non_identifier_fields_get_prefix() {
for field in ["_", "$", "α", "€", ""] {
let segs = [seg(field, SegType::Present, false)];
let names = assign_names(&[Chain::item(&segs)]).unwrap();
let name = names[0].fn_name();
assert_ne!(name, "_", "字段 {field}");
assert!(
name.starts_with('f') || name.starts_with('_'),
"字段 {field} → {name}"
);
assert!(name.len() > 1, "字段 {field}");
}
}
#[test]
fn distinct_field_names_do_not_share_name_key() {
let piped = [seg("a|r.b", SegType::Present, false)];
let two = [
seg("a", SegType::Present, false),
seg("b", SegType::Present, false),
];
let names = assign_names(&[Chain::item(&piped), Chain::item(&two)]).unwrap();
assert_ne!(names[0].fn_name(), names[1].fn_name());
}
#[test]
fn rust_2024_reserved_names_get_suffix() {
for field in ["gen", "try", "box", "typeof", "do", "macro"] {
let segs = [seg(field, SegType::Present, false)];
let names = assign_names(&[Chain::item(&segs)]).unwrap();
assert_eq!(names[0].fn_name(), format!("{field}_v"), "字段 {field}");
}
}
#[test]
fn var_index_is_named_at() {
let segs = [Segment::var_index(
"i",
IndexTy::I64,
SegType::Present,
false,
)];
let names = assign_names(&[Chain::item(&segs)]).unwrap();
assert_eq!(names[0].fn_name(), "at");
assert_eq!(names[0].js_path(), "item[i]");
}
#[test]
fn nullability_is_part_of_the_name_key() {
let opt = [
seg("a", SegType::Present, false),
seg("b", SegType::Optional, false),
];
let req = [
seg("a", SegType::Present, false),
seg("b", SegType::Present, false),
];
let names = assign_names(&[Chain::item(&opt), Chain::item(&req)]).unwrap();
assert_ne!(names[0].fn_name(), names[1].fn_name());
let dup = [
seg("a", SegType::Present, false),
seg("b", SegType::Optional, false),
];
let names = assign_names(&[Chain::item(&opt), Chain::item(&dup)]).unwrap();
assert_eq!(names[0].fn_name(), names[1].fn_name());
}
#[test]
fn mixed_bases_never_share_a_name() {
let segs = [seg("a", SegType::Present, false)];
let chains = [
Chain::item(&segs),
Chain::params(true, &segs),
Chain::local("x", false, &segs),
];
let names = assign_names(&chains).unwrap();
assert_ne!(names[0].fn_name(), names[1].fn_name());
assert_ne!(names[1].fn_name(), names[2].fn_name());
assert_eq!(names[2].js_path(), "x.a");
}
#[test]
fn empty_chain_follows_base_nullability() {
let empty: &[Segment<'_>] = &[];
assert!(!plan(&Chain::item(empty)).returns_option());
assert!(plan(&Chain::params(true, empty)).returns_option());
assert!(plan(&Chain::local("x", true, empty)).returns_option());
}
#[test]
fn method_check_returns_a_diagnostic() {
assert_eq!(check_method("includes"), Ok(WhitelistedMethod::Includes));
let err = check_method("toUpperCase").unwrap_err();
assert_eq!(err.code(), Code::ChainHasCall);
assert_eq!(err.code_str(), "E_CHAIN_HAS_CALL");
assert!(err.suggestion().is_some());
}
#[test]
fn local_base_renders_its_variable_name() {
let segs = [
seg("a", SegType::Optional, false),
seg("b", SegType::Present, false),
];
let chain = Chain::local("row", false, &segs);
assert_eq!(render_path(&chain), "row.a.b");
assert_eq!(
plan(&chain).diagnostics()[0].suggestion(),
Some("改为 row.a?.b")
);
assert_eq!(assign_names(&[chain]).unwrap()[0].fn_name(), "a_b");
}
#[test]
fn jsdoc_map_forms() {
assert_eq!(
jsdoc_map("Object.<string, string>")
.unwrap()
.map(|m| m.value()),
Some("string")
);
assert_eq!(
jsdoc_map("{Object<string, number>}")
.unwrap()
.map(|m| m.value()),
Some("number")
);
assert_eq!(
jsdoc_map("{[k: string]: Foo}").unwrap().map(|m| m.value()),
Some("Foo")
);
assert!(jsdoc_map("Object.<number, string>").unwrap().is_none());
let e = jsdoc_map("Object.<string, string|number>").unwrap_err();
assert_eq!(e.code(), Code::MapValueMixed);
assert_eq!(
jsdoc_map("Object.<string, {a: number, b: string}>")
.unwrap()
.map(|m| m.value()),
Some("{a: number, b: string}")
);
}
#[test]
fn whitelist_entries() {
assert_eq!(
whitelisted_method("includes"),
Some(WhitelistedMethod::Includes)
);
assert_eq!(whitelisted_method("toLowerCase"), None);
assert_eq!(Code::ChainHasCall.as_str(), "E_CHAIN_HAS_CALL");
}
#[test]
fn render_path_marks_optional_segments() {
let segs = [
seg("detail", SegType::Optional, false),
Segment::const_index(0.0, SegType::Present, true),
seg("name", SegType::Present, false),
];
assert_eq!(render_path(&Chain::item(&segs)), "item.detail?.[0].name");
}
#[test]
fn local_base_collisions_and_invalid_names() {
let segs = [seg("foo", SegType::Present, false)];
let names =
assign_names(&[Chain::item(&segs), Chain::local("item", false, &segs)]).unwrap();
assert_ne!(names[0].fn_name(), names[1].fn_name());
for (raw, want) in [("_", "f__"), ("$", "f__"), ("1bad", "f_1bad"), ("", "f_")] {
let empty = [];
let got = assign_names(&[Chain::local(raw, false, &empty)]).unwrap();
assert_eq!(got[0].fn_name(), want, "local({raw:?})");
}
}
#[test]
fn map_noncanonical_index_truncates_steps() {
let segs = [
seg("m", SegType::Map("string"), false),
Segment::const_index(1e300, SegType::Present, false),
];
let p = plan(&Chain::item(&segs));
assert!(p.has_errors());
assert_eq!(p.steps(), &[Step::Field("m")]);
}
#[test]
fn field_on_map_returns_option() {
let segs = [
seg("tags", SegType::Map("string"), false),
seg("foo", SegType::Present, false),
];
let p = plan(&Chain::item(&segs));
assert_eq!(p.steps()[1], Step::MapField("foo"));
assert!(p.steps()[1].is_option());
assert!(p.returns_option());
}
#[test]
fn folded_index_does_not_hide_optional_type_error() {
let segs = [
seg("detail", SegType::Optional, false),
Segment::const_index(-1.0, SegType::Present, false),
];
let p = plan(&Chain::item(&segs));
assert!(p.is_constant_undefined());
assert!(p.has_errors());
assert_eq!(p.diagnostics()[0].code(), Code::NonOptOnOptional);
let ok = [
seg("detail", SegType::Optional, false),
Segment::const_index(-1.0, SegType::Present, true),
];
let p = plan(&Chain::item(&ok));
assert!(p.is_constant_undefined());
assert!(!p.has_warnings());
assert!(p.diagnostics().is_empty());
}
#[test]
fn index_names_use_real_array_bounds() {
let big = [Segment::const_index(1e300, SegType::Present, false)];
let real = [Segment::const_index(
18446744073709551615.0,
SegType::Present,
false,
)];
let names = assign_names(&[Chain::item(&big), Chain::item(&real)]).unwrap();
assert_eq!(names[0].fn_name(), "i_invalid");
assert_eq!(names[1].fn_name(), "i_invalid__2");
let zero = [Segment::const_index(0.0, SegType::Present, false)];
assert_eq!(
assign_names(&[Chain::item(&zero)]).unwrap()[0].fn_name(),
"i0"
);
let top = [Segment::const_index(
MAX_ARRAY_INDEX,
SegType::Present,
false,
)];
assert_eq!(
assign_names(&[Chain::item(&top)]).unwrap()[0].fn_name(),
"i_invalid"
);
}
#[test]
fn map_value_name_cannot_inject_dedup_key() {
let a_segs = [seg("y)", SegType::Present, false)];
let b_segs: [Segment; 0] = [];
let a = Chain {
base: Base::Item,
base_ty: SegType::Map("x"),
segs: &a_segs,
};
let b = Chain {
base: Base::Item,
base_ty: SegType::Map("x)|r.2:y"),
segs: &b_segs,
};
let names = assign_names(&[a, b]).unwrap();
assert_ne!(names[0].fn_name(), names[1].fn_name());
}
#[test]
fn mixed_map_value_is_diagnosed_for_every_access_shape() {
for segs in [
vec![
seg("m", SegType::Map("string | number"), false),
seg("foo", SegType::Present, false),
],
vec![
seg("m", SegType::Map("string | number"), false),
Segment::const_index(0.0, SegType::Present, false),
],
vec![
seg("m", SegType::Map("string | number"), false),
Segment::var_index("k", IndexTy::I64, SegType::Present, false),
],
] {
let p = plan(&Chain::item(&segs));
assert!(
p.diagnostics()
.iter()
.any(|d| d.code() == Code::MapValueMixed),
"{segs:?}"
);
}
}
}