use nativeview_view_syntax::{
ElementNode, ExprSpan, StringAnalysis, ViewArg, analyze_string_literal, unescape_rust_string,
};
use crate::hot_diff::attrs::{AttrSpec, is_test_id_attr, prop_bits};
use crate::hot_diff::eval::{TypedAttrValue, evaluate, same_shape};
use crate::hot_diff::lexer::{Lex as PropLex, tokenize as prop_tokenize};
use crate::hot_diff::typed_style_chain::{ChainArgSpan, scan_typed_style_chain_with_aliases};
use super::diff::DiffCtx;
use super::patch::{ViewAnchorTarget, ViewAttrChange, ViewTextChange};
use super::prop_specs::{
DirectArgOverlap, classify_direct_arg_overlap, is_ext_gap_direct_prop,
lookup_direct_float_spec, lookup_view_direct_spec, style_expr_written_bits,
};
pub(super) fn extract_static_test_id(
ctx: &DiffCtx<'_>,
args: Option<&[ViewArg]>,
) -> Option<String> {
let args = args?;
for arg in args {
if let ViewArg::Named { name, value, .. } = arg
&& is_test_id_attr(name)
&& let Some((raw, is_raw)) = ctx.single_old_string_tok(value.span)
&& let Ok(s) = unescape_rust_string(raw, is_raw)
&& !s.is_empty()
{
return Some(s);
}
}
None
}
pub(super) fn diff_direct_root_args(
ctx: &mut DiffCtx<'_>,
call_idx: usize,
old_el: &ElementNode,
new_el: &ElementNode,
) -> Result<(), String> {
let (old_args, new_args) = match (&old_el.args, &new_el.args) {
(None, None) => return Ok(()),
(Some(o), Some(n)) => (o.as_slice(), n.as_slice()),
_ => {
return Err(format!(
"argument list presence changed on `{}` (line {})",
new_el.tag_name(),
ctx.new_line(new_el.span.start)
));
}
};
if old_args.len() != new_args.len() {
return Err(format!(
"argument count changed on `{}` (line {})",
new_el.tag_name(),
ctx.new_line(new_el.span.start)
));
}
let mut direct_bits_by_arg: Vec<u64> = Vec::with_capacity(old_args.len());
let mut all_direct_bits = 0u64;
let mut direct_always_shadowed = 0u64;
let mut has_ext_gap_direct = false;
let mut style_arg_count = 0usize;
let mut all_style_bits = 0u64;
for arg in old_args {
let bits = match arg {
ViewArg::Named { name, value, .. } if matches!(name.as_str(), "style" | "nv_style") => {
style_arg_count += 1;
all_style_bits |= style_expr_written_bits(&value.raw);
0
}
ViewArg::Named { name, .. } => {
if is_ext_gap_direct_prop(name) {
has_ext_gap_direct = true;
}
match classify_direct_arg_overlap(name) {
DirectArgOverlap::Disjoint => 0,
DirectArgOverlap::Shadow(b) => b,
DirectArgOverlap::Bidirectional(b) => {
direct_always_shadowed |= b;
b
}
}
}
ViewArg::Positional { .. } => 0,
};
direct_bits_by_arg.push(bits);
all_direct_bits |= bits;
}
let is_leaf_text = old_el
.children
.as_ref()
.is_none_or(|c| c.children.is_empty());
let ordinal = ctx.ordinal(call_idx);
let test_id = extract_static_test_id(ctx, Some(old_args));
let make_target = || ViewAnchorTarget {
anchor: old_el.anchor,
ordinal,
static_ast_path: old_el.path.clone(),
tag: old_el.tag_name().to_owned(),
test_id: test_id.clone(),
};
for (idx, (old_arg, new_arg)) in old_args.iter().zip(new_args.iter()).enumerate() {
match (old_arg, new_arg) {
(
ViewArg::Positional {
attrs: old_attrs,
value: old_expr,
},
ViewArg::Positional {
attrs: new_attrs,
value: new_expr,
},
) => {
if !ctx.attrs_token_equal(call_idx, old_attrs, new_attrs) {
return Err(format!(
"argument attribute changed on `{}` (line {})",
new_el.tag_name(),
ctx.new_line(new_expr.span.start)
));
}
if ctx.exprs_token_equal(call_idx, old_expr.span, new_expr.span) {
continue;
}
if !old_attrs.is_empty() {
return Err(format!(
"cfg-attributed argument changed (Tier-2) on `{}` (line {})",
new_el.tag_name(),
ctx.new_line(new_expr.span.start)
));
}
if idx == 0 && old_el.tag_name() == "Text" {
diff_text_arg(ctx, old_expr, new_expr, is_leaf_text, make_target())?;
} else {
return Err(format!(
"positional argument #{idx} changed on `{}` (line {})",
new_el.tag_name(),
ctx.new_line(new_expr.span.start)
));
}
}
(
ViewArg::Named {
attrs: old_attrs,
name: old_name,
value: old_expr,
..
},
ViewArg::Named {
attrs: new_attrs,
name: new_name,
value: new_expr,
..
},
) => {
if !ctx.attrs_token_equal(call_idx, old_attrs, new_attrs) {
return Err(format!(
"argument attribute changed on `{}` (line {})",
new_el.tag_name(),
ctx.new_line(new_expr.span.start)
));
}
if old_name != new_name {
return Err(format!(
"argument name changed `{old_name}` -> `{new_name}` on `{}` (line {})",
new_el.tag_name(),
ctx.new_line(new_expr.span.start)
));
}
if ctx.exprs_token_equal(call_idx, old_expr.span, new_expr.span) {
continue;
}
if !old_attrs.is_empty() {
return Err(format!(
"cfg-attributed argument changed (Tier-2) on `{}` (line {})",
new_el.tag_name(),
ctx.new_line(new_expr.span.start)
));
}
if old_el.tag_name() == "Text" && matches!(old_name.as_str(), "text" | "content") {
diff_text_arg(ctx, old_expr, new_expr, is_leaf_text, make_target())?;
} else if matches!(old_name.as_str(), "style" | "nv_style") {
if style_arg_count > 1 {
return Err(format!(
"multiple `style` arguments on `{}` changed (Tier-2) (line {})",
new_el.tag_name(),
ctx.new_line(new_expr.span.start)
));
}
diff_style_chain_arg(
ctx,
old_expr,
new_expr,
all_direct_bits,
make_target(),
)?;
} else if let Some(base_spec) = lookup_view_direct_spec(old_name) {
let later_bits = direct_bits_by_arg[idx + 1..]
.iter()
.fold(0u64, |acc, &b| acc | b);
let blocked_by_gap =
base_spec.bits == prop_bits::GAP && has_ext_gap_direct;
if blocked_by_gap
|| (base_spec.bits
& (later_bits | direct_always_shadowed | all_style_bits))
!= 0
{
return Err(format!(
"prop `{old_name}` is shadowed by another prop or `style:` on `{}` (line {})",
new_el.tag_name(),
ctx.new_line(new_expr.span.start)
));
}
diff_direct_prop_arg(
ctx,
old_name,
base_spec,
old_expr,
new_expr,
make_target(),
)?;
} else {
return Err(format!(
"non-patchable prop `{old_name}` changed on `{}` (line {})",
new_el.tag_name(),
ctx.new_line(new_expr.span.start)
));
}
}
_ => {
return Err(format!(
"argument kind changed on `{}` (line {})",
new_el.tag_name(),
ctx.new_line(new_el.span.start)
));
}
}
}
Ok(())
}
fn diff_text_arg(
ctx: &mut DiffCtx<'_>,
old_expr: &ExprSpan,
new_expr: &ExprSpan,
is_leaf_text: bool,
target: ViewAnchorTarget,
) -> Result<(), String> {
let line = ctx.new_line(new_expr.span.start);
let Some((old_raw, old_is_raw)) = ctx.single_old_string_tok(old_expr.span) else {
return Err(format!(
"dynamic `Text` baseline argument changed (line {line})"
));
};
let Some((new_raw, new_is_raw)) = ctx.single_new_string_tok(new_expr.span) else {
return Err(format!(
"dynamic `Text` argument requires Tier-2 rebuild (line {line})"
));
};
let old_analysis = analyze_string_literal(old_raw, old_is_raw)
.map_err(|e| format!("invalid baseline `Text` string literal: {e} (line {line})"))?;
let new_analysis = analyze_string_literal(new_raw, new_is_raw)
.map_err(|e| format!("invalid `Text` string literal: {e} (line {line})"))?;
match (old_analysis, new_analysis) {
(StringAnalysis::Static(old_s), StringAnalysis::Static(new_s)) => {
if old_s == new_s {
return Ok(());
}
if old_s.is_empty() && !is_leaf_text {
return Err(format!(
"empty static text literal on non-leaf `Text` cannot be patched safely (line {line})"
));
}
ctx.patch.text_changes.push(ViewTextChange {
target,
old: old_s,
new: new_s,
});
Ok(())
}
(StringAnalysis::Dynamic(a), StringAnalysis::Dynamic(b)) if a == b => Ok(()),
_ => Err(format!(
"interpolated `Text` string changed (line {line})"
)),
}
}
fn diff_style_chain_arg(
ctx: &mut DiffCtx<'_>,
old_expr: &ExprSpan,
new_expr: &ExprSpan,
direct_prop_bits: u64,
target: ViewAnchorTarget,
) -> Result<(), String> {
let line = ctx.new_line(new_expr.span.start);
let old_tokens = prop_tokenize(&old_expr.raw)
.map_err(|e| format!("baseline style expression lex error: {} (line {line})", e.as_str()))?;
let new_tokens = prop_tokenize(&new_expr.raw)
.map_err(|e| format!("style expression lex error: {} (line {line})", e.as_str()))?;
let old_lex = PropLex::new(&old_expr.raw, &old_tokens);
let new_lex = PropLex::new(&new_expr.raw, &new_tokens);
let mut old_steps: Vec<(Option<ChainArgSpan>, u64)> = Vec::new();
let mut new_steps: Vec<(Option<ChainArgSpan>, u64)> = Vec::new();
if !scan_typed_style_chain_with_aliases(old_lex, 0, old_lex.len(), &mut old_steps, true)
|| !scan_typed_style_chain_with_aliases(new_lex, 0, new_lex.len(), &mut new_steps, true)
{
return Err(format!(
"non-literal or unknown `style` expression changed (line {line})"
));
}
let old_spans: Vec<ChainArgSpan> = old_steps.into_iter().filter_map(|(s, _)| s).collect();
let new_spans: Vec<ChainArgSpan> = new_steps.into_iter().filter_map(|(s, _)| s).collect();
if old_spans.len() != new_spans.len() {
return Err(format!(
"`style` builder chain structure changed (line {line})"
));
}
let mut oi = 0usize;
let mut ni = 0usize;
for (o_sp, n_sp) in old_spans.iter().zip(new_spans.iter()) {
let (os, oe) = (o_sp.start as usize, o_sp.end as usize);
let (ns, ne) = (n_sp.start as usize, n_sp.end as usize);
if os - oi != ns - ni || !old_lex.same_range(oi, os, new_lex, ni) {
return Err(format!(
"`style` builder chain methods or non-patchable args changed (line {line})"
));
}
if o_sp.spec.name != n_sp.spec.name {
return Err(format!(
"`style` builder chain property changed (`{}` -> `{}`) (line {line})",
o_sp.spec.name, n_sp.spec.name
));
}
oi = oe;
ni = ne;
}
if old_lex.len() - oi != new_lex.len() - ni
|| !old_lex.same_range(oi, old_lex.len(), new_lex, ni)
{
return Err(format!(
"`style` builder chain suffix changed (line {line})"
));
}
for (o_sp, n_sp) in old_spans.iter().zip(new_spans.iter()) {
let (os, oe) = (o_sp.start as usize, o_sp.end as usize);
let (ns, ne) = (n_sp.start as usize, n_sp.end as usize);
if oe - os == ne - ns && old_lex.same_range(os, oe, new_lex, ns) {
continue;
}
if (o_sp.spec.bits & direct_prop_bits) != 0 {
return Err(format!(
"`style` property `{}` is shadowed by a direct prop on the same element (line {line})",
o_sp.spec.name
));
}
let old = evaluate(old_lex, os, oe).map_err(|e| {
format!(
"`{}` baseline value is not a Tier-1 constant: {} (line {line})",
o_sp.spec.name,
e.as_str()
)
})?;
record_typed_attr_change_with_old(
ctx,
o_sp.spec,
old,
old_lex,
(os, oe),
new_lex,
(ns, ne),
target.clone(),
line,
)?;
}
Ok(())
}
fn diff_direct_prop_arg(
ctx: &mut DiffCtx<'_>,
prop_name: &str,
base_spec: &'static AttrSpec,
old_expr: &ExprSpan,
new_expr: &ExprSpan,
target: ViewAnchorTarget,
) -> Result<(), String> {
let line = ctx.new_line(new_expr.span.start);
let old_tokens = prop_tokenize(&old_expr.raw)
.map_err(|e| format!("baseline `{prop_name}` lex error: {} (line {line})", e.as_str()))?;
let new_tokens = prop_tokenize(&new_expr.raw)
.map_err(|e| format!("`{prop_name}` lex error: {} (line {line})", e.as_str()))?;
let old_lex = PropLex::new(&old_expr.raw, &old_tokens);
let new_lex = PropLex::new(&new_expr.raw, &new_tokens);
let old_val = evaluate(old_lex, 0, old_lex.len()).map_err(|e| {
format!(
"`{prop_name}` baseline value is not a Tier-1 constant: {} (line {line})",
e.as_str()
)
})?;
let spec = if matches!(old_val, TypedAttrValue::Float(_)) {
lookup_direct_float_spec(prop_name).unwrap_or(base_spec)
} else {
base_spec
};
record_typed_attr_change_with_old(
ctx,
spec,
old_val,
old_lex,
(0, old_lex.len()),
new_lex,
(0, new_lex.len()),
target,
line,
)
}
#[allow(clippy::too_many_arguments)]
fn record_typed_attr_change_with_old(
ctx: &mut DiffCtx<'_>,
spec: &'static AttrSpec,
old: TypedAttrValue,
old_lex: PropLex<'_>,
old_range: (usize, usize),
new_lex: PropLex<'_>,
new_range: (usize, usize),
target: ViewAnchorTarget,
line: u32,
) -> Result<(), String> {
let name = spec.name;
let new = evaluate(new_lex, new_range.0, new_range.1).map_err(|e| {
format!(
"`{name}` value is not a Tier-1 constant: {} (line {line})",
e.as_str()
)
})?;
if !same_value_shape(old_lex, old_range, new_lex, new_range, &old) {
return Err(format!(
"`{name}` value shape changed ({old} -> {new}); Tier-1 only patches literal values \
(line {line})"
));
}
if old == new {
return Ok(());
}
if !spec.accepts_value(&new) {
return Err(format!("`{name}` does not accept {new} (line {line})"));
}
ctx.patch.attr_changes.push(ViewAttrChange {
target,
attr: spec,
old,
new,
});
Ok(())
}
fn same_value_shape(
old_lex: PropLex<'_>,
old_range: (usize, usize),
new_lex: PropLex<'_>,
new_range: (usize, usize),
old_val: &TypedAttrValue,
) -> bool {
let is_color_const = matches!(old_val, TypedAttrValue::Rgba { .. })
&& !(old_range.0..old_range.1).any(|i| old_lex.is_punct(i, b'('));
let leaf_ident = matches!(
old_val,
TypedAttrValue::Enum { .. } | TypedAttrValue::ThemeToken(_)
) || is_color_const;
same_shape(old_lex, old_range, new_lex, new_range, leaf_ident)
}