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
//! Direct-root `view!` element argument diffing: static `Text("...")` strings, `style:` /
//! `nv_style:` `TypedStyle` / `Style` builder chains, and direct named style/layout/typography
//! props, reusing `hot_diff`'s attribute registry, const evaluator, and chain scanner.

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

/// Extracts the static `test_id` Rust string literal attached to a direct-root element (for watch
/// log formatting only; never emitted as `TemplatePatch::target_test_id` for keyed anchors).
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
}

/// Diffs arguments on a direct-root patchable element (`Node`, `LeafNode`, `Text`, `Pressable`,
/// `ScrollView`, `Column`, `Row`).
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)
        ));
    }

    // Collect bitmasks for direct props, bidirectional `layout_ext` / unknown props, and `style:` /
    // `nv_style:` chains so neither a `style:` edit nor a direct prop edit can ever diverge from a
    // shadowed prop, shorthand, or `.merge*` / non-chain style expression.
    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(())
}

/// Diffs a static string argument on `Text("...")` / `Text(text: "...")`.
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})"
        )),
    }
}

/// Diffs a `style: TypedStyle::...` / `style: Style::...` builder chain argument.
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})"
        ));
    }

    // Verify every token outside the scanned literal argument spans matches 1:1.
    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(())
}

/// Diffs one direct named style/layout/typography prop (`padding: 16.0`, `bg: Rgba::rgb(...)`,
/// `color: ...`, `font_size: 18.0`, `align_items: AlignItems::Center`, etc.).
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);

    // Evaluate `old_lex` once; if a dimension prop (`width`, `height`, `top`, etc.) is given bare
    // float literals (`width: 120.0` -> `width: 240.0`), promote to the float-accepting pixel spec.
    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(())
}

/// Checks constructor-shape preservation while also allowing same-type color constant swaps such as
/// `Rgba::WHITE` -> `Rgba::BLACK` (and `ColorRgba::WHITE` -> `ColorRgba::TRANSPARENT`).
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)
}