raf-source 0.0.0

Workspace source index: a Tree file seam with disk and memory backends under canonical path containment.
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
// SPDX-FileCopyrightText: 2026 Blackcat InformaticsĀ® Inc. <paudley@blackcatinformatics.ca>
// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0

//! Actual query and surface admission boundaries of selected-route proofs.

use super::*;
use crate::exports::Surface;
use crate::meter::Meter;
use crate::resolve::Source;
use crate::{Budget, ExportError, ExportOptions, LoadOptions, MemoryTree, RelPath, Workspace};
use std::fmt::Write;

fn workspace() -> Workspace {
    workspace_with_suffix("")
}

fn workspace_with_suffix(extra: &str) -> Workspace {
    let source = include_str!("../../../../../fuzz/corpus/rustc-oracle/import_cycle_a_private_glob_does_not_finalize_a_returning_type.rs")
        .replace("pub(crate) const fn A() -> u32 { 1 }", "pub const fn A() -> u32 { 1 }")
        .replace("pub mod m2 {", "pub mod m2 {\npub use crate::m1::A as Bound;");
    let source = format!("{source}\npub use m2::Bound as Named;\n{extra}\n");
    let tree: MemoryTree = [
        (
            "Cargo.toml",
            "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        ),
        ("src/lib.rs", source.as_str()),
    ]
    .into_iter()
    .collect();
    Workspace::load(&tree, &["."]).expect("late import fixture")
}

fn query(ws: &Workspace, meter: &Meter, surface: bool) -> Result<(), ResolveError> {
    if surface {
        let target = ws.target_ids().next().expect("library");
        match Surface::new(
            ws.index(),
            target,
            "demo",
            &ExportOptions::default(),
            meter,
            &BTreeSet::new(),
        )
        .list()
        {
            Err(ExportError::Resolve(error)) => Err(error),
            other => panic!("expected semantic refusal from actual surface: {other:?}"),
        }
    } else {
        ws.index()
            .resolve("demo::Named", Some(Namespace::Value), None, meter)
            .map(|_| ())
    }
}

#[test]
fn selected_query_and_surface_proofs_admit_exact_work_and_release_all_scratch() {
    unresolved_import_read_refusals();
    derived_glob_fact_admission();
    let ws = workspace();
    for surface in [false, true] {
        let options = LoadOptions::default();
        let meter = Meter::query(&options);
        assert!(matches!(
            query(&ws, &meter, surface),
            Err(ResolveError::IndeterminateImport { .. })
        ));
        let usage = meter.usage();
        assert!(usage.work > 0 && usage.glob_bytes > 0);
        // Every proof's scratch has died even on semantic refusal.
        let memory = Transient::new(&meter);
        memory
            .charge(options.max_glob_bytes, &RelPath::root(), None)
            .expect("no proof scratch remains live");
        drop(memory);
        let mut exact = options;
        exact.max_query_work = usage.work;
        exact.max_glob_bytes = usage.glob_bytes;
        assert!(matches!(
            query(&ws, &Meter::query(&exact), surface),
            Err(ResolveError::IndeterminateImport { .. })
        ));
        let mut short_work = exact.clone();
        short_work.max_query_work -= 1;
        assert!(matches!(
            query(&ws, &Meter::query(&short_work), surface),
            Err(ResolveError::Budget {
                budget: Budget::Work,
                ..
            })
        ));
        exact.max_glob_bytes -= 1;
        assert!(matches!(
            query(&ws, &Meter::query(&exact), surface),
            Err(ResolveError::Budget {
                budget: Budget::GlobBytes,
                ..
            })
        ));
    }
}

fn derived_glob_fact_admission() {
    let mut source = "pub fn good() {}\n".to_owned();
    for family in ["r", "u"] {
        for at in 0..6 {
            writeln!(source, "pub mod {family}{at} {{").unwrap();
            for target in 0..6 {
                if at != target {
                    writeln!(source, "pub use crate::{family}{target}::*;").unwrap();
                }
            }
            writeln!(source, "pub use crate::{family}{at}::Absent::*;").unwrap();
            if family == "u" && at == 0 {
                source.push_str("pub use unknown_dependency::*;\n");
            }
            source.push_str("}\n");
        }
    }
    let tree = MemoryTree::from([
        (
            "Cargo.toml",
            "[package]\nname='demo'\nversion='0.1.0'\nedition='2021'\n",
        ),
        ("src/lib.rs", source.as_str()),
    ]);
    let workspace =
        Workspace::load(&tree, &["."]).expect("dense missing and unknown glob relation");
    let index = workspace.index();
    assert!(
        index
            .glob_facts
            .get()
            .is_some_and(|facts| !facts.broken.is_empty())
    );
    derived_glob_fact_build(&workspace);
    derived_glob_fact_query(index);
}

fn derived_glob_fact_build(workspace: &Workspace) {
    let index = workspace.index();
    let source = &workspace
        .files()
        .find(|file| file.path.as_str() == "src/lib.rs")
        .expect("fixture source")
        .text;
    let first = index.glob_imports[0];
    let decl = &index.uses[first];
    let build = |options: &LoadOptions| {
        let mut copy = index.clone();
        copy.lookups.built(false);
        let meter = Meter::new(options);
        // Conservatively reserve the prior load peak; no private resident
        // accounting is exposed merely to measure this construction stage.
        meter
            .globs(workspace.usage().glob_bytes, &decl.file, Some(decl.line))
            .expect("the conservative prior-peak reservation fits");
        copy.settle_glob_facts(&meter)?;
        copy.lookups_charged()?;
        let usage = meter.usage();
        let scratch = Transient::new(&meter);
        scratch
            .charge(
                options.max_glob_bytes - workspace.usage().glob_bytes,
                &decl.file,
                Some(decl.line),
            )
            .expect("only the conservative prior-peak reservation remains live");
        drop(scratch);
        assert_eq!(
            copy.resolve(
                "demo::good",
                None,
                None,
                &Meter::query(&LoadOptions::default())
            )
            .unwrap()
            .path,
            "demo::good"
        );
        Ok::<_, LoadError>(usage)
    };
    let spent = build(&LoadOptions::default()).expect("roomy derived graph");
    assert!(
        spent.item_bytes > 0 && spent.work > 0 && spent.glob_bytes > workspace.usage().glob_bytes
    );
    let exact = LoadOptions {
        max_item_bytes: spent.item_bytes,
        max_glob_bytes: spent.glob_bytes,
        max_work: spent.work,
        ..LoadOptions::default()
    };
    assert_eq!(build(&exact).expect("exact graph allowances"), spent);
    for budget in [Budget::ItemBytes, Budget::GlobBytes, Budget::Work] {
        let mut short = exact.clone();
        match budget {
            Budget::ItemBytes => short.max_item_bytes -= 1,
            Budget::GlobBytes => short.max_glob_bytes -= 1,
            Budget::Work => short.max_work -= 1,
            _ => unreachable!(),
        }
        let error = build(&short).expect_err("one unit below the actual graph reservation");
        assert!(
            matches!(error.kind, crate::LoadErrorKind::Budget { budget: got, .. } if got == budget),
            "{error}"
        );
        assert_eq!(error.file.as_str(), "src/lib.rs");
        assert!(
            source
                .lines()
                .nth(error.line.expect("responsible glob") - 1)
                .unwrap()
                .contains("use ")
        );
    }
}

fn derived_glob_fact_query(index: &Index) {
    let module = index.module_named("demo::r0", None).unwrap().unwrap();
    let (file, line) = index.module_site(module);
    let reads = [Source {
        module,
        ns: Namespace::Type,
        name: "Absent".into(),
    }];
    let query = |options: &LoadOptions| {
        let meter = Meter::query(options);
        let result = {
            let memory = Transient::new(&meter);
            index.unresolved_glob_read(
                &reads,
                Steps::QueryAt {
                    memory: &memory,
                    file: &file,
                    line,
                },
            )?
        };
        let spent = meter.usage();
        let memory = Transient::new(&meter);
        memory
            .charge(options.max_glob_bytes, &file, line)
            .expect("query scratch is released");
        Ok::<_, LoadError>((result, spent))
    };
    let (answer, spent) = query(&LoadOptions::default()).expect("roomy derived query");
    assert!(answer.is_some() && spent.glob_bytes > 0 && spent.work > 0);
    let exact = LoadOptions {
        max_glob_bytes: spent.glob_bytes,
        max_query_work: spent.work,
        ..LoadOptions::default()
    };
    assert_eq!(query(&exact).unwrap().0, answer);
    for budget in [Budget::GlobBytes, Budget::Work] {
        let mut short = exact.clone();
        match budget {
            Budget::GlobBytes => short.max_glob_bytes -= 1,
            Budget::Work => short.max_query_work -= 1,
            _ => unreachable!(),
        }
        let error = query(&short).expect_err("query refuses one unit short");
        assert!(
            matches!(error.kind, crate::LoadErrorKind::Budget { budget: got, .. } if got == budget),
            "{error}"
        );
    }
}

fn unresolved_import_read_refusals() {
    let tree: MemoryTree = [
        (
            "Cargo.toml",
            "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        ),
        (
            "src/lib.rs",
            "pub use crate::missing as A; pub fn good() {}",
        ),
    ]
    .into_iter()
    .collect();
    let ws = Workspace::load(&tree, &["."]).expect("a settled missing import loads");
    assert_eq!(
        ws.resolve("demo::good").expect("valid neighbour").path,
        "demo::good"
    );
    let index = ws.index();
    let root = index
        .module_named("demo", None)
        .expect("root lookup")
        .expect("root");
    let (file, line) = index.module_site(root);
    let missing = [Source {
        module: root,
        ns: Namespace::Type,
        name: "A".into(),
    }];
    for limited in [false, true] {
        let mut options = LoadOptions::default();
        if limited {
            options.max_item_bytes = 1;
        }
        let meter = Meter::query(&options);
        let error = index.unbound(
            &missing,
            &[],
            "demo::A",
            Steps::QueryItems {
                meter: &meter,
                file: &file,
                line,
            },
        );
        if limited {
            assert!(
                matches!(
                    error,
                    ResolveError::Budget {
                        budget: Budget::ItemBytes,
                        limit: 1,
                        ..
                    }
                ),
                "{error:?}"
            );
        } else {
            assert!(matches!(error, ResolveError::NotFound(_)), "{error:?}");
        }
    }
}

#[test]
fn native_query_layout_failure_is_reported_as_storage_without_allocating() {
    let meter = Meter::query(&LoadOptions::default());
    let memory = Transient::new(&meter);
    let file = RelPath::new("src/lib.rs").expect("source path");
    let mut admission = NativeAdmission::new(Steps::QueryAt {
        memory: &memory,
        file: &file,
        line: Some(13),
    });
    let mut values = Vec::<usize>::new();
    let error = purrdf_lex::allocation::Memory::new(&mut admission)
        .reserve(&mut values, usize::MAX)
        .expect_err("impossible native layout");
    let error = ResolveError::storage(admission.graph_error(error.into()));
    assert!(
        matches!(error, ResolveError::Storage { file: at, line: Some(13), what } if at == file && !what.is_empty())
    );
    assert_eq!(values, [] as [usize; 0]);
    assert_eq!(values.capacity(), 0);
    assert_eq!(meter.usage().glob_bytes, 0);
}

fn spill_workspace() -> Workspace {
    let mut source = "pub mod spill_source { pub fn x() {} }\n".to_owned();
    for route in 0..9 {
        writeln!(
            source,
            "pub mod route{route} {{ pub use crate::spill_source::*; }}"
        )
        .expect("write fixture module");
    }
    source.push_str("pub mod fan {\n");
    for route in 0..9 {
        writeln!(source, "pub use crate::route{route}::*;").expect("write fixture import");
    }
    source.push_str("}\n");
    workspace_with_suffix(&source)
}

#[test]
fn selected_path_proof_spills_on_real_routes_and_releases_its_scratch() {
    let ws = spill_workspace();
    let index = ws.index();
    assert!(index.has_late_imports);
    let root = index
        .module_named("demo", None)
        .expect("root lookup")
        .expect("root");
    let (file, line) = index.module_site(root);
    let options = LoadOptions::default();
    assert_eq!(
        index
            .resolve(
                "demo::fan::x",
                Some(Namespace::Value),
                None,
                &Meter::query(&options),
            )
            .expect("unrelated late import does not poison a genuine route")
            .path,
        "demo::spill_source::x"
    );
    let meter = Meter::query(&options);
    let memory = Transient::new(&meter);
    {
        let mut proof = Proof::new(
            index,
            Steps::QueryAt {
                memory: &memory,
                file: &file,
                line,
            },
        );
        proof
            .path(
                root,
                &["fan".to_owned(), "x".to_owned()],
                false,
                Namespace::Value,
                Heads::Local,
                None,
            )
            .expect("actual path seed");
        assert_eq!(proof.finish().expect("independent route proof"), None);
        assert!(proof.pending.is_empty());
        assert!(
            proof.pending.heap_capacity() > 0,
            "nine routes exceed inline storage"
        );
    }
    drop(memory);
    Transient::new(&meter)
        .charge(options.max_glob_bytes, &file, line)
        .expect("all proof and native spill storage was released");
}

struct SpillRun {
    result: Result<(), LoadError>,
    attempted: usize,
    pending: usize,
    capacity: usize,
    peak: usize,
}

fn select_real_routes(ws: &Workspace, limit: usize) -> SpillRun {
    let index = ws.index();
    let source = index
        .module_named("demo::spill_source", None)
        .expect("source lookup")
        .expect("source");
    let id = *index.scopes[source]["x"].defs[slot(Namespace::Value)]
        .keys()
        .next()
        .expect("genuine function");
    let fan = index
        .module_named("demo::fan", None)
        .expect("fan lookup")
        .expect("fan");
    let routes: Vec<_> = (0..9)
        .map(|route| {
            index
                .module_named(&format!("demo::route{route}"), None)
                .expect("route lookup")
                .expect("route")
        })
        .collect();
    let (file, line) = index.module_site(fan);
    let options = LoadOptions {
        max_glob_bytes: limit,
        ..LoadOptions::default()
    };
    let meter = Meter::query(&options);
    let memory = Transient::new(&meter);
    let steps = Steps::QueryAt {
        memory: &memory,
        file: &file,
        line,
    };
    let mut proof = Proof::new(index, steps);
    let mut attempted = 0;
    let result = routes.into_iter().try_for_each(|module| {
        attempted += 1;
        assert!(proof.select_at(module, Namespace::Value, "x", None, Some(fan), &[id], steps)?);
        Ok(())
    });
    let run = SpillRun {
        result,
        attempted,
        pending: proof.pending.len(),
        capacity: proof.pending.heap_capacity(),
        peak: meter.usage().glob_bytes,
    };
    drop(proof);
    drop(memory);
    Transient::new(&meter)
        .charge(limit, &file, line)
        .expect("successful and refused native pushes release all scratch");
    run
}

#[test]
fn selected_routes_admit_the_first_native_spill_exactly_and_refuse_before_mutation() {
    let ws = spill_workspace();
    let full = select_real_routes(&ws, usize::MAX);
    full.result.expect("unrestricted real selections");
    assert_eq!((full.attempted, full.pending), (9, 9));
    assert!(full.capacity > 0 && full.peak > 0);
    let exact = select_real_routes(&ws, full.peak);
    exact.result.expect("exact first-spill peak");
    assert_eq!(
        (exact.attempted, exact.pending, exact.peak),
        (9, 9, full.peak)
    );
    assert!(exact.capacity > 0);
    let short = select_real_routes(&ws, full.peak - 1);
    assert!(matches!(short.result, Err(LoadError {
        kind: crate::LoadErrorKind::Budget { budget: Budget::GlobBytes, limit }, ..
    }) if limit == full.peak - 1));
    assert_eq!((short.attempted, short.pending, short.capacity), (9, 8, 0));
}