Skip to main content

nativeview_cli/view_diff/
diff.rs

1//! Whole-file `view!` AST and outer-Rust token differ powered strictly by `nativeview-view-syntax`.
2
3use nativeview_view_syntax::{
4    ByteSpan, ElementNode, IfCond, Lex, ParsedViewCall, StringAnalysis, ViewArg, ViewBlock,
5    ViewNode, scan_lex_views, workspace_rel_file,
6};
7
8use super::ViewDiffOutcome;
9use super::patch::{TypedViewPatch, ViewAnchorTarget, ViewTextChange};
10use super::props::diff_direct_root_args;
11use super::tokens::{
12    compute_call_nesting, lex_streams_equal, match_tokens_skipping_spans, single_string_token,
13    token_range_for_span,
14};
15
16/// Diffs `old_src` against `new_src` for a `.rs` file at `rel_file` containing `view! { ... }`
17/// blocks and classifies the edit as [`ViewDiffOutcome::NoOp`], [`ViewDiffOutcome::Tier1Patch`],
18/// or [`ViewDiffOutcome::NeedsRebuild`].
19pub fn diff_view_source(
20    rel_file: &str,
21    old_src: &str,
22    new_src: &str,
23    generation: u64,
24) -> ViewDiffOutcome {
25    if old_src == new_src {
26        return ViewDiffOutcome::NoOp;
27    }
28
29    let old_lex = match Lex::tokenize(old_src) {
30        Ok(lex) => lex,
31        Err(err) => {
32            return ViewDiffOutcome::NeedsRebuild {
33                reason: format!("baseline lex error: {err:?}"),
34            };
35        }
36    };
37    let new_lex = match Lex::tokenize(new_src) {
38        Ok(lex) => lex,
39        Err(err) => {
40            return ViewDiffOutcome::NeedsRebuild {
41                reason: format!("syntax error: {err:?}"),
42            };
43        }
44    };
45
46    if lex_streams_equal(&old_lex, &new_lex) {
47        return ViewDiffOutcome::NoOp;
48    }
49
50    let norm_rel = workspace_rel_file(rel_file, "");
51    let old_calls = scan_lex_views(&old_lex, &norm_rel);
52    let new_calls = scan_lex_views(&new_lex, &norm_rel);
53    diff_scanned_views(&old_lex, &new_lex, &old_calls, &new_calls, generation)
54}
55
56/// Diffs already-tokenized and already-scanned `view!` invocations (zero redundant lexing/parsing).
57pub(super) fn diff_scanned_views(
58    old_lex: &Lex<'_>,
59    new_lex: &Lex<'_>,
60    old_calls: &[ParsedViewCall],
61    new_calls: &[ParsedViewCall],
62    generation: u64,
63) -> ViewDiffOutcome {
64    if old_calls.len() != new_calls.len() {
65        return ViewDiffOutcome::NeedsRebuild {
66            reason: format!(
67                "view! invocation count changed ({} -> {})",
68                old_calls.len(),
69                new_calls.len()
70            ),
71        };
72    }
73    if old_calls.is_empty() {
74        return ViewDiffOutcome::NeedsRebuild {
75            reason: "non-view! Rust code changed".to_owned(),
76        };
77    }
78
79    let (old_parents, old_children) = compute_call_nesting(old_calls);
80    let (new_parents, new_children) = compute_call_nesting(new_calls);
81    if old_parents != new_parents {
82        return ViewDiffOutcome::NeedsRebuild {
83            reason: "nested view! structure changed".to_owned(),
84        };
85    }
86
87    // Verify every Rust token outside top-level `view! { ... }` body spans matches 1:1.
88    let old_top_bodies: Vec<ByteSpan> = old_calls
89        .iter()
90        .enumerate()
91        .filter(|(i, _)| old_parents[*i].is_none())
92        .map(|(_, c)| c.body_span)
93        .collect();
94    let new_top_bodies: Vec<ByteSpan> = new_calls
95        .iter()
96        .enumerate()
97        .filter(|(i, _)| new_parents[*i].is_none())
98        .map(|(_, c)| c.body_span)
99        .collect();
100
101    if let Err(reason) = match_tokens_skipping_spans(
102        old_lex,
103        0..old_lex.len(),
104        &old_top_bodies,
105        new_lex,
106        0..new_lex.len(),
107        &new_top_bodies,
108    ) {
109        return ViewDiffOutcome::NeedsRebuild { reason };
110    }
111
112    // Track every call nested inside an unparsed (`Err`) ancestor so no nested `view!` inside an
113    // unparsed outer `view!` can ever emit a Tier-1 patch (the ancestor compares its entire raw
114    // body token stream without skipping nested spans).
115    let mut under_err_ancestor = vec![false; old_calls.len()];
116    for idx in 0..old_calls.len() {
117        if let Some(parent) = old_parents[idx]
118            && (under_err_ancestor[parent]
119                || old_calls[parent].body.is_err()
120                || new_calls[parent].body.is_err())
121        {
122            under_err_ancestor[idx] = true;
123        }
124    }
125
126    let mut ctx = DiffCtx {
127        old_lex,
128        new_lex,
129        old_calls,
130        new_calls,
131        old_children: &old_children,
132        new_children: &new_children,
133        patch: TypedViewPatch::default(),
134    };
135
136    for call_idx in 0..old_calls.len() {
137        if old_calls[call_idx].ordinal != new_calls[call_idx].ordinal {
138            return ViewDiffOutcome::NeedsRebuild {
139                reason: "view! ordinal alignment changed".to_owned(),
140            };
141        }
142        if under_err_ancestor[call_idx] {
143            continue;
144        }
145        match (&old_calls[call_idx].body, &new_calls[call_idx].body) {
146            (Ok(old_root), Ok(new_root)) => {
147                if let Err(reason) = diff_block(&mut ctx, call_idx, old_root, new_root) {
148                    return ViewDiffOutcome::NeedsRebuild { reason };
149                }
150            }
151            (Err(_), Err(_)) => {
152                let old_range = token_range_for_span(old_lex, old_calls[call_idx].body_span);
153                let new_range = token_range_for_span(new_lex, new_calls[call_idx].body_span);
154                if match_tokens_skipping_spans(old_lex, old_range, &[], new_lex, new_range, &[])
155                    .is_err()
156                {
157                    return ViewDiffOutcome::NeedsRebuild {
158                        reason: "unparsed view! block changed".to_owned(),
159                    };
160                }
161            }
162            (Err(err), Ok(_)) => {
163                return ViewDiffOutcome::NeedsRebuild {
164                    reason: format!("baseline view! parse error: {err}"),
165                };
166            }
167            (Ok(_), Err(err)) => {
168                return ViewDiffOutcome::NeedsRebuild {
169                    reason: format!("view! parse error: {err}"),
170                };
171            }
172        }
173    }
174
175    if ctx.patch.is_empty() {
176        return ViewDiffOutcome::NoOp;
177    }
178
179    match ctx.patch.to_template_patches(generation) {
180        Ok(messages) => ViewDiffOutcome::Tier1Patch {
181            patch: ctx.patch,
182            messages,
183        },
184        Err(reason) => ViewDiffOutcome::NeedsRebuild { reason },
185    }
186}
187
188pub(super) struct DiffCtx<'a> {
189    old_lex: &'a Lex<'a>,
190    new_lex: &'a Lex<'a>,
191    old_calls: &'a [ParsedViewCall],
192    new_calls: &'a [ParsedViewCall],
193    old_children: &'a [Vec<usize>],
194    new_children: &'a [Vec<usize>],
195    pub(super) patch: TypedViewPatch,
196}
197
198impl<'a> DiffCtx<'a> {
199    #[inline]
200    pub(super) fn ordinal(&self, call_idx: usize) -> u32 {
201        self.old_calls[call_idx].ordinal
202    }
203
204    #[inline]
205    pub(super) fn new_line(&self, byte_offset: usize) -> u32 {
206        self.new_lex.line_col(byte_offset).line
207    }
208
209    pub(super) fn single_old_string_tok(&self, span: ByteSpan) -> Option<(&'a str, bool)> {
210        single_string_token(self.old_lex, span)
211    }
212
213    pub(super) fn single_new_string_tok(&self, span: ByteSpan) -> Option<(&'a str, bool)> {
214        single_string_token(self.new_lex, span)
215    }
216
217    /// Returns `true` iff two `#[...]` attribute lists have equal length and pairwise identical
218    /// Rust tokens.
219    pub(super) fn attrs_token_equal(
220        &self,
221        call_idx: usize,
222        old_attrs: &[ByteSpan],
223        new_attrs: &[ByteSpan],
224    ) -> bool {
225        old_attrs.len() == new_attrs.len()
226            && old_attrs
227                .iter()
228                .zip(new_attrs.iter())
229                .all(|(a, b)| self.exprs_token_equal(call_idx, *a, *b))
230    }
231
232    /// Returns `true` iff `old_span` and `new_span` have identical Rust tokens (ignoring comments,
233    /// whitespace, and the inner bodies of any nested `view! { ... }` calls inside them, which are
234    /// diffed independently under their own ordinals).
235    pub(super) fn exprs_token_equal(
236        &self,
237        call_idx: usize,
238        old_span: ByteSpan,
239        new_span: ByteSpan,
240    ) -> bool {
241        let old_range = token_range_for_span(self.old_lex, old_span);
242        let new_range = token_range_for_span(self.new_lex, new_span);
243
244        let old_skip: Vec<ByteSpan> = self.old_children[call_idx]
245            .iter()
246            .filter_map(|&child| {
247                let m = self.old_calls[child].macro_span;
248                (m.start >= old_span.start && m.end <= old_span.end)
249                    .then_some(self.old_calls[child].body_span)
250            })
251            .collect();
252        let new_skip: Vec<ByteSpan> = self.new_children[call_idx]
253            .iter()
254            .filter_map(|&child| {
255                let m = self.new_calls[child].macro_span;
256                (m.start >= new_span.start && m.end <= new_span.end)
257                    .then_some(self.new_calls[child].body_span)
258            })
259            .collect();
260
261        if old_skip.len() != new_skip.len() {
262            return false;
263        }
264        match_tokens_skipping_spans(
265            self.old_lex,
266            old_range,
267            &old_skip,
268            self.new_lex,
269            new_range,
270            &new_skip,
271        )
272        .is_ok()
273    }
274}
275
276fn diff_block(
277    ctx: &mut DiffCtx<'_>,
278    call_idx: usize,
279    old_block: &ViewBlock,
280    new_block: &ViewBlock,
281) -> Result<(), String> {
282    if old_block.children.len() != new_block.children.len() {
283        return Err(format!(
284            "child count changed ({} -> {}) inside view! (line {})",
285            old_block.children.len(),
286            new_block.children.len(),
287            ctx.new_line(new_block.span.start)
288        ));
289    }
290    for (old_node, new_node) in old_block.children.iter().zip(new_block.children.iter()) {
291        diff_node(ctx, call_idx, old_node, new_node)?;
292    }
293    Ok(())
294}
295
296fn diff_node(
297    ctx: &mut DiffCtx<'_>,
298    call_idx: usize,
299    old_node: &ViewNode,
300    new_node: &ViewNode,
301) -> Result<(), String> {
302    if !ctx.attrs_token_equal(call_idx, old_node.attrs(), new_node.attrs()) {
303        return Err(format!(
304            "node attribute changed inside view! (line {})",
305            ctx.new_line(new_node.span().start)
306        ));
307    }
308    if old_node.anchor() != new_node.anchor() {
309        return Err(format!(
310            "AST anchor path changed inside view! (line {})",
311            ctx.new_line(new_node.span().start)
312        ));
313    }
314    match (old_node, new_node) {
315        (ViewNode::TextLit(old_t), ViewNode::TextLit(new_t)) => {
316            let line = ctx.new_line(new_t.span.start);
317            match (&old_t.analysis, &new_t.analysis) {
318                (StringAnalysis::Static(old_s), StringAnalysis::Static(new_s)) => {
319                    if old_s == new_s {
320                        return Ok(());
321                    }
322                    ctx.patch.text_changes.push(ViewTextChange {
323                        target: ViewAnchorTarget {
324                            anchor: old_t.anchor,
325                            ordinal: ctx.ordinal(call_idx),
326                            static_ast_path: old_t.path.clone(),
327                            tag: "<text>".to_owned(),
328                            test_id: None,
329                        },
330                        old: old_s.clone(),
331                        new: new_s.clone(),
332                    });
333                    Ok(())
334                }
335                (StringAnalysis::Dynamic(a), StringAnalysis::Dynamic(b)) if a == b => Ok(()),
336                _ => Err(format!(
337                    "interpolated text literal changed inside view! (line {line})"
338                )),
339            }
340        }
341        (ViewNode::Expr(old_e), ViewNode::Expr(new_e)) => {
342            if ctx.exprs_token_equal(call_idx, old_e.expr.span, new_e.expr.span) {
343                Ok(())
344            } else {
345                Err(format!(
346                    "dynamic expression changed inside view! (line {})",
347                    ctx.new_line(new_e.span.start)
348                ))
349            }
350        }
351        (ViewNode::Element(old_el), ViewNode::Element(new_el)) => {
352            diff_element(ctx, call_idx, old_el, new_el)
353        }
354        (ViewNode::If(old_if), ViewNode::If(new_if)) => {
355            let line = ctx.new_line(new_if.span.start);
356            if old_if.branches.len() != new_if.branches.len()
357                || old_if.else_branch.is_some() != new_if.else_branch.is_some()
358            {
359                return Err(format!("`if` branch structure changed (line {line})"));
360            }
361            for (ob, nb) in old_if.branches.iter().zip(new_if.branches.iter()) {
362                match (&ob.cond, &nb.cond) {
363                    (IfCond::Expr(oe), IfCond::Expr(ne))
364                    | (IfCond::LetChain(oe), IfCond::LetChain(ne)) => {
365                        if !ctx.exprs_token_equal(call_idx, oe.span, ne.span) {
366                            return Err(format!(
367                                "`if` condition changed (line {})",
368                                ctx.new_line(ne.span.start)
369                            ));
370                        }
371                    }
372                    (
373                        IfCond::Let {
374                            pat: op,
375                            expr: oe,
376                        },
377                        IfCond::Let {
378                            pat: np,
379                            expr: ne,
380                        },
381                    ) => {
382                        if !ctx.exprs_token_equal(call_idx, op.span, np.span)
383                            || !ctx.exprs_token_equal(call_idx, oe.span, ne.span)
384                        {
385                            return Err(format!(
386                                "`if let` condition changed (line {})",
387                                ctx.new_line(np.span.start)
388                            ));
389                        }
390                    }
391                    _ => return Err(format!("`if` condition kind changed (line {line})")),
392                }
393                diff_block(ctx, call_idx, &ob.body, &nb.body)?;
394            }
395            if let (Some(oe), Some(ne)) = (&old_if.else_branch, &new_if.else_branch) {
396                diff_block(ctx, call_idx, oe, ne)?;
397            }
398            Ok(())
399        }
400        (ViewNode::Match(old_m), ViewNode::Match(new_m)) => {
401            let line = ctx.new_line(new_m.span.start);
402            if !ctx.exprs_token_equal(call_idx, old_m.scrutinee.span, new_m.scrutinee.span) {
403                return Err(format!("`match` scrutinee changed (line {line})"));
404            }
405            if old_m.arms.len() != new_m.arms.len() {
406                return Err(format!("`match` arm count changed (line {line})"));
407            }
408            for (oa, na) in old_m.arms.iter().zip(new_m.arms.iter()) {
409                let arm_line = ctx.new_line(na.span.start);
410                if !ctx.attrs_token_equal(call_idx, &oa.attrs, &na.attrs) {
411                    return Err(format!("`match` arm attribute changed (line {arm_line})"));
412                }
413                if !ctx.exprs_token_equal(call_idx, oa.pat.span, na.pat.span) {
414                    return Err(format!("`match` arm pattern changed (line {arm_line})"));
415                }
416                match (&oa.guard, &na.guard) {
417                    (None, None) => {}
418                    (Some(og), Some(ng)) if ctx.exprs_token_equal(call_idx, og.span, ng.span) => {}
419                    _ => return Err(format!("`match` arm guard changed (line {arm_line})")),
420                }
421                diff_block(ctx, call_idx, &oa.body, &na.body)?;
422            }
423            Ok(())
424        }
425        (ViewNode::For(old_f), ViewNode::For(new_f)) => {
426            let line = ctx.new_line(new_f.span.start);
427            if !ctx.exprs_token_equal(call_idx, old_f.pat.span, new_f.pat.span)
428                || !ctx.exprs_token_equal(call_idx, old_f.iter.span, new_f.iter.span)
429            {
430                return Err(format!("`for` loop header changed (line {line})"));
431            }
432            match (&old_f.key, &new_f.key) {
433                (None, None) => {}
434                (Some(ok), Some(nk)) if ctx.exprs_token_equal(call_idx, ok.span, nk.span) => {}
435                _ => return Err(format!("`for` loop key changed (line {line})")),
436            }
437            diff_block(ctx, call_idx, &old_f.body, &new_f.body)
438        }
439        _ => Err(format!(
440            "view! node kind changed structurally (line {})",
441            ctx.new_line(new_node.span().start)
442        )),
443    }
444}
445
446fn diff_element(
447    ctx: &mut DiffCtx<'_>,
448    call_idx: usize,
449    old_el: &ElementNode,
450    new_el: &ElementNode,
451) -> Result<(), String> {
452    let line = ctx.new_line(new_el.span.start);
453    if old_el.leading_colon != new_el.leading_colon || old_el.path_segments != new_el.path_segments
454    {
455        return Err(format!(
456            "element tag changed (`{}{}` -> `{}{}`) (line {line})",
457            if old_el.leading_colon { "::" } else { "" },
458            old_el.path_segments.join("::"),
459            if new_el.leading_colon { "::" } else { "" },
460            new_el.path_segments.join("::"),
461        ));
462    }
463
464    let generics_match = match (&old_el.generics, &new_el.generics) {
465        (None, None) => true,
466        (Some(og), Some(ng)) => ctx.exprs_token_equal(call_idx, og.span, ng.span),
467        _ => false,
468    };
469    if !generics_match {
470        return Err(format!(
471            "element generics changed on `{}` (line {line})",
472            new_el.path_segments.join("::")
473        ));
474    }
475
476    if old_el.is_direct_root_patchable() && new_el.is_direct_root_patchable() {
477        diff_direct_root_args(ctx, call_idx, old_el, new_el)?;
478    } else {
479        verify_composite_args_unchanged(ctx, call_idx, old_el, new_el)?;
480    }
481
482    match (&old_el.children, &new_el.children) {
483        (None, None) => Ok(()),
484        (Some(oc), Some(nc)) => diff_block(ctx, call_idx, oc, nc),
485        _ => Err(format!(
486            "children block presence changed on `{}` (line {line})",
487            new_el.path_segments.join("::")
488        )),
489    }
490}
491
492fn verify_composite_args_unchanged(
493    ctx: &DiffCtx<'_>,
494    call_idx: usize,
495    old_el: &ElementNode,
496    new_el: &ElementNode,
497) -> Result<(), String> {
498    let tag = new_el.path_segments.join("::");
499    let line = ctx.new_line(new_el.span.start);
500    let (old_args, new_args) = match (&old_el.args, &new_el.args) {
501        (None, None) => return Ok(()),
502        (Some(o), Some(n)) if o.len() == n.len() => (o, n),
503        _ => {
504            return Err(format!(
505                "composite component `{tag}` arguments changed (Tier-2) (line {line})"
506            ));
507        }
508    };
509    for (old_arg, new_arg) in old_args.iter().zip(new_args.iter()) {
510        let same = match (old_arg, new_arg) {
511            (
512                ViewArg::Positional {
513                    attrs: oa,
514                    value: oe,
515                },
516                ViewArg::Positional {
517                    attrs: na,
518                    value: ne,
519                },
520            ) => {
521                ctx.attrs_token_equal(call_idx, oa, na)
522                    && ctx.exprs_token_equal(call_idx, oe.span, ne.span)
523            }
524            (
525                ViewArg::Named {
526                    attrs: oa,
527                    name: on,
528                    value: ov,
529                    ..
530                },
531                ViewArg::Named {
532                    attrs: na,
533                    name: nn,
534                    value: nv,
535                    ..
536                },
537            ) => {
538                ctx.attrs_token_equal(call_idx, oa, na)
539                    && on == nn
540                    && ctx.exprs_token_equal(call_idx, ov.span, nv.span)
541            }
542            _ => false,
543        };
544        if !same {
545            return Err(format!(
546                "composite component `{tag}` prop changed (Tier-2) (line {line})"
547            ));
548        }
549    }
550    Ok(())
551}