Skip to main content

proa_source_tools/
source.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::path::{Path, PathBuf};
5use std::process::Command;
6
7use anyhow::{bail, Context, Result};
8use walkdir::{DirEntry, WalkDir};
9
10#[derive(Debug, Clone, Copy, Eq, PartialEq)]
11pub enum MacroDialect {
12    Html,
13    Xml,
14    /// `md!` / `md_sync!`. The body is a single string literal rather than a
15    /// markup tree, so it never reaches the HTML template parser.
16    Md,
17}
18
19#[derive(Debug, Clone)]
20pub struct MacroInvocation {
21    pub name: String,
22    pub dialect: MacroDialect,
23    pub name_start: usize,
24    pub open_brace: usize,
25    pub body_start: usize,
26    pub body_end: usize,
27    pub close_brace: usize,
28    pub name_line: usize,
29    pub name_column: usize,
30    /// Indentation of the source line containing the macro invocation.
31    pub indentation_column: usize,
32    pub body_start_line: usize,
33    pub body_start_column: usize,
34}
35
36impl MacroInvocation {
37    pub fn body<'a>(&self, source: &'a str) -> &'a str {
38        &source[self.body_start..self.body_end]
39    }
40}
41
42#[derive(Debug, Clone, Copy, Eq, PartialEq)]
43pub struct LineColumn {
44    pub line: usize,
45    pub column: usize,
46}
47
48#[derive(Debug)]
49pub struct SourceMap<'a> {
50    source: &'a str,
51    line_starts: Vec<usize>,
52}
53
54impl<'a> SourceMap<'a> {
55    pub fn new(source: &'a str) -> Self {
56        let mut line_starts = vec![0];
57        for (idx, byte) in source.bytes().enumerate() {
58            if byte == b'\n' {
59                line_starts.push(idx + 1);
60            }
61        }
62        Self {
63            source,
64            line_starts,
65        }
66    }
67
68    pub fn line_column(&self, byte: usize) -> LineColumn {
69        let line_idx = match self.line_starts.binary_search(&byte) {
70            Ok(idx) => idx,
71            Err(idx) => idx.saturating_sub(1),
72        };
73        let line_start = self.line_starts[line_idx];
74        let column = self
75            .source
76            .get(line_start..byte)
77            .map(str::chars)
78            .map(Iterator::count)
79            .unwrap_or_else(|| byte.saturating_sub(line_start));
80        LineColumn {
81            line: line_idx + 1,
82            column,
83        }
84    }
85
86    pub fn byte_for_line_column(&self, line: usize, column: usize) -> Option<usize> {
87        if line == 0 {
88            return None;
89        }
90        let line_start = *self.line_starts.get(line - 1)?;
91        let line_end = self
92            .line_starts
93            .get(line)
94            .map(|next_start| next_start.saturating_sub(1))
95            .unwrap_or(self.source.len());
96        let line_source = self.source.get(line_start..line_end)?;
97        if column == 0 {
98            return Some(line_start);
99        }
100        let char_count = line_source.chars().count();
101        if column == char_count {
102            return Some(line_end);
103        }
104        if column > char_count {
105            return None;
106        }
107        line_source
108            .char_indices()
109            .nth(column)
110            .map(|(offset, _)| line_start + offset)
111    }
112
113    pub fn span_snippet(&self, span: proc_macro2::Span) -> Option<&'a str> {
114        let start = span.start();
115        let end = span.end();
116        if start.line == 0 || end.line == 0 {
117            return None;
118        }
119        let start = self.byte_for_line_column(start.line, start.column)?;
120        let end = self.byte_for_line_column(end.line, end.column)?;
121        if start <= end && end <= self.source.len() {
122            Some(&self.source[start..end])
123        } else {
124            None
125        }
126    }
127
128    pub fn source_from_span_start(&self, span: proc_macro2::Span) -> Option<&'a str> {
129        let start = span.start();
130        if start.line == 0 {
131            return None;
132        }
133        let start = self.byte_for_line_column(start.line, start.column)?;
134        self.source.get(start..)
135    }
136}
137
138pub fn file_line_column_for_body_span(
139    inv: &MacroInvocation,
140    span: proc_macro2::Span,
141) -> Option<LineColumn> {
142    let start = span.start();
143    if start.line == 0 {
144        return None;
145    }
146
147    let line = inv.body_start_line + start.line - 1;
148    let column = if start.line == 1 {
149        inv.body_start_column + start.column
150    } else {
151        start.column
152    };
153    Some(LineColumn { line, column })
154}
155
156pub fn find_rust_files(paths: &[PathBuf]) -> Result<Vec<PathBuf>> {
157    let roots = if paths.is_empty() {
158        vec![PathBuf::from(".")]
159    } else {
160        paths.to_vec()
161    };
162
163    let mut files = Vec::new();
164    for root in roots {
165        if root.is_file() {
166            if root.extension().is_some_and(|ext| ext == "rs") {
167                files.push(root);
168            }
169            continue;
170        }
171
172        for entry in WalkDir::new(&root)
173            .into_iter()
174            .filter_entry(is_visible_entry)
175        {
176            let entry = entry.with_context(|| format!("failed to walk {}", root.display()))?;
177            if entry.file_type().is_file()
178                && entry.path().extension().is_some_and(|ext| ext == "rs")
179                && should_scan_path(entry.path())
180            {
181                files.push(entry.path().to_path_buf());
182            }
183        }
184    }
185
186    files.sort();
187    files.dedup();
188    Ok(files)
189}
190
191pub fn find_changed_rust_files(base: Option<&str>, staged: bool) -> Result<Vec<PathBuf>> {
192    let cwd = std::env::current_dir().context("resolve current directory")?;
193    find_changed_rust_files_in(&cwd, base, staged)
194}
195
196fn find_changed_rust_files_in(
197    dir: &Path,
198    base: Option<&str>,
199    staged: bool,
200) -> Result<Vec<PathBuf>> {
201    // git prints paths relative to the repository root, not the current
202    // directory, so resolve the root first or every path check below would
203    // silently miss when the command runs from a subdirectory.
204    let toplevel = git_output(dir, &["rev-parse", "--show-toplevel"])?
205        .into_iter()
206        .next()
207        .map(PathBuf::from)
208        .context("git did not report a repository root")?;
209
210    let mut names = if staged {
211        git_output(
212            dir,
213            &[
214                "diff",
215                "--cached",
216                "--name-only",
217                "--diff-filter=ACMRTUXB",
218                "--",
219                "*.rs",
220            ],
221        )?
222    } else {
223        let mut names = git_output(
224            dir,
225            &[
226                "diff",
227                "--name-only",
228                "--diff-filter=ACMRTUXB",
229                base.unwrap_or("HEAD"),
230                "--",
231                "*.rs",
232            ],
233        )?;
234        names.extend(git_output(
235            dir,
236            &[
237                "ls-files",
238                "--others",
239                "--exclude-standard",
240                "--full-name",
241                "--",
242                "*.rs",
243            ],
244        )?);
245        names
246    };
247
248    names.sort();
249    names.dedup();
250
251    let mut files = Vec::new();
252    for name in names {
253        let rel = PathBuf::from(name);
254        let path = toplevel.join(&rel);
255        if path.exists() && should_scan_path(&rel) {
256            files.push(path);
257        }
258    }
259    Ok(files)
260}
261
262fn git_output(dir: &Path, args: &[&str]) -> Result<Vec<String>> {
263    let output = Command::new("git")
264        .args(args)
265        .current_dir(dir)
266        .output()
267        .with_context(|| "failed to run git")?;
268
269    if !output.status.success() {
270        bail!(
271            "`git {}` failed: {}",
272            args.join(" "),
273            String::from_utf8_lossy(&output.stderr).trim()
274        );
275    }
276
277    Ok(String::from_utf8_lossy(&output.stdout)
278        .lines()
279        .filter(|line| !line.is_empty())
280        .map(str::to_owned)
281        .collect())
282}
283
284fn is_visible_entry(entry: &DirEntry) -> bool {
285    if entry.depth() == 0 {
286        return true;
287    }
288    if !entry.file_type().is_dir() {
289        return true;
290    }
291    entry.file_name().to_str().is_some_and(|name| {
292        !name.starts_with('.') && !matches!(name, "target" | "node_modules" | "dist")
293    })
294}
295
296fn should_scan_path(path: &Path) -> bool {
297    if path.extension().is_none_or(|ext| ext != "rs") {
298        return false;
299    }
300    if path.components().any(|component| {
301        matches!(
302            component.as_os_str().to_str(),
303            Some(
304                ".git"
305                    | ".claude"
306                    | ".codex"
307                    | ".worktrees"
308                    | ".next"
309                    | "target"
310                    | "node_modules"
311                    | "dist"
312            )
313        )
314    }) {
315        return false;
316    }
317    !is_generator_owned_golden(path) && !is_compile_fail_fixture(path)
318}
319
320fn is_generator_owned_golden(path: &Path) -> bool {
321    path.file_name()
322        .and_then(|name| name.to_str())
323        .is_some_and(|name| name.ends_with(".golden.rs"))
324        && path
325            .parent()
326            .and_then(Path::file_name)
327            .and_then(|name| name.to_str())
328            == Some("golden")
329        && path
330            .parent()
331            .and_then(Path::parent)
332            .and_then(Path::file_name)
333            .and_then(|name| name.to_str())
334            == Some("rsjs_macros")
335}
336
337fn is_compile_fail_fixture(path: &Path) -> bool {
338    let mut under_ui_tests = false;
339    let mut saw_tests = false;
340    for component in path
341        .components()
342        .filter_map(|component| component.as_os_str().to_str())
343    {
344        if component == "tests" {
345            saw_tests = true;
346            continue;
347        }
348        if saw_tests && component == "ui" {
349            under_ui_tests = true;
350            continue;
351        }
352        if under_ui_tests && component == "fail" {
353            return true;
354        }
355    }
356    false
357}
358
359pub fn find_macros(source: &str) -> Vec<MacroInvocation> {
360    let map = SourceMap::new(source);
361    let bytes = source.as_bytes();
362    let mut out = Vec::new();
363    let mut i = 0;
364    // Scanning imports walks the whole file, and only a bare `html!` needs it.
365    let bare_html_is_foreign = std::cell::OnceCell::new();
366
367    while i < bytes.len() {
368        if let Some(next) = skip_ignored(source, i) {
369            i = next;
370            continue;
371        }
372
373        if is_ident_start(bytes[i]) {
374            let name_start = i;
375            let name_end = parse_ident_end(bytes, i);
376            let name = &source[name_start..name_end];
377
378            if name == "macro_rules" {
379                if let Some(close_delimiter) = macro_rules_close_delimiter(source, name_end) {
380                    i = close_delimiter + 1;
381                    continue;
382                }
383            }
384
385            if let Some((open_delimiter, close_delimiter)) = macro_open_delimiter(source, name_end)
386            {
387                if let Some(close_delimiter_at) =
388                    find_matching_delimiter(source, open_delimiter, close_delimiter)
389                {
390                    if let Some(dialect) = macro_dialect(name) {
391                        let foreign = qualified_macro_owner(source, name_start)
392                            .is_some_and(|owner| !matches!(owner, "proa_macros" | "proa"))
393                            || (name == "html"
394                                && qualified_macro_owner(source, name_start).is_none()
395                                && *bare_html_is_foreign
396                                    .get_or_init(|| bare_html_is_imported_from_yew(source)));
397                        if foreign || close_delimiter != b'}' {
398                            i = close_delimiter_at + 1;
399                            continue;
400                        }
401
402                        let name_pos = map.line_column(name_start);
403                        let indentation_column = line_indentation_column(source, name_start);
404                        let body_pos = map.line_column(open_delimiter + 1);
405                        out.push(MacroInvocation {
406                            name: name.to_owned(),
407                            dialect,
408                            name_start,
409                            open_brace: open_delimiter,
410                            body_start: open_delimiter + 1,
411                            body_end: close_delimiter_at,
412                            close_brace: close_delimiter_at,
413                            name_line: name_pos.line,
414                            name_column: name_pos.column,
415                            indentation_column,
416                            body_start_line: body_pos.line,
417                            body_start_column: body_pos.column,
418                        });
419                        i = close_delimiter_at + 1;
420                        continue;
421                    }
422
423                    // Macro inputs are arbitrary token languages. Do not treat
424                    // an html!-looking identifier nested inside an unrelated
425                    // macro as Proa source before that macro expands it.
426                    i = close_delimiter_at + 1;
427                    continue;
428                }
429            }
430            i = name_end;
431            continue;
432        }
433
434        i += 1;
435    }
436
437    out
438}
439
440fn macro_rules_close_delimiter(source: &str, after_macro_rules: usize) -> Option<usize> {
441    let bytes = source.as_bytes();
442    let mut cursor = skip_ws(bytes, after_macro_rules);
443    if bytes.get(cursor) != Some(&b'!') {
444        return None;
445    }
446    cursor = skip_ws(bytes, cursor + 1);
447    if !bytes.get(cursor).is_some_and(|byte| is_ident_start(*byte)) {
448        return None;
449    }
450    cursor = parse_ident_end(bytes, cursor);
451    cursor = skip_ws(bytes, cursor);
452    let close = match bytes.get(cursor).copied()? {
453        b'{' => b'}',
454        b'(' => b')',
455        b'[' => b']',
456        _ => return None,
457    };
458    find_matching_delimiter(source, cursor, close)
459}
460
461/// Out-of-line `mod name;` items at the top level of `source`, with whether
462/// each carries exactly `#[cfg(test)]` and whether it has a `#[path]`
463/// attribute. One lexical pass: comments, strings, and inline module bodies
464/// are skipped, so text that merely looks like a declaration never counts.
465pub(crate) fn top_level_module_declarations(source: &str) -> Vec<(String, bool, bool)> {
466    let bytes = source.as_bytes();
467    let mut declarations = Vec::new();
468    // Compact text of the outer attributes since the last item boundary.
469    let mut attributes: Vec<String> = Vec::new();
470    let mut depth = 0usize;
471    let mut i = 0;
472    while i < bytes.len() {
473        if let Some(next) = skip_ignored(source, i) {
474            i = next;
475            continue;
476        }
477        match bytes[i] {
478            b'#' => {
479                let inner = bytes.get(skip_ws(bytes, i + 1)) == Some(&b'!');
480                let open = skip_ws(
481                    bytes,
482                    if inner {
483                        skip_ws(bytes, i + 1) + 1
484                    } else {
485                        i + 1
486                    },
487                );
488                match (bytes.get(open), find_matching_delimiter(source, open, b']')) {
489                    (Some(b'['), Some(close)) => {
490                        if depth == 0 && !inner {
491                            attributes.push(
492                                source[open + 1..close]
493                                    .chars()
494                                    .filter(|ch| !ch.is_whitespace())
495                                    .collect(),
496                            );
497                        }
498                        i = close + 1;
499                    }
500                    _ => i += 1,
501                }
502            }
503            b'{' | b'}' | b';' => {
504                match bytes[i] {
505                    b'{' => depth += 1,
506                    b'}' => depth = depth.saturating_sub(1),
507                    _ => {}
508                }
509                attributes.clear();
510                i += 1;
511            }
512            byte if is_ident_start(byte) => {
513                let end = parse_ident_end(bytes, i);
514                let word = &source[i..end];
515                i = end;
516                if depth != 0 {
517                    continue;
518                }
519                match word {
520                    // Visibility belongs to the item that follows.
521                    "pub" => {
522                        let open = skip_ws(bytes, i);
523                        if bytes.get(open) == Some(&b'(') {
524                            if let Some(close) = find_matching_delimiter(source, open, b')') {
525                                i = close + 1;
526                            }
527                        }
528                    }
529                    "mod" => {
530                        let name_start = skip_ws(bytes, i);
531                        if !bytes.get(name_start).is_some_and(|b| is_ident_start(*b)) {
532                            attributes.clear();
533                            continue;
534                        }
535                        let name_end = parse_ident_end(bytes, name_start);
536                        let after = skip_ws(bytes, name_end);
537                        if bytes.get(after) == Some(&b';') {
538                            declarations.push((
539                                source[name_start..name_end].to_owned(),
540                                attributes.iter().any(|attr| attr == "cfg(test)"),
541                                attributes.iter().any(|attr| attr.starts_with("path=")),
542                            ));
543                            attributes.clear();
544                            i = after + 1;
545                        } else {
546                            // An inline body: its `{` resets the attributes.
547                            i = name_end;
548                        }
549                    }
550                    _ => attributes.clear(),
551                }
552            }
553            _ => i += 1,
554        }
555    }
556    declarations
557}
558
559fn qualified_macro_owner(source: &str, name_start: usize) -> Option<&str> {
560    let prefix = source.get(..name_start)?.trim_end();
561    let before_separator = prefix.strip_suffix("::")?.trim_end();
562    let start = before_separator
563        .char_indices()
564        .rev()
565        .find_map(|(idx, ch)| (!ch.is_alphanumeric() && ch != '_').then_some(idx + ch.len_utf8()))
566        .unwrap_or(0);
567    before_separator
568        .get(start..)
569        .filter(|segment| !segment.is_empty())
570}
571
572pub(crate) fn bare_html_is_imported_from_yew(source: &str) -> bool {
573    let compact = compact_code_for_imports(source);
574    let mut yew_html = false;
575    let mut proa_html = false;
576    for statement in compact.split(';') {
577        yew_html |= use_statement_imports(statement, "yew", "html");
578        proa_html |= use_statement_imports(statement, "proa_macros", "html")
579            || use_statement_imports(statement, "proa", "html");
580    }
581    yew_html && !proa_html
582}
583
584fn compact_code_for_imports(source: &str) -> String {
585    let mut compact = String::with_capacity(source.len());
586    let mut cursor = 0;
587    while cursor < source.len() {
588        if let Some(next) = skip_ignored(source, cursor) {
589            cursor = next;
590            continue;
591        }
592        let ch = source[cursor..].chars().next().unwrap();
593        if !ch.is_whitespace() {
594            compact.push(ch);
595        }
596        cursor += ch.len_utf8();
597    }
598    compact
599}
600
601fn use_statement_imports(statement: &str, root: &str, target: &str) -> bool {
602    let marker = format!("use{root}::");
603    let Some(imports) = statement
604        .find(&marker)
605        .and_then(|start| statement.get(start + marker.len()..))
606    else {
607        return false;
608    };
609    if imports.contains('*') {
610        return true;
611    }
612
613    let bytes = imports.as_bytes();
614    let mut cursor = 0;
615    while cursor < bytes.len() {
616        if !is_ident_start(bytes[cursor]) {
617            cursor += 1;
618            continue;
619        }
620        let end = parse_ident_end(bytes, cursor);
621        if imports.get(cursor..end) == Some(target) {
622            return true;
623        }
624        cursor = end;
625    }
626    false
627}
628
629fn line_indentation_column(source: &str, byte: usize) -> usize {
630    let line_start = source
631        .get(..byte)
632        .and_then(|prefix| prefix.rfind('\n').map(|idx| idx + 1))
633        .unwrap_or(0);
634    source[line_start..byte]
635        .chars()
636        .take_while(|ch| ch.is_whitespace())
637        .count()
638}
639
640pub(crate) fn macro_dialect(name: &str) -> Option<MacroDialect> {
641    match name {
642        "html" | "html_sync" => Some(MacroDialect::Html),
643        "xml" | "xml_sync" => Some(MacroDialect::Xml),
644        "md" | "md_sync" => Some(MacroDialect::Md),
645        _ => None,
646    }
647}
648
649fn macro_open_delimiter(source: &str, after_name: usize) -> Option<(usize, u8)> {
650    let bytes = source.as_bytes();
651    let mut i = skip_ws(bytes, after_name);
652    if bytes.get(i) != Some(&b'!') {
653        return None;
654    }
655    i = skip_ws(bytes, i + 1);
656    let close_delimiter = match bytes.get(i).copied()? {
657        b'{' => b'}',
658        b'(' => b')',
659        b'[' => b']',
660        _ => return None,
661    };
662    Some((i, close_delimiter))
663}
664
665fn find_matching_delimiter(source: &str, open: usize, close_delimiter: u8) -> Option<usize> {
666    let bytes = source.as_bytes();
667    let open_delimiter = *bytes.get(open)?;
668    let mut depth = 1usize;
669    let mut i = open + 1;
670
671    while i < bytes.len() {
672        if let Some(next) = skip_ignored(source, i) {
673            i = next;
674            continue;
675        }
676
677        match bytes[i] {
678            byte if byte == open_delimiter => depth += 1,
679            byte if byte == close_delimiter => {
680                depth -= 1;
681                if depth == 0 {
682                    return Some(i);
683                }
684            }
685            _ => {}
686        }
687        i += 1;
688    }
689
690    None
691}
692
693fn skip_ignored(source: &str, i: usize) -> Option<usize> {
694    let bytes = source.as_bytes();
695    match bytes.get(i).copied()? {
696        b'/' if bytes.get(i + 1) == Some(&b'/') => Some(skip_line_comment(bytes, i + 2)),
697        b'/' if bytes.get(i + 1) == Some(&b'*') => Some(skip_block_comment(bytes, i + 2)),
698        b'"' => Some(skip_string(bytes, i + 1)),
699        b'\'' if looks_like_char_literal(bytes, i) => Some(skip_char(bytes, i + 1)),
700        b'b' if bytes.get(i + 1) == Some(&b'"') => Some(skip_string(bytes, i + 2)),
701        b'r' => skip_raw_string(source, i, 0),
702        b'b' if bytes.get(i + 1) == Some(&b'r') => skip_raw_string(source, i, 1),
703        _ => None,
704    }
705}
706
707fn skip_line_comment(bytes: &[u8], mut i: usize) -> usize {
708    while i < bytes.len() && bytes[i] != b'\n' {
709        i += 1;
710    }
711    i
712}
713
714fn skip_block_comment(bytes: &[u8], mut i: usize) -> usize {
715    let mut depth = 1usize;
716    while i + 1 < bytes.len() {
717        match (bytes[i], bytes[i + 1]) {
718            (b'/', b'*') => {
719                depth += 1;
720                i += 2;
721            }
722            (b'*', b'/') => {
723                depth -= 1;
724                i += 2;
725                if depth == 0 {
726                    return i;
727                }
728            }
729            _ => i += 1,
730        }
731    }
732    bytes.len()
733}
734
735fn skip_string(bytes: &[u8], mut i: usize) -> usize {
736    while i < bytes.len() {
737        match bytes[i] {
738            b'\\' => i = (i + 2).min(bytes.len()),
739            b'"' => return i + 1,
740            _ => i += 1,
741        }
742    }
743    bytes.len()
744}
745
746fn skip_raw_string(source: &str, i: usize, prefix_len: usize) -> Option<usize> {
747    let bytes = source.as_bytes();
748    let mut cursor = i + prefix_len + 1;
749    let mut hashes = 0usize;
750    while bytes.get(cursor) == Some(&b'#') {
751        hashes += 1;
752        cursor += 1;
753    }
754    if bytes.get(cursor) != Some(&b'"') {
755        return None;
756    }
757    cursor += 1;
758
759    while cursor < bytes.len() {
760        if bytes[cursor] == b'"' {
761            let end = cursor + 1 + hashes;
762            if end <= bytes.len() && bytes[cursor + 1..end].iter().all(|b| *b == b'#') {
763                return Some(end);
764            }
765        }
766        cursor += 1;
767    }
768
769    Some(bytes.len())
770}
771
772pub(crate) fn looks_like_char_literal(bytes: &[u8], i: usize) -> bool {
773    let Some(next) = bytes.get(i + 1).copied() else {
774        return false;
775    };
776    if is_ident_start(next) {
777        let ident_end = parse_ident_end(bytes, i + 1);
778        return bytes.get(ident_end) == Some(&b'\'');
779    }
780    true
781}
782
783pub(crate) fn skip_char(bytes: &[u8], mut i: usize) -> usize {
784    while i < bytes.len() {
785        match bytes[i] {
786            b'\\' => i = (i + 2).min(bytes.len()),
787            b'\'' => return i + 1,
788            _ => i += 1,
789        }
790    }
791    bytes.len()
792}
793
794fn skip_ws(bytes: &[u8], mut i: usize) -> usize {
795    while i < bytes.len() && bytes[i].is_ascii_whitespace() {
796        i += 1;
797    }
798    i
799}
800
801fn parse_ident_end(bytes: &[u8], mut i: usize) -> usize {
802    i += 1;
803    while i < bytes.len() && is_ident_continue(bytes[i]) {
804        i += 1;
805    }
806    i
807}
808
809fn is_ident_start(byte: u8) -> bool {
810    byte == b'_' || byte.is_ascii_alphabetic()
811}
812
813fn is_ident_continue(byte: u8) -> bool {
814    is_ident_start(byte) || byte.is_ascii_digit()
815}
816
817pub fn display_path(path: &Path) -> PathBuf {
818    let Ok(cwd) = std::env::current_dir() else {
819        return path.to_path_buf();
820    };
821    pathdiff::diff_paths(path, cwd).unwrap_or_else(|| path.to_path_buf())
822}
823
824#[cfg(test)]
825mod tests {
826    use super::*;
827    use std::str::FromStr;
828    use syn::spanned::Spanned;
829
830    #[test]
831    fn finds_supported_macros_and_ignores_strings_and_comments() {
832        let source = r#"
833            let ignored = "html_sync! { <div></div> }";
834            // html! { <div></div> }
835            proa_macros::html_sync! { <div>{name}</div> }
836            xml! { <svg:path /> }
837            let generated = quote! {
838                ::proa_macros::html_sync! {
839                    < #tag #attr=#value >
840                        #(#children)*
841                    </ #tag >
842                }
843            };
844        "#;
845
846        let macros = find_macros(source);
847        assert_eq!(macros.len(), 2);
848        assert_eq!(macros[0].name, "html_sync");
849        assert_eq!(macros[0].dialect, MacroDialect::Html);
850        assert_eq!(macros[0].name_column, 25);
851        assert_eq!(macros[0].indentation_column, 12);
852        assert_eq!(macros[1].name, "xml");
853        assert_eq!(macros[1].dialect, MacroDialect::Xml);
854    }
855
856    #[test]
857    fn ignores_foreign_and_macro_generated_html_invocations() {
858        let source = r#"
859            use yew::prelude::*;
860
861            macro_rules! generated {
862                ($child:ident) => {
863                    html_sync! { <div>{$child}</div> }
864                };
865            }
866
867            seq_macro::seq!(N in 0..3 {
868                html_sync! {
869                    #(<span>{N}</span>)*
870                }
871            });
872
873            fn yew_view() -> Html {
874                html! {
875                    <main>{ for items }</main>
876                }
877            }
878
879            fn proa_view() {
880                proa_macros::html_sync! { <main>"Proa"</main> }
881            }
882        "#;
883
884        let macros = find_macros(source);
885        assert_eq!(macros.len(), 1, "{macros:#?}");
886        assert_eq!(macros[0].name, "html_sync");
887        assert!(macros[0].body(source).contains("\"Proa\""));
888    }
889
890    #[test]
891    fn explicit_proa_html_import_wins_over_yew_glob() {
892        let source = r#"
893            use proa_macros::html;
894            use yew::prelude::*;
895
896            fn view() {
897                html! { <main>"Proa"</main> }
898            }
899        "#;
900
901        let macros = find_macros(source);
902        assert_eq!(macros.len(), 1, "{macros:#?}");
903        assert_eq!(macros[0].name, "html");
904    }
905
906    #[test]
907    fn ignores_qualified_foreign_html_macro() {
908        let source = r#"
909            fn view() {
910                yew::html! { <main>{ for items }</main> }
911                ::proa_macros::html_sync! { <main>"Proa"</main> }
912            }
913        "#;
914
915        let macros = find_macros(source);
916        assert_eq!(macros.len(), 1, "{macros:#?}");
917        assert_eq!(macros[0].name, "html_sync");
918    }
919
920    #[test]
921    fn source_map_columns_are_utf8_safe() {
922        let source = "let label = \"Rust→Zig\";\nhtml_sync! { <div>{self.title}</div> }\n";
923        let map = SourceMap::new(source);
924        let byte = source.find("Zig").unwrap();
925        let pos = map.line_column(byte);
926        assert_eq!(map.byte_for_line_column(pos.line, pos.column), Some(byte));
927
928        let body = r#"<div title="Rust→Zig" data-label={self.title}></div>"#;
929        let tokens = proc_macro2::TokenStream::from_str(body).unwrap();
930        let root = syn::parse2::<proa_dsl::parse::HtmlRoot>(tokens).unwrap();
931        let proa_dsl::parse::Node::Element(element) = &root.nodes[0] else {
932            panic!("expected element");
933        };
934        let proa_dsl::parse::Attribute::Dynamic { value, .. } = &element.attrs[1] else {
935            panic!("expected dynamic attr");
936        };
937        assert_eq!(
938            SourceMap::new(body).span_snippet(value.span()),
939            Some("self.title")
940        );
941    }
942
943    #[test]
944    fn finds_rs_files_under_visible_directories() {
945        let temp = tempfile::tempdir().unwrap();
946        let src = temp.path().join("src");
947        std::fs::create_dir(&src).unwrap();
948        std::fs::write(src.join("lib.rs"), "").unwrap();
949        std::fs::create_dir(temp.path().join("target")).unwrap();
950        std::fs::write(temp.path().join("target").join("ignored.rs"), "").unwrap();
951        let hidden_worktree = temp.path().join(".claude/worktrees/agent/src");
952        std::fs::create_dir_all(&hidden_worktree).unwrap();
953        std::fs::write(hidden_worktree.join("ignored.rs"), "").unwrap();
954
955        let files = find_rust_files(&[temp.path().to_path_buf()]).unwrap();
956        assert_eq!(files, vec![src.join("lib.rs")]);
957
958        let hidden = hidden_worktree.join("ignored.rs");
959        let files = find_rust_files(std::slice::from_ref(&hidden)).unwrap();
960        assert_eq!(files, vec![hidden]);
961    }
962
963    #[test]
964    fn directory_discovery_excludes_compile_fail_fixtures_but_explicit_files_are_allowed() {
965        let temp = tempfile::tempdir().unwrap();
966        let fail = temp
967            .path()
968            .join("crate/tests/ui/conformance/fail/broken.rs");
969        let pass = temp.path().join("crate/tests/ui/conformance/pass/valid.rs");
970        std::fs::create_dir_all(fail.parent().unwrap()).unwrap();
971        std::fs::create_dir_all(pass.parent().unwrap()).unwrap();
972        std::fs::write(&fail, "compile_error!(\"expected\");").unwrap();
973        std::fs::write(&pass, "fn valid() {}").unwrap();
974
975        let files = find_rust_files(&[temp.path().to_path_buf()]).unwrap();
976        assert_eq!(files, vec![pass]);
977
978        let files = find_rust_files(std::slice::from_ref(&fail)).unwrap();
979        assert_eq!(files, vec![fail]);
980    }
981
982    #[test]
983    fn directory_discovery_excludes_generator_owned_goldens_but_explicit_files_are_allowed() {
984        let temp = tempfile::tempdir().unwrap();
985        let golden_dir = temp.path().join("rsjs_macros/golden");
986        let other_golden_dir = temp.path().join("other/golden");
987        std::fs::create_dir_all(&golden_dir).unwrap();
988        std::fs::create_dir_all(&other_golden_dir).unwrap();
989
990        let generated = golden_dir.join("counter.golden.rs");
991        let handwritten = golden_dir.join("helpers.rs");
992        let unrelated = other_golden_dir.join("counter.golden.rs");
993        std::fs::write(&generated, "").unwrap();
994        std::fs::write(&handwritten, "").unwrap();
995        std::fs::write(&unrelated, "").unwrap();
996
997        let files = find_rust_files(&[temp.path().to_path_buf()]).unwrap();
998        assert_eq!(files, vec![unrelated, handwritten]);
999
1000        let files = find_rust_files(std::slice::from_ref(&generated)).unwrap();
1001        assert_eq!(files, vec![generated]);
1002    }
1003
1004    fn git(dir: &Path, args: &[&str]) {
1005        let status = Command::new("git")
1006            .args(args)
1007            .current_dir(dir)
1008            .stdout(std::process::Stdio::null())
1009            .stderr(std::process::Stdio::null())
1010            .status()
1011            .unwrap();
1012        assert!(status.success(), "git {args:?} failed in {}", dir.display());
1013    }
1014
1015    fn init_repo(dir: &Path) {
1016        git(dir, &["init", "-q"]);
1017        git(dir, &["config", "user.email", "test@example.com"]);
1018        git(dir, &["config", "user.name", "Test"]);
1019    }
1020
1021    #[test]
1022    fn changed_files_resolve_against_repo_root_from_subdirectory() {
1023        let temp = tempfile::tempdir().unwrap();
1024        let root = temp.path().canonicalize().unwrap();
1025        init_repo(&root);
1026        std::fs::create_dir_all(root.join("crate/src")).unwrap();
1027        std::fs::write(root.join("crate/src/lib.rs"), "pub fn a() {}\n").unwrap();
1028        git(&root, &["add", "."]);
1029        git(&root, &["commit", "-qm", "init"]);
1030        std::fs::write(root.join("crate/src/lib.rs"), "pub fn b() {}\n").unwrap();
1031
1032        // Run the selection from a subdirectory: paths must still resolve.
1033        let files = find_changed_rust_files_in(&root.join("crate"), None, false).unwrap();
1034        assert_eq!(files, vec![root.join("crate/src/lib.rs")]);
1035        assert!(files[0].exists());
1036    }
1037
1038    #[test]
1039    fn changed_files_include_untracked_from_subdirectory() {
1040        let temp = tempfile::tempdir().unwrap();
1041        let root = temp.path().canonicalize().unwrap();
1042        init_repo(&root);
1043        std::fs::create_dir_all(root.join("crate/src")).unwrap();
1044        std::fs::write(root.join("crate/src/lib.rs"), "pub fn a() {}\n").unwrap();
1045        git(&root, &["add", "."]);
1046        git(&root, &["commit", "-qm", "init"]);
1047        std::fs::write(root.join("crate/src/new.rs"), "pub fn c() {}\n").unwrap();
1048
1049        let files = find_changed_rust_files_in(&root.join("crate/src"), None, false).unwrap();
1050        assert_eq!(files, vec![root.join("crate/src/new.rs")]);
1051    }
1052
1053    #[test]
1054    fn changed_files_exclude_generator_owned_goldens() {
1055        let temp = tempfile::tempdir().unwrap();
1056        let root = temp.path().canonicalize().unwrap();
1057        init_repo(&root);
1058        std::fs::create_dir_all(root.join("rsjs_macros/golden")).unwrap();
1059        std::fs::create_dir_all(root.join("rsjs_macros/src")).unwrap();
1060        std::fs::write(
1061            root.join("rsjs_macros/golden/counter.golden.rs"),
1062            "generated v1\n",
1063        )
1064        .unwrap();
1065        std::fs::write(root.join("rsjs_macros/src/lib.rs"), "pub fn before() {}\n").unwrap();
1066        git(&root, &["add", "."]);
1067        git(&root, &["commit", "-qm", "init"]);
1068
1069        std::fs::write(
1070            root.join("rsjs_macros/golden/counter.golden.rs"),
1071            "generated v2\n",
1072        )
1073        .unwrap();
1074        std::fs::write(root.join("rsjs_macros/golden/new.golden.rs"), "generated\n").unwrap();
1075        std::fs::write(root.join("rsjs_macros/src/lib.rs"), "pub fn after() {}\n").unwrap();
1076        std::fs::write(
1077            root.join("rsjs_macros/src/new.rs"),
1078            "pub fn untracked() {}\n",
1079        )
1080        .unwrap();
1081
1082        let files = find_changed_rust_files_in(&root, None, false).unwrap();
1083        assert_eq!(
1084            files,
1085            vec![
1086                root.join("rsjs_macros/src/lib.rs"),
1087                root.join("rsjs_macros/src/new.rs"),
1088            ]
1089        );
1090    }
1091
1092    #[test]
1093    fn changed_files_staged_selection() {
1094        let temp = tempfile::tempdir().unwrap();
1095        let root = temp.path().canonicalize().unwrap();
1096        init_repo(&root);
1097        std::fs::write(root.join("a.rs"), "pub fn a() {}\n").unwrap();
1098        git(&root, &["add", "."]);
1099        git(&root, &["commit", "-qm", "init"]);
1100        std::fs::write(root.join("a.rs"), "pub fn b() {}\n").unwrap();
1101        std::fs::write(root.join("b.rs"), "pub fn c() {}\n").unwrap();
1102        git(&root, &["add", "a.rs"]);
1103
1104        let files = find_changed_rust_files_in(&root, None, true).unwrap();
1105        assert_eq!(files, vec![root.join("a.rs")]);
1106    }
1107
1108    #[test]
1109    fn changed_files_bad_base_ref_errors_instead_of_reporting_clean() {
1110        let temp = tempfile::tempdir().unwrap();
1111        let root = temp.path().canonicalize().unwrap();
1112        init_repo(&root);
1113        std::fs::write(root.join("a.rs"), "pub fn a() {}\n").unwrap();
1114        git(&root, &["add", "."]);
1115        git(&root, &["commit", "-qm", "init"]);
1116
1117        let error = find_changed_rust_files_in(&root, Some("no-such-ref"), false).unwrap_err();
1118        assert!(error.to_string().contains("git diff"), "{error}");
1119    }
1120
1121    #[test]
1122    fn changed_files_outside_repo_errors_instead_of_reporting_clean() {
1123        let temp = tempfile::tempdir().unwrap();
1124        let root = temp.path().canonicalize().unwrap();
1125        let error = find_changed_rust_files_in(&root, None, false).unwrap_err();
1126        assert!(error.to_string().contains("git"), "{error}");
1127    }
1128}
1129
1130#[cfg(test)]
1131mod facade_tests {
1132    #[test]
1133    fn qualified_facade_templates_are_discovered() {
1134        let macros = super::find_macros(
1135            "proa::html_sync! { <p>{name}</p> }; proa::md_sync! { r#\"{name}\"# };",
1136        );
1137        assert_eq!(macros.len(), 2);
1138    }
1139}