statum-macros 0.8.2

Proc macros for representing legal workflow and protocol states explicitly in Rust
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
use crate::cache::{
    self, clear_line_cache_for_file, file_fingerprint, get_or_parse_file_modules, store_line_result,
};
use crate::parser::resolve_module_path_from_lines;
use crate::pathing::normalize_file_path;
use proc_macro2::Span;

/// Extracts the file path and line number where the macro was invoked.
pub fn get_source_info() -> Option<(String, usize)> {
    // `proc_macro` APIs panic when used outside a proc-macro context.
    // Return `None` instead of panicking so callers can degrade gracefully.
    let span = std::panic::catch_unwind(proc_macro::Span::call_site).ok()?;
    source_info_from_proc_span(span)
}

pub fn get_source_info_for_span(span: Span) -> Option<(String, usize)> {
    // Prefer the item's own span because `call_site` can be missing or lossy in
    // proc-macro server contexts. Fall back to `call_site` to preserve the older
    // best-effort path when span-local file info is unavailable.
    std::panic::catch_unwind(move || span.unwrap())
        .ok()
        .and_then(source_info_from_proc_span)
        .or_else(get_source_info)
}

fn source_info_from_proc_span(span: proc_macro::Span) -> Option<(String, usize)> {
    let line_number = span.start().line();

    if let Some(local_file) = span.local_file() {
        return Some((local_file.to_string_lossy().into_owned(), line_number));
    }

    let file_path = span.file();
    if file_path.is_empty() {
        None
    } else {
        Some((file_path, line_number))
    }
}

/// Reads the file and extracts the module path at the given line.
pub fn find_module_path(file_path: &str, line_number: usize) -> Option<String> {
    let normalized_file_path = normalize_file_path(file_path);
    let fingerprint = file_fingerprint(&normalized_file_path)?;

    match cache::cached_line_result(&normalized_file_path, line_number, fingerprint) {
        cache::CacheLookup::Fresh(module_path) => return module_path,
        // Cached line/module mappings are only valid as a set for one file fingerprint.
        // Once the file changes, drop every cached line for that file before reparsing.
        cache::CacheLookup::Stale => clear_line_cache_for_file(&normalized_file_path),
        cache::CacheLookup::Missing => {}
    }

    let parsed_file = get_or_parse_file_modules(&normalized_file_path, fingerprint)?;
    let resolved = resolve_module_path_from_lines(
        &parsed_file.base_module,
        &parsed_file.line_modules,
        line_number,
    );

    store_line_result(
        &normalized_file_path,
        line_number,
        fingerprint,
        resolved.clone(),
    );

    resolved
}

/// Reads the file and extracts the module path at the given line, using a known module root.
#[cfg(test)]
pub fn find_module_path_in_file(
    file_path: &str,
    line_number: usize,
    module_root: &std::path::Path,
) -> Option<String> {
    let normalized_file_path = normalize_file_path(file_path);
    let (base_module, line_modules) =
        crate::parser::parse_file_modules(&normalized_file_path, module_root)?;
    resolve_module_path_from_lines(&base_module, &line_modules, line_number)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pathing::{module_path_from_file, module_path_to_file};
    use std::fs;
    use std::path::{Path, PathBuf};
    use std::thread;
    use std::time::Duration;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn unique_temp_dir(label: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock")
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("statum_module_path_{label}_{nanos}"));
        fs::create_dir_all(&dir).expect("create temp dir");
        dir
    }

    fn write_file(path: &Path, contents: &str) {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).expect("create parent");
        }
        fs::write(path, contents).expect("write file");
    }

    #[test]
    fn module_path_from_file_handles_lib_mod_and_nested_paths() {
        assert_eq!(module_path_from_file("/tmp/project/src/lib.rs"), "crate");
        assert_eq!(module_path_from_file("/tmp/project/src/main.rs"), "crate");
        assert_eq!(
            module_path_from_file("/tmp/project/src/foo/bar.rs"),
            "foo::bar"
        );
        assert_eq!(module_path_from_file("/tmp/project/src/foo/mod.rs"), "foo");
    }

    #[test]
    fn module_path_to_file_resolves_crate_rs_and_mod_rs() {
        let crate_dir = unique_temp_dir("to_file");
        let src = crate_dir.join("src");
        let lib = src.join("lib.rs");
        let workflow = src.join("workflow.rs");
        let worker_mod = src.join("worker").join("mod.rs");

        write_file(&lib, "pub mod workflow; pub mod worker;");
        write_file(&workflow, "pub fn run() {}");
        write_file(&worker_mod, "pub fn spawn() {}");

        let current = workflow.to_string_lossy().into_owned();
        let module_root = src;

        assert_eq!(
            module_path_to_file("crate", &current, &module_root),
            Some(lib.clone())
        );
        assert_eq!(
            module_path_to_file("crate::workflow", &current, &module_root),
            Some(workflow.clone())
        );
        assert_eq!(
            module_path_to_file("crate::worker", &current, &module_root),
            Some(worker_mod.clone())
        );

        let _ = fs::remove_dir_all(crate_dir);
    }

    #[test]
    fn find_module_path_in_file_resolves_nested_inline_modules() {
        let crate_dir = unique_temp_dir("nested_mods");
        let src = crate_dir.join("src");
        let lib = src.join("lib.rs");

        write_file(
            &lib,
            "mod outer {\n    mod inner {\n        pub fn marker() {}\n    }\n}\n",
        );

        let found = find_module_path_in_file(&lib.to_string_lossy(), 3, &src);
        assert_eq!(found.as_deref(), Some("outer::inner"));

        let _ = fs::remove_dir_all(crate_dir);
    }

    #[test]
    fn find_module_path_in_file_handles_raw_identifier_modules() {
        let crate_dir = unique_temp_dir("raw_ident_mods");
        let src = crate_dir.join("src");
        let lib = src.join("lib.rs");

        write_file(
            &lib,
            "#[cfg(any())]\npub(crate) mod r#async {\n    pub mod r#type {\n        pub fn marker() {}\n    }\n}\n",
        );

        let found = find_module_path_in_file(&lib.to_string_lossy(), 4, &src);
        assert_eq!(found.as_deref(), Some("r#async::r#type"));

        let _ = fs::remove_dir_all(crate_dir);
    }

    #[test]
    fn find_module_path_in_file_separates_sibling_modules_with_similar_shapes() {
        let crate_dir = unique_temp_dir("sibling_modules");
        let src = crate_dir.join("src");
        let lib = src.join("lib.rs");

        write_file(
            &lib,
            "mod alpha {\n    mod support {\n        pub struct Text;\n    }\n\n    pub enum WorkflowState {\n        Draft,\n    }\n\n    pub struct Row {\n        pub status: &'static str,\n    }\n}\n\nmod beta {\n    mod support {\n        pub struct Text;\n    }\n\n    pub enum WorkflowState {\n        Draft,\n    }\n\n    pub struct Row {\n        pub status: &'static str,\n    }\n}\n",
        );

        assert_eq!(
            find_module_path_in_file(&lib.to_string_lossy(), 6, &src).as_deref(),
            Some("alpha")
        );
        assert_eq!(
            find_module_path_in_file(&lib.to_string_lossy(), 20, &src).as_deref(),
            Some("beta")
        );
        assert_eq!(
            find_module_path_in_file(&lib.to_string_lossy(), 19, &src).as_deref(),
            Some("beta")
        );

        let _ = fs::remove_dir_all(crate_dir);
    }

    #[test]
    fn find_module_path_in_file_rejects_same_line_sibling_modules() {
        let crate_dir = unique_temp_dir("same_line_siblings");
        let src = crate_dir.join("src");
        let lib = src.join("lib.rs");

        write_file(
            &lib,
            "mod alpha { pub fn left() {} } mod beta { pub fn right() {} }\n",
        );

        assert_eq!(
            find_module_path_in_file(&lib.to_string_lossy(), 1, &src),
            None
        );
        assert_eq!(find_module_path(&lib.to_string_lossy(), 1), None);

        let _ = fs::remove_dir_all(crate_dir);
    }

    #[test]
    fn find_module_path_in_file_rejects_same_line_nested_module_boundaries() {
        let crate_dir = unique_temp_dir("same_line_nested");
        let src = crate_dir.join("src");
        let lib = src.join("lib.rs");

        write_file(
            &lib,
            "mod outer { pub fn left() {} mod inner { pub fn right() {} } }\n",
        );

        assert_eq!(
            find_module_path_in_file(&lib.to_string_lossy(), 1, &src),
            None
        );
        assert_eq!(find_module_path(&lib.to_string_lossy(), 1), None);

        let _ = fs::remove_dir_all(crate_dir);
    }

    #[test]
    fn find_module_path_in_file_ignores_mod_tokens_in_comments_and_raw_strings() {
        let crate_dir = unique_temp_dir("comments_and_raw_strings");
        let src = crate_dir.join("src");
        let lib = src.join("lib.rs");

        write_file(
            &lib,
            "const TEMPLATE: &str = r#\"\nmod fake {\n    mod nested {}\n}\n\"#;\n\n/* mod ignored {\n    mod deeper {}\n} */\n\nmod outer {\n    // mod hidden { mod nope {} }\n    mod inner {\n        pub fn marker() {}\n    }\n}\n",
        );

        let found = find_module_path_in_file(&lib.to_string_lossy(), 14, &src);
        assert_eq!(found.as_deref(), Some("outer::inner"));

        let _ = fs::remove_dir_all(crate_dir);
    }

    #[test]
    fn find_module_path_in_file_ignores_modules_inside_macro_rules_bodies() {
        let crate_dir = unique_temp_dir("macro_rules_body");
        let src = crate_dir.join("src");
        let lib = src.join("lib.rs");

        write_file(
            &lib,
            "mod outer {\n    macro_rules! generated {\n        () => {\n            mod fake {\n                pub fn hidden() {}\n            }\n        };\n    }\n}\n",
        );

        assert_eq!(
            find_module_path_in_file(&lib.to_string_lossy(), 5, &src).as_deref(),
            Some("outer")
        );

        let _ = fs::remove_dir_all(crate_dir);
    }

    #[test]
    fn find_module_path_in_file_ignores_modules_inside_macro_invocation_bodies() {
        let crate_dir = unique_temp_dir("macro_invocation_body");
        let src = crate_dir.join("src");
        let lib = src.join("lib.rs");

        write_file(
            &lib,
            "mod outer {\n    generated! {\n        mod fake {\n            pub fn hidden() {}\n        }\n    }\n\n    mod inner {\n        pub fn marker() {}\n    }\n}\n",
        );

        assert_eq!(
            find_module_path_in_file(&lib.to_string_lossy(), 4, &src).as_deref(),
            Some("outer")
        );
        assert_eq!(
            find_module_path_in_file(&lib.to_string_lossy(), 8, &src).as_deref(),
            Some("outer::inner")
        );

        let _ = fs::remove_dir_all(crate_dir);
    }

    #[test]
    fn find_module_path_in_file_ignores_modules_inside_macro_invocations_for_all_delimiters() {
        let crate_dir = unique_temp_dir("macro_invocation_delimiters");
        let src = crate_dir.join("src");
        let lib = src.join("lib.rs");

        for (label, open, close) in [
            ("brace", "{", "}"),
            ("paren", "(", ")"),
            ("bracket", "[", "]"),
        ] {
            write_file(
                &lib,
                &format!(
                    "mod outer {{\n    generated!{open}\n        mod fake {{\n            pub fn hidden() {{}}\n        }}\n    {close};\n\n    mod inner {{\n        pub fn marker() {{}}\n    }}\n}}\n"
                ),
            );

            assert_eq!(
                find_module_path_in_file(&lib.to_string_lossy(), 4, &src).as_deref(),
                Some("outer"),
                "fake module should stay opaque for {label} delimiter"
            );
            assert_eq!(
                find_module_path_in_file(&lib.to_string_lossy(), 9, &src).as_deref(),
                Some("outer::inner"),
                "real nested module should resolve for {label} delimiter"
            );
        }

        let _ = fs::remove_dir_all(crate_dir);
    }

    #[test]
    fn find_module_path_invalidates_stale_line_cache_when_file_changes() {
        let crate_dir = unique_temp_dir("invalidate_cache");
        let src = crate_dir.join("src");
        let lib = src.join("lib.rs");

        write_file(
            &lib,
            "mod outer {\n    mod inner {\n        pub fn marker() {}\n    }\n}\n",
        );

        let lib_path = lib.to_string_lossy().to_string();
        let first = find_module_path(&lib_path, 3);
        assert_eq!(first.as_deref(), Some("outer::inner"));

        // Ensure the file metadata timestamp has a chance to advance on coarse filesystems.
        thread::sleep(Duration::from_millis(2));
        write_file(
            &lib,
            "mod changed {\n    mod deeper {\n        pub fn marker() {}\n    }\n}\n",
        );

        let second = find_module_path(&lib_path, 3);
        assert_eq!(second.as_deref(), Some("changed::deeper"));

        let _ = fs::remove_dir_all(crate_dir);
    }

    #[test]
    fn stale_line_entries_are_replaced_after_file_change() {
        let crate_dir = unique_temp_dir("stale_line_entries");
        let src = crate_dir.join("src");
        let lib = src.join("lib.rs");

        write_file(
            &lib,
            "mod outer {\n    mod inner {\n        pub fn marker() {}\n    }\n}\n",
        );

        let lib_path = lib.to_string_lossy().to_string();
        let _ = find_module_path(&lib_path, 2);
        let _ = find_module_path(&lib_path, 3);
        assert_eq!(cache::line_cache_entries_for(&lib_path), 2);

        // Ensure the file metadata timestamp has a chance to advance on coarse filesystems.
        thread::sleep(Duration::from_millis(2));
        write_file(
            &lib,
            "mod changed {\n    mod deeper {\n        pub fn marker() {}\n    }\n}\n",
        );

        let refreshed = find_module_path(&lib_path, 3);
        assert_eq!(refreshed.as_deref(), Some("changed::deeper"));
        assert_eq!(cache::line_cache_entries_for(&lib_path), 1);

        let second_line = find_module_path(&lib_path, 2);
        assert_eq!(second_line.as_deref(), Some("changed::deeper"));
        assert_eq!(cache::line_cache_entries_for(&lib_path), 2);

        let _ = fs::remove_dir_all(crate_dir);
    }

    #[test]
    fn find_module_path_handles_non_src_fixture_files_with_nested_modules() {
        let crate_dir = unique_temp_dir("non_src_fixture");
        let tests_ui = crate_dir.join("tests").join("ui");
        let fixture = tests_ui.join("fixture.rs");

        write_file(
            &fixture,
            "pub mod public_flow {\n    #[allow(dead_code)]\n    pub struct Machine;\n}\n",
        );

        assert_eq!(
            find_module_path(&fixture.to_string_lossy(), 3).as_deref(),
            Some("fixture::public_flow")
        );

        let _ = fs::remove_dir_all(crate_dir);
    }

    #[test]
    fn find_module_path_handles_nested_trybuild_style_fixture() {
        let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../statum-macros/tests/ui/valid_helper_trait_visibility.rs");

        assert_eq!(
            find_module_path(&fixture.to_string_lossy(), 30).as_deref(),
            Some("valid_helper_trait_visibility::public_flow")
        );
        assert_eq!(
            find_module_path(&fixture.to_string_lossy(), 39).as_deref(),
            Some("valid_helper_trait_visibility::public_flow")
        );
        assert_eq!(
            find_module_path(&fixture.to_string_lossy(), 103).as_deref(),
            Some("valid_helper_trait_visibility::crate_flow")
        );
    }

    #[test]
    fn find_module_path_handles_sibling_trybuild_modules() {
        let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../statum-macros/tests/ui/valid_matrix.rs");

        assert_eq!(
            find_module_path(&fixture.to_string_lossy(), 18).as_deref(),
            Some("valid_matrix::simple")
        );
        assert_eq!(
            find_module_path(&fixture.to_string_lossy(), 47).as_deref(),
            Some("valid_matrix::data_state")
        );
        assert_eq!(
            find_module_path(&fixture.to_string_lossy(), 69).as_deref(),
            Some("valid_matrix::wrappers_option")
        );
        assert_eq!(
            find_module_path(&fixture.to_string_lossy(), 113).as_deref(),
            Some("valid_matrix::validators_sync")
        );
    }
}