euv-cli 0.41.1

Cross-platform CLI tool for the euv native UI framework supporting run, build, check, fmt, doctor, and new across Web, Android, iOS, iPadOS, macOS, Windows, and Linux.
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
use super::*;

/// Formats all `euv` procedural macro bodies (`view!`, `style!`, `tokens!`, etc.) in a single Rust source string deterministically and idempotently.
///
/// # Arguments
///
/// - `&str` - Raw Rust source code.
///
/// # Returns
///
/// - `(String, usize)` - Tuple of `(formatted_source, formatted_macro_count)`.
#[must_use]
pub fn format_euv_macros_in_source(source: &str) -> (String, usize) {
    let bytes: &[u8] = source.as_bytes();
    let len: usize = bytes.len();
    let mut out: String = String::with_capacity(len + 64);
    let mut idx: usize = 0;
    let mut count: usize = 0;
    while idx < len {
        if let Some(next_idx) = skip_string_or_comment(bytes, idx) {
            out.push_str(&source[idx..next_idx]);
            idx = next_idx;
            continue;
        }
        if is_ident_start(bytes[idx]) && (idx == 0 || !is_ident_continue(bytes[idx - 1])) {
            let ident_start: usize = idx;
            let mut ident_end: usize = idx + 1;
            while ident_end < len && is_ident_continue(bytes[ident_end]) {
                ident_end += 1;
            }
            let ident: &str = &source[ident_start..ident_end];
            if EUV_FMT_MACRO_NAMES.contains(&ident)
                && ident_end < len
                && bytes[ident_end] == BYTE_BANG
            {
                let mut probe: usize = ident_end + 1;
                while probe < len && (bytes[probe] == BYTE_SPACE || bytes[probe] == BYTE_TAB) {
                    probe += 1;
                }
                if probe < len
                    && bytes[probe] == BYTE_LBRACE
                    && let Some(close_brace) = find_matching_brace(bytes, probe)
                {
                    let inner: &str = &source[(probe + 1)..close_brace];
                    let base_indent: usize = line_leading_spaces(source, ident_start);
                    let formatted_block: String = format_macro_brace_body(inner, base_indent);
                    out.push_str(ident);
                    out.push_str("! ");
                    out.push_str(&formatted_block);
                    if formatted_block != source[probe..=close_brace]
                        || &source[(ident_end + 1)..probe] != " "
                    {
                        count += 1;
                    }
                    idx = close_brace + 1;
                    continue;
                }
            }
            out.push_str(&source[ident_start..ident_end]);
            idx = ident_end;
            continue;
        }
        let ch_len: usize = source[idx..]
            .chars()
            .next()
            .map(char::len_utf8)
            .unwrap_or(1);
        out.push_str(&source[idx..(idx + ch_len)]);
        idx += ch_len;
    }
    (out, count)
}

/// Runs `crate-cli`'s unified Prettier-aligned text, derive, and Rust formatting pass before `euv` macro normalization.
///
/// # Arguments
///
/// - `&Path` - Root directory, `Cargo.toml` manifest path, or single file path.
/// - `bool` - When `true`, checks formatting without modifying files.
///
/// # Returns
///
/// - `io::Result<UnifiedFmtReport>` - Summary of scanned and formatted non-Rust text files.
pub fn run_unified_base_fmt(target_root: &Path, check: bool) -> io::Result<UnifiedFmtReport> {
    let is_non_manifest_file: bool = target_root.is_file()
        && target_root.file_name().and_then(OsStr::to_str) != Some(CARGO_TOML_NAME);
    if is_non_manifest_file {
        return format_workspace_text_files(target_root, check);
    }
    let runtime: Runtime = Builder::new_current_thread().enable_all().build()?;
    runtime.block_on(execute_unified_fmt(target_root, check))
}

/// Formats all `.rs` files under `root` (or a single `.rs` file) in place or in `--check` mode.
///
/// # Arguments
///
/// - `&Path` - Root directory or single Rust source file.
/// - `bool` - When `true`, verifies formatting without modifying files and returns an error if changes are needed.
///
/// # Returns
///
/// - `io::Result<FmtReport>` - Structured formatting report or error on I/O / check failure.
pub fn format_workspace_macros(root: &Path, check: bool) -> io::Result<FmtReport> {
    let mut files: Vec<PathBuf> = Vec::new();
    collect_rs_files(root, &mut files)?;
    files.sort();
    let mut report: FmtReport = FmtReport::new(files.len(), 0, 0, 0, 0, check, Vec::new());
    for file_path in files.into_iter() {
        let original: String = fs::read_to_string(&file_path)?;
        let (formatted, macro_hits): (String, usize) = format_euv_macros_in_source(&original);
        if formatted != original {
            let next_files: usize = report.get_files_formatted() + 1;
            let next_macros: usize = report.get_macros_formatted() + macro_hits.max(1);
            report.set_files_formatted(next_files);
            report.set_macros_formatted(next_macros);
            report
                .get_mut_changed_files()
                .push(file_path.display().to_string());
            if !check {
                fs::write(&file_path, formatted)?;
            }
        }
    }
    if check && report.get_files_formatted() > 0 {
        return Err(Error::other(format!(
            "{ERR_FMT_CHECK_FAILED}: {}",
            report.get_changed_files().join(", ")
        )));
    }
    Ok(report)
}

/// Recursively collects `.rs` source files under `path`, skipping build/VCS directories.
///
/// # Arguments
///
/// - `&Path` - Directory or file path to inspect.
/// - `&mut Vec<PathBuf>` - Output accumulator of Rust source paths.
///
/// # Returns
///
/// - `io::Result<()>` - Traversal result.
fn collect_rs_files(path: &Path, out: &mut Vec<PathBuf>) -> io::Result<()> {
    if path.is_file() {
        if path.extension().and_then(OsStr::to_str) == Some(EUV_FMT_RS_EXT) {
            out.push(path.to_path_buf());
        }
        return Ok(());
    }
    if !path.is_dir() {
        return Ok(());
    }
    for entry_res in fs::read_dir(path)? {
        let entry: DirEntry = entry_res?;
        let child: PathBuf = entry.path();
        if child.is_dir() {
            let name: String = entry.file_name().to_string_lossy().into_owned();
            if name.starts_with('.') || EUV_FMT_SKIP_DIRS.contains(&name.as_str()) {
                continue;
            }
            collect_rs_files(&child, out)?;
        } else if child.extension().and_then(OsStr::to_str) == Some(EUV_FMT_RS_EXT) {
            out.push(child);
        }
    }
    Ok(())
}

/// Formats the contents inside `{ ... }` of an `euv` macro invocation with exact 4-space nested indentation.
///
/// # Arguments
///
/// - `&str` - Raw interior slice between `{` and `}`.
/// - `usize` - Base indentation in spaces of the macro call line.
///
/// # Returns
///
/// - `String` - Cleanly formatted `{ ... }` block including outer braces.
fn format_macro_brace_body(inner: &str, base_indent: usize) -> String {
    if !inner.contains('\n') {
        let trimmed: &str = inner.trim();
        if trimmed.is_empty() {
            return "{}".to_string();
        }
        return format!("{{ {trimmed} }}");
    }
    let mut out: String = String::with_capacity(inner.len() + 64);
    out.push_str("{\n");
    let mut indent_stack: Vec<usize> = Vec::new();
    let mut in_block_comment: bool = false;
    let mut raw_hashes: Option<usize> = None;
    for raw_line in inner.lines() {
        if let Some(hashes) = raw_hashes {
            out.push_str(raw_line);
            out.push('\n');
            raw_hashes = scan_raw_string_end(raw_line, hashes);
            continue;
        }
        let trimmed: &str = raw_line.trim();
        if trimmed.is_empty() {
            continue;
        }
        let (events, next_comment, next_raw): (Vec<bool>, bool, Option<usize>) =
            scan_line_delimiter_events(trimmed, in_block_comment);
        in_block_comment = next_comment;
        raw_hashes = next_raw;
        let leading_closes: usize = events
            .iter()
            .take_while(|is_open: &&bool| !**is_open)
            .count();
        for _ in 0..leading_closes {
            let _: Option<usize> = indent_stack.pop();
        }
        let visual_depth: usize = 1 + indent_stack.iter().copied().sum::<usize>();
        let indent_spaces: usize = base_indent + visual_depth * EUV_FMT_INDENT_SPACES;
        for _ in 0..indent_spaces {
            out.push(' ');
        }
        out.push_str(trimmed);
        out.push('\n');
        let mut line_opens: usize = 0;
        for is_open in events.into_iter().skip(leading_closes) {
            if is_open {
                line_opens += 1;
            } else if line_opens > 0 {
                line_opens -= 1;
            } else {
                let _: Option<usize> = indent_stack.pop();
            }
        }
        for open_idx in 0..line_opens {
            indent_stack.push(usize::from(open_idx == 0));
        }
    }
    for _ in 0..base_indent {
        out.push(' ');
    }
    out.push('}');
    out
}

/// Scans a single trimmed line for ordered delimiter events (`true` for `{`/`(`/ `[`, `false` for `}`/`)`/`]`) outside strings and comments.
///
/// # Arguments
///
/// - `&str` - Trimmed source line.
/// - `bool` - Whether a `/* ... */` block comment was already open on entry.
///
/// # Returns
///
/// - `(Vec<bool>, bool, Option<usize>)` - `(ordered_events, next_in_block_comment, unclosed_raw_string_hashes)`.
fn scan_line_delimiter_events(
    line: &str,
    mut in_block_comment: bool,
) -> (Vec<bool>, bool, Option<usize>) {
    let bytes: &[u8] = line.as_bytes();
    let len: usize = bytes.len();
    let mut i: usize = 0;
    let mut events: Vec<bool> = Vec::new();
    while i < len {
        if in_block_comment {
            if bytes[i] == BYTE_STAR && i + 1 < len && bytes[i + 1] == BYTE_SLASH {
                in_block_comment = false;
                i += 2;
            } else {
                i += 1;
            }
            continue;
        }
        if bytes[i] == BYTE_SLASH && i + 1 < len && bytes[i + 1] == BYTE_SLASH {
            break;
        }
        if bytes[i] == BYTE_SLASH && i + 1 < len && bytes[i + 1] == BYTE_STAR {
            in_block_comment = true;
            i += 2;
            continue;
        }
        if bytes[i] == BYTE_LOWER_R
            && let Some((end_pos, hashes)) = parse_raw_string_on_line(bytes, i)
        {
            match end_pos {
                Some(next_i) => {
                    i = next_i;
                    continue;
                }
                None => return (events, in_block_comment, Some(hashes)),
            }
        }
        if bytes[i] == BYTE_DQUOTE {
            i += 1;
            while i < len {
                if bytes[i] == BYTE_BACKSLASH && i + 1 < len {
                    i += 2;
                    continue;
                }
                if bytes[i] == BYTE_DQUOTE {
                    i += 1;
                    break;
                }
                i += 1;
            }
            continue;
        }
        if bytes[i] == BYTE_SQUOTE
            && let Some(next_i) = skip_char_literal(bytes, i)
        {
            i = next_i;
            continue;
        }
        match bytes[i] {
            BYTE_LBRACE | BYTE_LPAREN | BYTE_LBRACKET => events.push(true),
            BYTE_RBRACE | BYTE_RPAREN | BYTE_RBRACKET => events.push(false),
            _ => {}
        }
        i += 1;
    }
    (events, in_block_comment, None)
}

/// Checks if a multi-line raw string literal closes on `line`.
///
/// # Arguments
///
/// - `&str` - Raw line inside an active raw string literal.
/// - `usize` - Number of `#` delimiters required after `"`.
///
/// # Returns
///
/// - `Option<usize>` - `None` if closed on this line, or `Some(hashes)` if still open.
fn scan_raw_string_end(line: &str, hashes: usize) -> Option<usize> {
    let bytes: &[u8] = line.as_bytes();
    let len: usize = bytes.len();
    let mut i: usize = 0;
    while i < len {
        if bytes[i] == BYTE_DQUOTE {
            let mut h: usize = 0;
            while i + 1 + h < len && bytes[i + 1 + h] == BYTE_HASH && h < hashes {
                h += 1;
            }
            if h == hashes {
                return None;
            }
        }
        i += 1;
    }
    Some(hashes)
}

/// Attempts to parse a Rust raw string starting at `bytes[start] == b'r'` within a single line.
///
/// # Arguments
///
/// - `&[u8]` - Line bytes.
/// - `usize` - Index of `'r'`.
///
/// # Returns
///
/// - `Option<(Option<usize>, usize)>` - `Some((end_index_if_closed_on_line, hash_count))` if a raw string starts here.
fn parse_raw_string_on_line(bytes: &[u8], start: usize) -> Option<(Option<usize>, usize)> {
    let len: usize = bytes.len();
    if start > 0 && is_ident_continue(bytes[start - 1]) {
        return None;
    }
    let mut i: usize = start + 1;
    let mut hashes: usize = 0;
    while i < len && bytes[i] == BYTE_HASH {
        hashes += 1;
        i += 1;
    }
    if i >= len || bytes[i] != BYTE_DQUOTE {
        return None;
    }
    i += 1;
    while i < len {
        if bytes[i] == BYTE_DQUOTE {
            let mut h: usize = 0;
            while i + 1 + h < len && bytes[i + 1 + h] == BYTE_HASH && h < hashes {
                h += 1;
            }
            if h == hashes {
                return Some((Some(i + 1 + hashes), hashes));
            }
        }
        i += 1;
    }
    Some((None, hashes))
}

/// Skips a string literal, raw string literal, char literal, or comment starting at `idx`.
///
/// # Arguments
///
/// - `&[u8]` - Full Rust source bytes.
/// - `usize` - Current byte offset.
///
/// # Returns
///
/// - `Option<usize>` - Byte offset immediately after the skipped literal or comment.
fn skip_string_or_comment(bytes: &[u8], idx: usize) -> Option<usize> {
    let len: usize = bytes.len();
    if bytes[idx] == BYTE_SLASH && idx + 1 < len && bytes[idx + 1] == BYTE_SLASH {
        let mut i: usize = idx + 2;
        while i < len && bytes[i] != BYTE_NEWLINE {
            i += 1;
        }
        return Some(i);
    }
    if bytes[idx] == BYTE_SLASH && idx + 1 < len && bytes[idx + 1] == BYTE_STAR {
        let mut i: usize = idx + 2;
        let mut nest: usize = 1;
        while i + 1 < len && nest > 0 {
            if bytes[i] == BYTE_SLASH && bytes[i + 1] == BYTE_STAR {
                nest += 1;
                i += 2;
            } else if bytes[i] == BYTE_STAR && bytes[i + 1] == BYTE_SLASH {
                nest -= 1;
                i += 2;
            } else {
                i += 1;
            }
        }
        return Some(i);
    }
    if bytes[idx] == BYTE_LOWER_R && (idx == 0 || !is_ident_continue(bytes[idx - 1])) {
        let mut i: usize = idx + 1;
        let mut hashes: usize = 0;
        while i < len && bytes[i] == BYTE_HASH {
            hashes += 1;
            i += 1;
        }
        if i < len && bytes[i] == BYTE_DQUOTE {
            i += 1;
            while i < len {
                if bytes[i] == BYTE_DQUOTE {
                    let mut h: usize = 0;
                    while i + 1 + h < len && bytes[i + 1 + h] == BYTE_HASH && h < hashes {
                        h += 1;
                    }
                    if h == hashes {
                        return Some(i + 1 + hashes);
                    }
                }
                i += 1;
            }
            return Some(len);
        }
    }
    if bytes[idx] == BYTE_DQUOTE {
        let mut i: usize = idx + 1;
        while i < len {
            if bytes[i] == BYTE_BACKSLASH && i + 1 < len {
                i += 2;
                continue;
            }
            if bytes[i] == BYTE_DQUOTE {
                return Some(i + 1);
            }
            i += 1;
        }
        return Some(len);
    }
    if bytes[idx] == BYTE_SQUOTE {
        return skip_char_literal(bytes, idx);
    }
    None
}

/// Skips a Rust character literal (`'a'`, `'\n'`, `'\''`) without confusing lifetimes (`'static`).
///
/// # Arguments
///
/// - `&[u8]` - Source bytes.
/// - `usize` - Offset of opening `'`.
///
/// # Returns
///
/// - `Option<usize>` - Byte offset immediately after closing `'` if a char literal was matched.
fn skip_char_literal(bytes: &[u8], idx: usize) -> Option<usize> {
    let len: usize = bytes.len();
    if idx + 2 >= len {
        return None;
    }
    if bytes[idx + 1] == BYTE_BACKSLASH {
        let mut i: usize = idx + 2;
        while i < len && i <= idx + 10 {
            if bytes[i] == BYTE_SQUOTE {
                return Some(i + 1);
            }
            i += 1;
        }
        return None;
    }
    if bytes[idx + 2] == BYTE_SQUOTE {
        return Some(idx + 3);
    }
    None
}

/// Finds the matching closing `}` for an opening `{` at `open_idx`, skipping nested braces, strings, and comments.
///
/// # Arguments
///
/// - `&[u8]` - Source bytes.
/// - `usize` - Byte offset of the opening `{`.
///
/// # Returns
///
/// - `Option<usize>` - Byte offset of the matching `}` if balanced.
fn find_matching_brace(bytes: &[u8], open_idx: usize) -> Option<usize> {
    let len: usize = bytes.len();
    let mut i: usize = open_idx + 1;
    let mut depth: usize = 1;
    while i < len {
        if let Some(next_i) = skip_string_or_comment(bytes, i) {
            i = next_i;
            continue;
        }
        if bytes[i] == BYTE_LBRACE {
            depth += 1;
        } else if bytes[i] == BYTE_RBRACE {
            depth -= 1;
            if depth == 0 {
                return Some(i);
            }
        }
        i += 1;
    }
    None
}

/// Computes the leading space count of the line containing byte offset `pos`.
///
/// # Arguments
///
/// - `&str` - Source text.
/// - `usize` - Byte offset within the line.
///
/// # Returns
///
/// - `usize` - Leading space indentation count.
fn line_leading_spaces(source: &str, pos: usize) -> usize {
    let bytes: &[u8] = source.as_bytes();
    let mut line_start: usize = pos;
    while line_start > 0 && bytes[line_start - 1] != BYTE_NEWLINE {
        line_start -= 1;
    }
    let mut spaces: usize = 0;
    while line_start + spaces < bytes.len() && bytes[line_start + spaces] == BYTE_SPACE {
        spaces += 1;
    }
    spaces
}

/// Returns `true` when `b` can begin a Rust identifier.
///
/// # Arguments
///
/// - `u8` - ASCII byte.
///
/// # Returns
///
/// - `bool` - Whether `b` is alphabetic or `_`.
fn is_ident_start(b: u8) -> bool {
    b.is_ascii_alphabetic() || b == BYTE_UNDERSCORE
}

/// Returns `true` when `b` can continue a Rust identifier.
///
/// # Arguments
///
/// - `u8` - ASCII byte.
///
/// # Returns
///
/// - `bool` - Whether `b` is alphanumeric or `_`.
fn is_ident_continue(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == BYTE_UNDERSCORE
}