nativeview-cli 0.1.0-rc.1

Developer CLI (`nv`) for Native View Engine: dev hot-reload, builds, pairing, SDK management, app scaffolding, and docs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
//! Whole-file `view!` AST and outer-Rust token differ powered strictly by `nativeview-view-syntax`.

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,
};

/// Diffs `old_src` against `new_src` for a `.rs` file at `rel_file` containing `view! { ... }`
/// blocks and classifies the edit as [`ViewDiffOutcome::NoOp`], [`ViewDiffOutcome::Tier1Patch`],
/// or [`ViewDiffOutcome::NeedsRebuild`].
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)
}

/// Diffs already-tokenized and already-scanned `view!` invocations (zero redundant lexing/parsing).
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(),
        };
    }

    // Verify every Rust token outside top-level `view! { ... }` body spans matches 1:1.
    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 };
    }

    // Track every call nested inside an unparsed (`Err`) ancestor so no nested `view!` inside an
    // unparsed outer `view!` can ever emit a Tier-1 patch (the ancestor compares its entire raw
    // body token stream without skipping nested spans).
    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)
    }

    /// Returns `true` iff two `#[...]` attribute lists have equal length and pairwise identical
    /// Rust tokens.
    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))
    }

    /// Returns `true` iff `old_span` and `new_span` have identical Rust tokens (ignoring comments,
    /// whitespace, and the inner bodies of any nested `view! { ... }` calls inside them, which are
    /// diffed independently under their own ordinals).
    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(())
}