pipecircuit-visualization 0.0.8

Code-derived architectural visualizations for Pipecircuit programs
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
use std::{error::Error, fs, path::PathBuf};

use quote::ToTokens as _;
use syn::{Attribute, ItemImpl, Type, TypePath, parse_quote, punctuated::Punctuated};

use super::*;

mod module_paths;

fn source_model(source: &str) -> Result<SourceModel, Box<dyn Error>> {
    let syntax = syn::parse_file(source)?;
    let mut model = SourceModel::new();
    model.read_items(
        &syntax.items,
        Vec::new(),
        Path::new("src"),
        Path::new("src"),
    )?;
    Ok(model)
}

fn read_source(source: &str) -> Result<(), ArchitectureError> {
    let syntax = match syn::parse_file(source) {
        Ok(syntax) => syntax,
        Err(error) => return Err(ArchitectureError::new(error.to_string())),
    };
    SourceModel::new().read_items(
        &syntax.items,
        Vec::new(),
        Path::new("src"),
        Path::new("src"),
    )
}

fn error_message<T>(result: Result<T, ArchitectureError>) -> String {
    match result {
        Ok(_) => "unexpected success".to_owned(),
        Err(error) => error.to_string(),
    }
}

fn temporary_root(name: &str) -> Result<PathBuf, Box<dyn Error>> {
    let root = std::env::temp_dir().join(format!(
        "pipecircuit-visualization-{name}-{}",
        std::process::id()
    ));
    if root.exists() {
        fs::remove_dir_all(&root)?;
    }
    fs::create_dir_all(root.join("src"))?;
    Ok(root)
}

#[test]
fn resolves_rust_paths_imports_reexports_and_globs() -> Result<(), Box<dyn Error>> {
    let model = source_model(
        r#"
        pub struct Root;
        pub mod east {
            pub struct East;
            pub struct Shared;
            pub mod nested {
                use crate::Root;
                use super::East as Renamed;
                use super::*;
                pub struct Local;
                pub type Alias = Local;
                pub union Storage { value: u64 }
            }
        }
        pub mod west {
            pub struct Shared;
        }
        pub mod exports {
            pub use crate::east::East;
        }
        pub mod consumer {
            use crate::exports::East;
            use crate::east::*;
            pub struct Consumer;
        }
        "#,
    )?;

    let nested = vec!["east".to_owned(), "nested".to_owned()];
    assert_eq!(
        model.resolve_path(&nested, &["crate".to_owned(), "Root".to_owned()])?,
        vec!["Root"]
    );
    assert_eq!(
        model.resolve_path(&nested, &["self".to_owned(), "Local".to_owned()])?,
        vec!["east", "nested", "Local"]
    );
    assert_eq!(
        model.resolve_path(&nested, &["super".to_owned(), "East".to_owned()])?,
        vec!["east", "East"]
    );
    assert_eq!(
        model.resolve_path(&nested, &["Renamed".to_owned()])?,
        vec!["east", "East"]
    );
    assert_eq!(
        model.resolve_path(&nested, &["Local".to_owned()])?,
        vec!["east", "nested", "Local"]
    );
    assert_eq!(
        model.resolve_path(&["consumer".to_owned()], &["East".to_owned()])?,
        vec!["east", "East"]
    );
    assert_eq!(
        model.resolve_path(&["consumer".to_owned()], &["Shared".to_owned()])?,
        vec!["east", "Shared"]
    );
    assert_eq!(
        model.resolve_path(&nested, &["Unknown".to_owned()])?,
        vec!["east", "nested", "Unknown"]
    );
    assert_eq!(
        model.resolve_import_target(&nested, &["Local".to_owned()])?,
        vec!["east", "nested", "Local"]
    );
    assert_eq!(
        model.resolve_import_target(&nested, &["Unknown".to_owned()])?,
        vec!["Unknown"]
    );
    assert_eq!(
        model.resolve_import_target(&[], &["crate".to_owned()])?,
        Vec::<String>::new()
    );
    assert_eq!(
        model.resolve_import_target(&[], &["missing".to_owned(), "Thing".to_owned()])?,
        vec!["missing", "Thing"]
    );
    assert_eq!(
        error_message(model.resolve_path(&[], &[])),
        "an empty Rust path was encountered"
    );
    assert_eq!(
        error_message(model.resolve_path(&[], &["super".to_owned(), "Root".to_owned()])),
        "path `super::Root` escaped the crate root"
    );
    assert_eq!(
        error_message(model.resolve_path(&["missing".to_owned()], &["Thing".to_owned()])),
        "module `crate::missing` was absent from the source model"
    );
    assert_eq!(
        error_message(model.resolve_import_target(&[], &[])),
        "an empty import path was encountered"
    );
    Ok(())
}

#[test]
fn rejects_ambiguous_glob_imports() -> Result<(), Box<dyn Error>> {
    let model = source_model(
        r#"
        mod east { pub struct Shared; }
        mod west { pub struct Shared; }
        mod consumer {
            use crate::east::*;
            use crate::west::*;
        }
        "#,
    )?;
    assert_eq!(
        error_message(model.resolve_path(&["consumer".to_owned()], &["Shared".to_owned()])),
        "path `Shared` was ambiguous through glob imports in `crate::consumer`"
    );
    Ok(())
}

#[test]
fn derives_plain_option_and_non_path_outcomes() -> Result<(), Box<dyn Error>> {
    let model = source_model(
        r#"
        enum Outcome { Complete, Waiting }
        struct Value;
        "#,
    )?;
    let plain: Type = syn::parse_str("Outcome")?;
    let option: Type = syn::parse_str("Option<Outcome>")?;
    let tuple: Type = syn::parse_str("(Value, Value)")?;

    assert_eq!(model.outcome_node(&[], &plain)?.label, "Outcome");
    assert_eq!(model.outcome_node(&[], &option)?.children.len(), 2);
    assert_eq!(
        model.outcome_node(&[], &tuple)?.label,
        tuple.to_token_stream().to_string()
    );
    assert_eq!(
        error_message(model.standard_outcome_node(&[], "Option", &PathArguments::None)),
        "outcome `Option` had no type arguments"
    );
    let wrong: Type = syn::parse_str("Option<Outcome, Value>")?;
    let Type::Path(wrong) = wrong else {
        return Ok(());
    };
    if let Some(segment) = wrong.path.segments.first() {
        assert_eq!(
            error_message(model.standard_outcome_node(&[], "Option", &segment.arguments)),
            "outcome `Option` had 2 type arguments instead of 1"
        );
    } else {
        return Err(std::io::Error::other("parsed type path had no segment").into());
    }
    let lifetime: Type = syn::parse_str("Option<'static>")?;
    let Type::Path(lifetime) = lifetime else {
        return Err(std::io::Error::other("Option was not parsed as a path").into());
    };
    if let Some(segment) = lifetime.path.segments.first() {
        assert_eq!(
            error_message(model.standard_outcome_node(&[], "Option", &segment.arguments)),
            "outcome `Option` had 0 type arguments instead of 1"
        );
    } else {
        return Err(std::io::Error::other("parsed Option path had no segment").into());
    }

    let empty_path = Type::Path(TypePath {
        qself: None,
        path: syn::Path {
            leading_colon: None,
            segments: Punctuated::new(),
        },
    });
    assert_eq!(
        error_message(model.outcome_node(&[], &empty_path)),
        "an outcome path had no segments"
    );
    Ok(())
}

#[test]
fn preserves_source_and_type_resolution_failures() -> Result<(), Box<dyn Error>> {
    let root = temporary_root("source-errors")?;
    fs::write(root.join("src/lib.rs"), "this is not Rust {")?;
    assert!(error_message(read_crate(&root)).contains("could not parse"));

    let missing = root.join("missing");
    assert!(error_message(read_crate(&missing)).contains("could not resolve"));

    fs::remove_file(root.join("src/lib.rs"))?;
    fs::create_dir(root.join("src/lib.rs"))?;
    assert!(error_message(read_crate(&root)).contains("could not read"));
    fs::remove_dir_all(&root)?;

    let model = source_model("struct Known;")?;
    let tuple: Type = syn::parse_str("(Known, Known)")?;
    assert_eq!(
        error_message(model.resolve_type(&[], &tuple)),
        "type `(Known , Known)` was not a named path"
    );
    let unknown: Type = syn::parse_str("Unknown")?;
    assert_eq!(
        error_message(model.resolve_type(&[], &unknown)),
        "type `Unknown` resolved to `crate::Unknown`, which was not declared in this crate"
    );
    let known: Type = syn::parse_str("Known")?;
    assert_eq!(
        error_message(model.resolve_type(&["missing".to_owned()], &known)),
        "module `crate::missing` was absent from the source model"
    );
    assert_eq!(
        error_message(model.outcome_node(&[], &unknown)),
        "type `Unknown` resolved to `crate::Unknown`, which was not declared in this crate"
    );
    let nested_unknown: Type = syn::parse_str("Result<Unknown, Known>")?;
    assert_eq!(
        error_message(model.outcome_node(&[], &nested_unknown)),
        "type `Unknown` resolved to `crate::Unknown`, which was not declared in this crate"
    );
    Ok(())
}

#[test]
fn preserves_import_resolution_failures() -> Result<(), Box<dyn Error>> {
    let model = source_model(
        r#"
        use super::*;
        struct Known;
        "#,
    )?;
    assert_eq!(
        error_message(model.resolve_path(&[], &["Unknown".to_owned()])),
        "path `super` escaped the crate root"
    );
    assert_eq!(
        error_message(
            model.resolve_import_target(&[], &["super".to_owned(), "Unknown".to_owned()])
        ),
        "path `super::Unknown` escaped the crate root"
    );
    Ok(())
}

#[test]
fn preserves_module_layout_failures_and_visited_files() -> Result<(), Box<dyn Error>> {
    let root = temporary_root("module-layout")?;
    fs::write(root.join("src/lib.rs"), "mod missing;")?;
    assert!(error_message(read_crate(&root)).contains("had no source"));

    fs::create_dir_all(root.join("src/duplicate"))?;
    fs::write(root.join("src/lib.rs"), "mod duplicate;")?;
    fs::write(root.join("src/duplicate.rs"), "pub struct Direct;")?;
    fs::write(root.join("src/duplicate/mod.rs"), "pub struct Nested;")?;
    assert!(error_message(read_crate(&root)).contains("had two possible source files"));

    fs::write(root.join("src/lib.rs"), "pub struct Root;")?;
    let mut model = SourceModel::new();
    model.read_module_file(&root.join("src/lib.rs"), Vec::new(), &root.join("src"))?;
    model.read_module_file(&root.join("src/lib.rs"), Vec::new(), &root.join("src"))?;
    assert_eq!(model.declarations.len(), 1);
    fs::remove_dir_all(&root)?;
    Ok(())
}

#[test]
fn rejects_duplicate_declarations_and_steps() -> Result<(), Box<dyn Error>> {
    let mut model = SourceModel::new();
    model.insert_declaration(&[], "Duplicate".to_owned(), DeclarationKind::Other)?;
    assert_eq!(
        error_message(model.insert_declaration(
            &[],
            "Duplicate".to_owned(),
            DeclarationKind::Other
        )),
        "type `crate::Duplicate` was declared more than once"
    );
    for source in [
        "enum Duplicate {} enum Duplicate {}",
        "struct Duplicate; struct Duplicate;",
        "union Duplicate { a: u8 } union Duplicate { b: u8 }",
        "type Duplicate = u8; type Duplicate = u16;",
    ] {
        assert!(error_message(read_source(source)).contains("was declared more than once"));
    }

    let root = temporary_root("duplicate-steps")?;
    fs::write(
        root.join("src/lib.rs"),
        r#"
        trait StateMachine {}
        trait StepInputOf<T> { type Outcome; }
        struct Machine;
        struct Input;
        enum Outcome { Done }
        impl StateMachine for Machine {}
        impl StepInputOf<Machine> for Input { type Outcome = Outcome; }
        impl StepInputOf<Machine> for Input { type Outcome = Outcome; }
        "#,
    )?;
    assert!(error_message(read_crate(&root)).contains("had more than one step"));
    fs::remove_dir_all(&root)?;
    Ok(())
}

#[test]
fn rejects_incomplete_state_machine_contracts() -> Result<(), Box<dyn Error>> {
    let root = temporary_root("incomplete-contracts")?;
    fs::write(
        root.join("src/lib.rs"),
        r#"
        trait StepInputOf<T> { type Outcome; }
        struct Machine;
        struct Input;
        enum Outcome { Done }
        impl StepInputOf<Machine> for Input { type Outcome = Outcome; }
        "#,
    )?;
    assert!(error_message(read_crate(&root)).contains("no StateMachine implementation"));

    fs::write(
        root.join("src/lib.rs"),
        r#"
        trait StateMachine {}
        trait StepInputOf<T> { type Outcome; }
        struct Machine;
        struct Input;
        impl StateMachine for Machine {}
        impl StepInputOf<Machine> for Input {}
        "#,
    )?;
    assert_eq!(
        error_message(read_crate(&root)),
        "a StepInputOf implementation did not declare its Outcome"
    );
    fs::remove_dir_all(&root)?;
    Ok(())
}

#[test]
fn rejects_every_incomplete_derived_contract() -> Result<(), Box<dyn Error>> {
    let root = temporary_root("derived-contract-errors")?;
    let cases = [
        (
            r#"
            trait StateMachine {}
            impl StateMachine for Missing {}
            "#,
            "type `Missing` resolved",
        ),
        (
            r#"
            trait StateMachine {}
            trait StepInputOf { type Outcome; }
            struct Machine;
            struct Input;
            enum Outcome { Done }
            impl StateMachine for Machine {}
            impl StepInputOf for Input { type Outcome = Outcome; }
            "#,
            "did not name its state machine",
        ),
        (
            r#"
            trait StateMachine {}
            trait StepInputOf<T> { type Outcome; }
            struct Input;
            enum Outcome { Done }
            impl StepInputOf<Missing> for Input { type Outcome = Outcome; }
            "#,
            "type `Missing` resolved",
        ),
        (
            r#"
            trait StateMachine {}
            trait StepInputOf<T> { type Outcome; }
            struct Machine;
            enum Outcome { Done }
            impl StateMachine for Machine {}
            impl StepInputOf<Machine> for Missing { type Outcome = Outcome; }
            "#,
            "type `Missing` resolved",
        ),
        (
            r#"
            trait StateMachine {}
            trait StepInputOf<T> { type Outcome; }
            struct Machine;
            struct Input;
            impl StateMachine for Machine {}
            impl StepInputOf<Machine> for Input { type Outcome = Missing; }
            "#,
            "type `Missing` resolved",
        ),
    ];
    for (source, expected) in cases {
        fs::write(root.join("src/lib.rs"), source)?;
        assert!(error_message(read_crate(&root)).contains(expected));
    }
    fs::remove_dir_all(&root)?;
    Ok(())
}

#[test]
fn parses_step_contract_components_exactly() {
    let inherent: ItemImpl = parse_quote!(impl Machine {});
    assert_eq!(trait_name(&inherent), None);
    assert_eq!(
        error_message(step_machine_type(&inherent)),
        "a StepInputOf implementation had no trait path"
    );

    let no_machine: ItemImpl = parse_quote!(impl StepInputOf for Input {});
    assert_eq!(
        error_message(step_machine_type(&no_machine)),
        "a StepInputOf implementation did not name its state machine"
    );

    let lifetime_only: ItemImpl = parse_quote!(impl StepInputOf<'static> for Input {});
    assert_eq!(
        error_message(step_machine_type(&lifetime_only)),
        "a StepInputOf implementation did not contain a state-machine type"
    );

    let mut empty_trait_path: ItemImpl = parse_quote!(impl StepInputOf<Machine> for Input {});
    if let Some((_, path, _)) = &mut empty_trait_path.trait_ {
        path.segments.clear();
    }
    assert_eq!(
        error_message(step_machine_type(&empty_trait_path)),
        "a StepInputOf implementation had an empty trait path"
    );

    let outcome_after_const: ItemImpl = parse_quote! {
        impl StepInputOf<Machine> for Input {
            const MARKER: u8 = 1;
            type Outcome = Result;
        }
    };
    assert_eq!(
        step_outcome_type(&outcome_after_const)
            .map(|outcome| outcome.to_token_stream())
            .map(|tokens| tokens.to_string()),
        Ok("Result".to_owned())
    );
}

#[test]
fn ignores_test_only_items_and_modules() -> Result<(), Box<dyn Error>> {
    let model = source_model(
        r#"
        #[cfg(test)] use crate::Missing;
        #[cfg(kani)] struct KaniOnly;
        #[cfg(test)] enum TestOnly { Variant }
        #[cfg(test)] union TestStorage { value: u64 }
        #[cfg(test)] type TestAlias = u64;
        #[cfg(test)] impl StateMachine for Missing {}
        #[cfg(test)] mod tests { struct Hidden; }
        struct Visible;
        "#,
    )?;
    assert_eq!(model.declarations.len(), 1);
    assert!(model.implementations.is_empty());
    assert!(model.declarations.contains_key(&vec!["Visible".to_owned()]));
    Ok(())
}

#[test]
fn qualifies_the_crate_root() {
    assert_eq!(qualified(&[]), "crate");
}

#[test]
fn distinguishes_cfg_attribute_forms() {
    let ordinary: Attribute = syn::parse_quote!(#[derive(Clone)]);
    let name_value: Attribute = syn::parse_quote!(#[cfg = "test"]);
    let test: Attribute = syn::parse_quote!(#[cfg(test)]);
    assert!(!test_only(&[ordinary]));
    assert!(!test_only(&[name_value]));
    assert!(test_only(&[test]));
}

#[test]
fn plain_declarations_render_without_children() -> Result<(), Box<dyn Error>> {
    let model = source_model("struct Value;")?;
    let value = model.resolve_type(&[], &syn::parse_str("Value")?)?;
    assert_eq!(declaration_node(value).children, Vec::new());
    Ok(())
}

#[test]
fn standard_library_outcomes_are_opaque_and_keep_their_resolved_identity()
-> Result<(), Box<dyn Error>> {
    let model = source_model(
        r#"
        use std::io::Error as IoError;
        use core::convert::Infallible;
        use alloc::string::String;
    "#,
    )?;
    for (syntax, expected) in [
        ("IoError", "std::io::Error"),
        ("std::io::Error", "std::io::Error"),
        ("Infallible", "core::convert::Infallible"),
        ("String", "alloc::string::String"),
    ] {
        let node = model.outcome_node(&[], &syn::parse_str(syntax)?)?;
        assert_eq!(node.label, expected);
        assert!(node.children.is_empty());
    }
    let node = model.outcome_node(&[], &syn::parse_str("Result<(), IoError>")?)?;
    assert_eq!(
        node.children
            .get(1)
            .and_then(|branch| branch.children.first())
            .map(|node| node.label.as_str()),
        Some("std::io::Error")
    );
    assert!(
        model
            .outcome_node(&[], &syn::parse_str("MissingLocal")?)
            .is_err()
    );
    let local = source_model(
        r#"
        mod std { pub mod io { pub enum Error { Retry, Refuse } } }
        use std::io::Error;
    "#,
    )?;
    let node = local.outcome_node(&[], &syn::parse_str("Error")?)?;
    assert_eq!(node.label, "Error");
    assert_eq!(
        node.children
            .iter()
            .map(|child| child.label.as_str())
            .collect::<Vec<_>>(),
        ["Retry", "Refuse"]
    );
    assert!(
        local
            .outcome_node(&[], &syn::parse_str("std::io::Missing")?)
            .is_err()
    );
    Ok(())
}