use nativeview_view_syntax::{
ByteSpan, ElementNode, IfCond, Lex, ParsedViewCall, StringAnalysis, ViewArg, ViewBlock,
ViewNode, scan_lex_views, workspace_rel_file,
};
use super::ViewDiffOutcome;
use super::patch::{TypedViewPatch, ViewAnchorTarget, ViewTextChange};
use super::props::diff_direct_root_args;
use super::tokens::{
compute_call_nesting, lex_streams_equal, match_tokens_skipping_spans, single_string_token,
token_range_for_span,
};
pub fn diff_view_source(
rel_file: &str,
old_src: &str,
new_src: &str,
generation: u64,
) -> ViewDiffOutcome {
if old_src == new_src {
return ViewDiffOutcome::NoOp;
}
let old_lex = match Lex::tokenize(old_src) {
Ok(lex) => lex,
Err(err) => {
return ViewDiffOutcome::NeedsRebuild {
reason: format!("baseline lex error: {err:?}"),
};
}
};
let new_lex = match Lex::tokenize(new_src) {
Ok(lex) => lex,
Err(err) => {
return ViewDiffOutcome::NeedsRebuild {
reason: format!("syntax error: {err:?}"),
};
}
};
if lex_streams_equal(&old_lex, &new_lex) {
return ViewDiffOutcome::NoOp;
}
let norm_rel = workspace_rel_file(rel_file, "");
let old_calls = scan_lex_views(&old_lex, &norm_rel);
let new_calls = scan_lex_views(&new_lex, &norm_rel);
diff_scanned_views(&old_lex, &new_lex, &old_calls, &new_calls, generation)
}
pub(super) fn diff_scanned_views(
old_lex: &Lex<'_>,
new_lex: &Lex<'_>,
old_calls: &[ParsedViewCall],
new_calls: &[ParsedViewCall],
generation: u64,
) -> ViewDiffOutcome {
if old_calls.len() != new_calls.len() {
return ViewDiffOutcome::NeedsRebuild {
reason: format!(
"view! invocation count changed ({} -> {})",
old_calls.len(),
new_calls.len()
),
};
}
if old_calls.is_empty() {
return ViewDiffOutcome::NeedsRebuild {
reason: "non-view! Rust code changed".to_owned(),
};
}
let (old_parents, old_children) = compute_call_nesting(old_calls);
let (new_parents, new_children) = compute_call_nesting(new_calls);
if old_parents != new_parents {
return ViewDiffOutcome::NeedsRebuild {
reason: "nested view! structure changed".to_owned(),
};
}
let old_top_bodies: Vec<ByteSpan> = old_calls
.iter()
.enumerate()
.filter(|(i, _)| old_parents[*i].is_none())
.map(|(_, c)| c.body_span)
.collect();
let new_top_bodies: Vec<ByteSpan> = new_calls
.iter()
.enumerate()
.filter(|(i, _)| new_parents[*i].is_none())
.map(|(_, c)| c.body_span)
.collect();
if let Err(reason) = match_tokens_skipping_spans(
old_lex,
0..old_lex.len(),
&old_top_bodies,
new_lex,
0..new_lex.len(),
&new_top_bodies,
) {
return ViewDiffOutcome::NeedsRebuild { reason };
}
let mut under_err_ancestor = vec![false; old_calls.len()];
for idx in 0..old_calls.len() {
if let Some(parent) = old_parents[idx]
&& (under_err_ancestor[parent]
|| old_calls[parent].body.is_err()
|| new_calls[parent].body.is_err())
{
under_err_ancestor[idx] = true;
}
}
let mut ctx = DiffCtx {
old_lex,
new_lex,
old_calls,
new_calls,
old_children: &old_children,
new_children: &new_children,
patch: TypedViewPatch::default(),
};
for call_idx in 0..old_calls.len() {
if old_calls[call_idx].ordinal != new_calls[call_idx].ordinal {
return ViewDiffOutcome::NeedsRebuild {
reason: "view! ordinal alignment changed".to_owned(),
};
}
if under_err_ancestor[call_idx] {
continue;
}
match (&old_calls[call_idx].body, &new_calls[call_idx].body) {
(Ok(old_root), Ok(new_root)) => {
if let Err(reason) = diff_block(&mut ctx, call_idx, old_root, new_root) {
return ViewDiffOutcome::NeedsRebuild { reason };
}
}
(Err(_), Err(_)) => {
let old_range = token_range_for_span(old_lex, old_calls[call_idx].body_span);
let new_range = token_range_for_span(new_lex, new_calls[call_idx].body_span);
if match_tokens_skipping_spans(old_lex, old_range, &[], new_lex, new_range, &[])
.is_err()
{
return ViewDiffOutcome::NeedsRebuild {
reason: "unparsed view! block changed".to_owned(),
};
}
}
(Err(err), Ok(_)) => {
return ViewDiffOutcome::NeedsRebuild {
reason: format!("baseline view! parse error: {err}"),
};
}
(Ok(_), Err(err)) => {
return ViewDiffOutcome::NeedsRebuild {
reason: format!("view! parse error: {err}"),
};
}
}
}
if ctx.patch.is_empty() {
return ViewDiffOutcome::NoOp;
}
match ctx.patch.to_template_patches(generation) {
Ok(messages) => ViewDiffOutcome::Tier1Patch {
patch: ctx.patch,
messages,
},
Err(reason) => ViewDiffOutcome::NeedsRebuild { reason },
}
}
pub(super) struct DiffCtx<'a> {
old_lex: &'a Lex<'a>,
new_lex: &'a Lex<'a>,
old_calls: &'a [ParsedViewCall],
new_calls: &'a [ParsedViewCall],
old_children: &'a [Vec<usize>],
new_children: &'a [Vec<usize>],
pub(super) patch: TypedViewPatch,
}
impl<'a> DiffCtx<'a> {
#[inline]
pub(super) fn ordinal(&self, call_idx: usize) -> u32 {
self.old_calls[call_idx].ordinal
}
#[inline]
pub(super) fn new_line(&self, byte_offset: usize) -> u32 {
self.new_lex.line_col(byte_offset).line
}
pub(super) fn single_old_string_tok(&self, span: ByteSpan) -> Option<(&'a str, bool)> {
single_string_token(self.old_lex, span)
}
pub(super) fn single_new_string_tok(&self, span: ByteSpan) -> Option<(&'a str, bool)> {
single_string_token(self.new_lex, span)
}
pub(super) fn attrs_token_equal(
&self,
call_idx: usize,
old_attrs: &[ByteSpan],
new_attrs: &[ByteSpan],
) -> bool {
old_attrs.len() == new_attrs.len()
&& old_attrs
.iter()
.zip(new_attrs.iter())
.all(|(a, b)| self.exprs_token_equal(call_idx, *a, *b))
}
pub(super) fn exprs_token_equal(
&self,
call_idx: usize,
old_span: ByteSpan,
new_span: ByteSpan,
) -> bool {
let old_range = token_range_for_span(self.old_lex, old_span);
let new_range = token_range_for_span(self.new_lex, new_span);
let old_skip: Vec<ByteSpan> = self.old_children[call_idx]
.iter()
.filter_map(|&child| {
let m = self.old_calls[child].macro_span;
(m.start >= old_span.start && m.end <= old_span.end)
.then_some(self.old_calls[child].body_span)
})
.collect();
let new_skip: Vec<ByteSpan> = self.new_children[call_idx]
.iter()
.filter_map(|&child| {
let m = self.new_calls[child].macro_span;
(m.start >= new_span.start && m.end <= new_span.end)
.then_some(self.new_calls[child].body_span)
})
.collect();
if old_skip.len() != new_skip.len() {
return false;
}
match_tokens_skipping_spans(
self.old_lex,
old_range,
&old_skip,
self.new_lex,
new_range,
&new_skip,
)
.is_ok()
}
}
fn diff_block(
ctx: &mut DiffCtx<'_>,
call_idx: usize,
old_block: &ViewBlock,
new_block: &ViewBlock,
) -> Result<(), String> {
if old_block.children.len() != new_block.children.len() {
return Err(format!(
"child count changed ({} -> {}) inside view! (line {})",
old_block.children.len(),
new_block.children.len(),
ctx.new_line(new_block.span.start)
));
}
for (old_node, new_node) in old_block.children.iter().zip(new_block.children.iter()) {
diff_node(ctx, call_idx, old_node, new_node)?;
}
Ok(())
}
fn diff_node(
ctx: &mut DiffCtx<'_>,
call_idx: usize,
old_node: &ViewNode,
new_node: &ViewNode,
) -> Result<(), String> {
if !ctx.attrs_token_equal(call_idx, old_node.attrs(), new_node.attrs()) {
return Err(format!(
"node attribute changed inside view! (line {})",
ctx.new_line(new_node.span().start)
));
}
if old_node.anchor() != new_node.anchor() {
return Err(format!(
"AST anchor path changed inside view! (line {})",
ctx.new_line(new_node.span().start)
));
}
match (old_node, new_node) {
(ViewNode::TextLit(old_t), ViewNode::TextLit(new_t)) => {
let line = ctx.new_line(new_t.span.start);
match (&old_t.analysis, &new_t.analysis) {
(StringAnalysis::Static(old_s), StringAnalysis::Static(new_s)) => {
if old_s == new_s {
return Ok(());
}
ctx.patch.text_changes.push(ViewTextChange {
target: ViewAnchorTarget {
anchor: old_t.anchor,
ordinal: ctx.ordinal(call_idx),
static_ast_path: old_t.path.clone(),
tag: "<text>".to_owned(),
test_id: None,
},
old: old_s.clone(),
new: new_s.clone(),
});
Ok(())
}
(StringAnalysis::Dynamic(a), StringAnalysis::Dynamic(b)) if a == b => Ok(()),
_ => Err(format!(
"interpolated text literal changed inside view! (line {line})"
)),
}
}
(ViewNode::Expr(old_e), ViewNode::Expr(new_e)) => {
if ctx.exprs_token_equal(call_idx, old_e.expr.span, new_e.expr.span) {
Ok(())
} else {
Err(format!(
"dynamic expression changed inside view! (line {})",
ctx.new_line(new_e.span.start)
))
}
}
(ViewNode::Element(old_el), ViewNode::Element(new_el)) => {
diff_element(ctx, call_idx, old_el, new_el)
}
(ViewNode::If(old_if), ViewNode::If(new_if)) => {
let line = ctx.new_line(new_if.span.start);
if old_if.branches.len() != new_if.branches.len()
|| old_if.else_branch.is_some() != new_if.else_branch.is_some()
{
return Err(format!("`if` branch structure changed (line {line})"));
}
for (ob, nb) in old_if.branches.iter().zip(new_if.branches.iter()) {
match (&ob.cond, &nb.cond) {
(IfCond::Expr(oe), IfCond::Expr(ne))
| (IfCond::LetChain(oe), IfCond::LetChain(ne)) => {
if !ctx.exprs_token_equal(call_idx, oe.span, ne.span) {
return Err(format!(
"`if` condition changed (line {})",
ctx.new_line(ne.span.start)
));
}
}
(
IfCond::Let {
pat: op,
expr: oe,
},
IfCond::Let {
pat: np,
expr: ne,
},
) => {
if !ctx.exprs_token_equal(call_idx, op.span, np.span)
|| !ctx.exprs_token_equal(call_idx, oe.span, ne.span)
{
return Err(format!(
"`if let` condition changed (line {})",
ctx.new_line(np.span.start)
));
}
}
_ => return Err(format!("`if` condition kind changed (line {line})")),
}
diff_block(ctx, call_idx, &ob.body, &nb.body)?;
}
if let (Some(oe), Some(ne)) = (&old_if.else_branch, &new_if.else_branch) {
diff_block(ctx, call_idx, oe, ne)?;
}
Ok(())
}
(ViewNode::Match(old_m), ViewNode::Match(new_m)) => {
let line = ctx.new_line(new_m.span.start);
if !ctx.exprs_token_equal(call_idx, old_m.scrutinee.span, new_m.scrutinee.span) {
return Err(format!("`match` scrutinee changed (line {line})"));
}
if old_m.arms.len() != new_m.arms.len() {
return Err(format!("`match` arm count changed (line {line})"));
}
for (oa, na) in old_m.arms.iter().zip(new_m.arms.iter()) {
let arm_line = ctx.new_line(na.span.start);
if !ctx.attrs_token_equal(call_idx, &oa.attrs, &na.attrs) {
return Err(format!("`match` arm attribute changed (line {arm_line})"));
}
if !ctx.exprs_token_equal(call_idx, oa.pat.span, na.pat.span) {
return Err(format!("`match` arm pattern changed (line {arm_line})"));
}
match (&oa.guard, &na.guard) {
(None, None) => {}
(Some(og), Some(ng)) if ctx.exprs_token_equal(call_idx, og.span, ng.span) => {}
_ => return Err(format!("`match` arm guard changed (line {arm_line})")),
}
diff_block(ctx, call_idx, &oa.body, &na.body)?;
}
Ok(())
}
(ViewNode::For(old_f), ViewNode::For(new_f)) => {
let line = ctx.new_line(new_f.span.start);
if !ctx.exprs_token_equal(call_idx, old_f.pat.span, new_f.pat.span)
|| !ctx.exprs_token_equal(call_idx, old_f.iter.span, new_f.iter.span)
{
return Err(format!("`for` loop header changed (line {line})"));
}
match (&old_f.key, &new_f.key) {
(None, None) => {}
(Some(ok), Some(nk)) if ctx.exprs_token_equal(call_idx, ok.span, nk.span) => {}
_ => return Err(format!("`for` loop key changed (line {line})")),
}
diff_block(ctx, call_idx, &old_f.body, &new_f.body)
}
_ => Err(format!(
"view! node kind changed structurally (line {})",
ctx.new_line(new_node.span().start)
)),
}
}
fn diff_element(
ctx: &mut DiffCtx<'_>,
call_idx: usize,
old_el: &ElementNode,
new_el: &ElementNode,
) -> Result<(), String> {
let line = ctx.new_line(new_el.span.start);
if old_el.leading_colon != new_el.leading_colon || old_el.path_segments != new_el.path_segments
{
return Err(format!(
"element tag changed (`{}{}` -> `{}{}`) (line {line})",
if old_el.leading_colon { "::" } else { "" },
old_el.path_segments.join("::"),
if new_el.leading_colon { "::" } else { "" },
new_el.path_segments.join("::"),
));
}
let generics_match = match (&old_el.generics, &new_el.generics) {
(None, None) => true,
(Some(og), Some(ng)) => ctx.exprs_token_equal(call_idx, og.span, ng.span),
_ => false,
};
if !generics_match {
return Err(format!(
"element generics changed on `{}` (line {line})",
new_el.path_segments.join("::")
));
}
if old_el.is_direct_root_patchable() && new_el.is_direct_root_patchable() {
diff_direct_root_args(ctx, call_idx, old_el, new_el)?;
} else {
verify_composite_args_unchanged(ctx, call_idx, old_el, new_el)?;
}
match (&old_el.children, &new_el.children) {
(None, None) => Ok(()),
(Some(oc), Some(nc)) => diff_block(ctx, call_idx, oc, nc),
_ => Err(format!(
"children block presence changed on `{}` (line {line})",
new_el.path_segments.join("::")
)),
}
}
fn verify_composite_args_unchanged(
ctx: &DiffCtx<'_>,
call_idx: usize,
old_el: &ElementNode,
new_el: &ElementNode,
) -> Result<(), String> {
let tag = new_el.path_segments.join("::");
let line = ctx.new_line(new_el.span.start);
let (old_args, new_args) = match (&old_el.args, &new_el.args) {
(None, None) => return Ok(()),
(Some(o), Some(n)) if o.len() == n.len() => (o, n),
_ => {
return Err(format!(
"composite component `{tag}` arguments changed (Tier-2) (line {line})"
));
}
};
for (old_arg, new_arg) in old_args.iter().zip(new_args.iter()) {
let same = match (old_arg, new_arg) {
(
ViewArg::Positional {
attrs: oa,
value: oe,
},
ViewArg::Positional {
attrs: na,
value: ne,
},
) => {
ctx.attrs_token_equal(call_idx, oa, na)
&& ctx.exprs_token_equal(call_idx, oe.span, ne.span)
}
(
ViewArg::Named {
attrs: oa,
name: on,
value: ov,
..
},
ViewArg::Named {
attrs: na,
name: nn,
value: nv,
..
},
) => {
ctx.attrs_token_equal(call_idx, oa, na)
&& on == nn
&& ctx.exprs_token_equal(call_idx, ov.span, nv.span)
}
_ => false,
};
if !same {
return Err(format!(
"composite component `{tag}` prop changed (Tier-2) (line {line})"
));
}
}
Ok(())
}