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
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
// SPDX-FileCopyrightText: 2026 Blackcat Informatics® Inc. <paudley@blackcatinformatics.ca>
// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0

//! The work and memory budgets of a load: the tokens of one file, the bytes a
//! load reads, the bytes of index records, the bytes of file facts, the bytes
//! of glob tables and the steps of glob table work. Each is shown at its
//! limit, where the load succeeds, and one over, where it is refused with a
//! `Budget` error that names the budget and the file.

use std::fmt::Write as _;

use raf_source::{
    Budget, LoadError, LoadErrorKind, LoadOptions, MemoryTree, PARSE_BYTES_PER_TOKEN, RelPath,
    Usage, Workspace, parse_source,
};

const DEMO: &str = "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n";

/// A token limit lowered for speed; the default behaves the same and is
/// checked on its own.
const TOKENS: usize = 100_000;

/// Options with the token limit lowered to [`TOKENS`].
fn lowered() -> LoadOptions {
    let mut options = LoadOptions::default();
    options.max_file_tokens = TOKENS;
    options
}

/// The tokens a load at the lowered limit counted.
fn tokens_at_lowered(text: &str) -> usize {
    load_with(&[("src/lib.rs", text)], &lowered())
        .unwrap_or_else(|error| panic!("loads: {error}"))
        .usage()
        .max_file_tokens
}

fn tree(files: &[(&str, &str)]) -> MemoryTree {
    let mut all = vec![("Cargo.toml", DEMO)];
    all.extend_from_slice(files);
    all.into_iter().collect()
}

fn load_with(files: &[(&str, &str)], options: &LoadOptions) -> Result<Workspace, LoadError> {
    Workspace::load_with(&tree(files), &["."], options)
}

fn usage(files: &[(&str, &str)]) -> Usage {
    load_with(files, &LoadOptions::default())
        .unwrap_or_else(|error| panic!("loads: {error}"))
        .usage()
}

/// The budget and limit of a refusal, after checking that it names `file`.
fn refused(result: Result<Workspace, LoadError>, file: &str) -> (Budget, usize, Option<usize>) {
    let error = result.expect_err("over the budget");
    assert_eq!(error.file.as_str(), file, "{error}");
    match error.kind {
        LoadErrorKind::Budget { budget, limit } => {
            let text = error.to_string();
            assert!(
                text.contains(file) && text.contains(budget.name()),
                "{text}"
            );
            (budget, limit, error.line)
        }
        other => panic!("not a budget refusal: {other:?}"),
    }
}

/// `count` empty statements, each one token.
fn semis(count: usize) -> String {
    "; ".repeat(count)
}

/// A file of exactly `tokens` tokens: `head`, a body of empty statements that
/// pads it, and the closing brace. `head` opens a function body and holds
/// `head_tokens` tokens.
fn padded(head: &str, head_tokens: usize, tokens: usize) -> String {
    let pad = tokens - head_tokens - 1;
    format!("{head}{}}}\n", semis(pad))
}

/// `a<b; ` repeated, the comparison chain of the pre-scan's measurements.
fn comparisons(tokens: usize) -> String {
    // `fn f ( ) { let _ = a < b ;` is twelve tokens, each further `a<b;` four.
    let head = format!(
        "fn f() {{ let _ = {}",
        "a<b; ".repeat((tokens - 13) / 4 + 1)
    );
    let head_tokens = 8 + 4 * ((tokens - 13) / 4 + 1);
    padded(&head, head_tokens, tokens)
}

/// Statements that each name a type nested 64 generic arguments deep.
fn deep_generic_arguments(tokens: usize) -> String {
    let one = format!("let _: {}u8{}; ", "A<".repeat(64), ">".repeat(64));
    // `let _ :` is three tokens, `A <` two per level, `u8` one, `>` one per
    // level and `;` one.
    let per = 3 + 2 * 64 + 1 + 64 + 1;
    let count = (tokens - 7) / per;
    padded(
        &format!("fn f() {{ {}", one.repeat(count)),
        5 + per * count,
        tokens,
    )
}

/// A run of outer attributes on one function.
fn attribute_run(tokens: usize) -> String {
    // `#[a]` is four tokens; `fn f ( ) {` five.
    let count = (tokens - 6) / 4;
    padded(
        &format!("{}fn f() {{ ", "#[a] ".repeat(count)),
        4 * count + 5,
        tokens,
    )
}

/// The costliest shape the other budgets admit: one function body of a power of
/// two and one more empty statements, whose list of statements doubles its
/// storage for the last one, after a body that takes the remaining tokens.
fn statement_lists(tokens: usize) -> String {
    // `fn a ( ) {` and `}` are six tokens around each body.
    let big = (1_usize << (tokens - 13).ilog2()) + 1;
    let rest = tokens - big - 6;
    format!(
        "fn p() {{ {}}}\nfn a() {{ {}}}\n",
        semis(rest - 6),
        semis(big)
    )
}

#[test]
fn a_file_at_the_token_limit_parses_and_one_more_token_is_refused_naming_its_line() {
    // `m ! {` and `}` are four tokens around the identifiers.
    let at = format!("m!{{ {} }}\n", "a ".repeat(TOKENS - 4));
    assert_eq!(tokens_at_lowered(&at), TOKENS);
    let over = format!("m!{{ {}\n}}\n", "a ".repeat(TOKENS - 3));
    let error = load_with(&[("src/lib.rs", &over)], &lowered()).expect_err("one over");
    assert!(
        matches!(
            error.kind,
            LoadErrorKind::Budget {
                budget: Budget::FileTokens,
                limit: TOKENS
            }
        ),
        "{error}"
    );
    assert_eq!(error.file.as_str(), "src/lib.rs");
    assert_eq!(error.line, Some(2));
    // `parse_source` applies the default limit, refused before any parse.
    let file = RelPath::new("src/lib.rs").expect("path");
    let default = Budget::FileTokens.limit();
    let past_default = format!("m!{{ {}\n}}\n", "a ".repeat(default - 3));
    let error = parse_source(&file, &past_default, |_| ()).expect_err("over the default");
    assert!(
        matches!(
            error.kind,
            LoadErrorKind::Budget {
                budget: Budget::FileTokens,
                limit
            } if limit == default
        ),
        "{error}"
    );
    assert_eq!(error.line, Some(2));
}

/// A shape: a name and the text of it with a given number of tokens.
type Shape = (&'static str, fn(usize) -> String);

#[test]
fn each_costly_shape_at_the_token_limit_loads_and_one_more_token_is_refused() {
    let shapes: [Shape; 4] = [
        ("comparisons", comparisons),
        ("deep generic arguments", deep_generic_arguments),
        ("attribute run", attribute_run),
        ("statement lists", statement_lists),
    ];
    for (name, shape) in shapes {
        assert_eq!(tokens_at_lowered(&shape(TOKENS)), TOKENS, "{name}");
        let over = shape(TOKENS + 1);
        let (budget, limit, _) = refused(
            load_with(&[("src/lib.rs", &over)], &lowered()),
            "src/lib.rs",
        );
        assert_eq!((budget, limit), (Budget::FileTokens, TOKENS), "{name}");
    }
}

#[test]
fn a_doc_comment_counts_as_the_tokens_of_its_attribute_and_other_comments_count_nothing() {
    let text = "//! inner\n/*! inner block */\n/// outer\n/** outer block */\n\
                //// plain\n/*** plain */\n/**/\n// plain\nfn f() {}\n";
    // Seven for each inner doc comment, six for each outer one and six for
    // `fn f ( ) { }`.
    assert_eq!(
        usage(&[("src/lib.rs", text)]).max_file_tokens,
        7 + 7 + 6 + 6 + 6
    );
    // A file of doc comments alone passes the limit: each counts.
    let docs = format!("{}fn f() {{}}\n", "/// a\n".repeat(TOKENS / 6));
    let (budget, _, line) = refused(
        load_with(&[("src/lib.rs", &docs)], &lowered()),
        "src/lib.rs",
    );
    assert_eq!(budget, Budget::FileTokens);
    assert_eq!(line, Some(TOKENS / 6 + 1));
}

/// The facts of each adversarial fixture: a 1 MiB doc comment, a 1 MiB
/// written self type and a `use` group of long names, with the line of the
/// fact that holds the payload.
fn large_payloads() -> [(&'static str, String, usize); 3] {
    let long = |index: usize| format!("N{index}_{}", "x".repeat(64 * 1024));
    let names: Vec<String> = (0..16).map(long).collect();
    [
        (
            "doc comment",
            format!("/// {}\npub fn f() {{}}\n", "d".repeat(1 << 20)),
            1,
        ),
        (
            "written self type",
            format!(
                "pub trait Tr {{}}\nimpl Tr for ({}) {{}}\n",
                names.join(", ")
            ),
            2,
        ),
        (
            "use group",
            format!("use std::{{{}}};\n", names.join(", ")),
            1,
        ),
    ]
}

#[test]
fn each_large_fact_payload_is_charged_and_refused_at_its_line_once_over_the_fact_budget() {
    for (kind, text, line) in large_payloads() {
        let files = [("src/lib.rs", text.as_str())];
        let spent = usage(&files).fact_bytes;
        assert!(spent > 1 << 20, "{kind}: {spent}");
        // At the limit the load succeeds; one byte less is refused.
        let mut options = LoadOptions::default();
        options.max_fact_bytes = spent;
        load_with(&files, &options).unwrap_or_else(|e| panic!("{kind} at the limit: {e}"));
        options.max_fact_bytes = spent - 1;
        let (budget, limit, _) = refused(load_with(&files, &options), "src/lib.rs");
        assert_eq!((budget, limit), (Budget::FactBytes, spent - 1), "{kind}");
        // A limit below the payload is passed at the payload's own line.
        options.max_fact_bytes = 1 << 20;
        let (budget, _, at) = refused(load_with(&files, &options), "src/lib.rs");
        assert_eq!((budget, at), (Budget::FactBytes, Some(line)), "{kind}");
    }
}

#[test]
fn a_verbatim_use_group_and_a_bodiless_function_are_charged_as_their_plain_forms() {
    // The members of a `use` group that syn returns as tokens are charged as
    // the separate `use` declarations, and a function with no body as the
    // function with an empty one; each is refused at its line once over.
    let long = "x".repeat(64 * 1024);
    let pairs = [
        (
            format!("pub mod a {{ pub fn f() {{}} }}\npub use {{ ::std::{long}, crate::a::f }};\n"),
            format!(
                "pub mod a {{ pub fn f() {{}} }}\npub use ::std::{long};\npub use crate::a::f;\n"
            ),
            2,
        ),
        (
            format!(
                "pub struct S;\nimpl S {{\n    #[doc = \"{long}\"] pub fn new() -> &'static S;\n}}\n"
            ),
            format!(
                "pub struct S;\nimpl S {{\n    #[doc = \"{long}\"] pub fn new() -> &'static S {{}}\n}}\n"
            ),
            3,
        ),
        (
            format!(
                "pub struct S;\nimpl S {{\n    #[doc = \"{long}\"] pub fn new<T>() -> &'static S;\n}}\n"
            ),
            format!(
                "pub struct S;\nimpl S {{\n    #[doc = \"{long}\"] pub fn new<T>() -> &'static S {{}}\n}}\n"
            ),
            3,
        ),
    ];
    for (verbatim, plain, at) in &pairs {
        let files = [("src/lib.rs", verbatim.as_str())];
        let spent = usage(&files).fact_bytes;
        assert_eq!(
            spent,
            usage(&[("src/lib.rs", plain.as_str())]).fact_bytes,
            "{verbatim:.40}"
        );
        assert!(spent > 64 * 1024, "{spent}");
        let mut options = LoadOptions::default();
        options.max_fact_bytes = spent;
        load_with(&files, &options).unwrap_or_else(|e| panic!("at the limit: {e}"));
        options.max_fact_bytes = 64 * 1024;
        let (budget, _, line) = refused(load_with(&files, &options), "src/lib.rs");
        assert_eq!((budget, line), (Budget::FactBytes, Some(*at)));
    }
}

#[test]
fn the_fact_budget_counts_over_every_file_of_the_load() {
    let doc = format!("/// {}\npub fn f() {{}}\n", "d".repeat(4096));
    let files = [
        ("src/lib.rs", "mod a;\nmod b;\n"),
        ("src/a.rs", doc.as_str()),
        ("src/b.rs", doc.as_str()),
    ];
    let spent = usage(&files).fact_bytes;
    let mut options = LoadOptions::default();
    options.max_fact_bytes = spent;
    load_with(&files, &options).expect("at the limit");
    options.max_fact_bytes = spent - 1;
    // The second file passes the budget that the first left.
    let (budget, _, _) = refused(load_with(&files, &options), "src/b.rs");
    assert_eq!(budget, Budget::FactBytes);
}

#[test]
fn wide_discovery_and_member_frontiers_spill_under_the_item_budget() {
    let mut files = vec![(
        "Cargo.toml".to_owned(),
        "[workspace]\nmembers = [\"p*\"]\nresolver = \"2\"\n".to_owned(),
    )];
    for n in 0..10 {
        files.push((
            format!("p{n}/Cargo.toml"),
            format!("[package]\nname = \"p{n}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n"),
        ));
        files.push((format!("p{n}/src/lib.rs"), "pub fn member() {}".to_owned()));
    }
    // Discovery queues all ten sibling packages; wildcard expansion queues
    // the same ten matches. Both actual LIFO frontiers exceed eight inline
    // entries before popping the first child.
    let tree: MemoryTree = files
        .iter()
        .map(|(path, text)| (path.as_str(), text.as_str()))
        .collect();
    let mut options = LoadOptions::default();
    options.max_glob_bytes = 0;
    options.max_work = 0;
    let ws = Workspace::load_with(&tree, &["."], &options).expect("wide no-import workspace");
    let spent = ws.usage();
    assert_eq!(spent.glob_bytes, 0);
    assert_eq!(spent.work, 0);
    assert_eq!(ws.target_ids().count(), 10);
    options.max_item_bytes = spent.item_bytes;
    Workspace::load_with(&tree, &["."], &options).expect("exact item grant");
    options.max_item_bytes -= 1;
    let error = Workspace::load_with(&tree, &["."], &options).expect_err("one item byte less");
    assert!(
        matches!(error.kind, LoadErrorKind::Budget { budget: Budget::ItemBytes, limit } if limit == spent.item_bytes - 1)
    );
}

#[test]
fn nested_definition_emission_spills_with_only_the_item_budget() {
    // Each entered inline module leaves its parent's Rest and Mods frames
    // pending. Twelve levels therefore exceed the native eight-frame inline
    // stack without any imports or import-settling storage.
    let source = format!(
        "{}pub fn leaf() {{}}{}",
        "pub mod a {".repeat(12),
        "}".repeat(12)
    );
    let files = [("src/lib.rs", source.as_str())];
    let mut options = LoadOptions::default();
    options.max_glob_bytes = 0;
    options.max_work = 0;
    let spent = load_with(&files, &options)
        .expect("definition-only stack spill")
        .usage();
    assert_eq!(spent.glob_bytes, 0);
    assert_eq!(spent.work, 0);
    assert!(spent.item_bytes > 0);
    options.max_item_bytes = spent.item_bytes;
    load_with(&files, &options).expect("exact item grant");
    options.max_item_bytes -= 1;
    let (budget, limit, _) = refused(load_with(&files, &options), "src/lib.rs");
    assert_eq!(budget, Budget::ItemBytes);
    assert_eq!(limit, spent.item_bytes - 1);
}

#[test]
fn index_records_at_the_item_budget_load_and_one_byte_less_is_refused() {
    let files = [
        (
            "src/lib.rs",
            "pub mod a;\npub use a::f as g;\npub fn top() {}\n",
        ),
        (
            "src/a.rs",
            "pub fn f() {}\npub struct S;\nimpl S { pub fn m() {} }\n",
        ),
    ];
    let spent = usage(&files).item_bytes;
    let mut options = LoadOptions::default();
    options.max_item_bytes = spent;
    load_with(&files, &options).expect("at the limit");
    options.max_item_bytes = spent - 1;
    let error = load_with(&files, &options).expect_err("one byte over");
    assert!(
        matches!(
            error.kind,
            LoadErrorKind::Budget {
                budget: Budget::ItemBytes,
                limit
            } if limit == spent - 1
        ),
        "{error}"
    );
    assert!(
        error.to_string().contains(Budget::ItemBytes.name()),
        "{error}"
    );
    // The last records charged are the members of the impl block in `a.rs`.
    assert_eq!(error.file.as_str(), "src/a.rs", "{error}");
    assert_eq!(error.line, Some(3), "{error}");
}

#[test]
fn a_long_module_name_is_charged_in_every_item_path_and_refused_over_the_item_budget() {
    let name = format!("m{}", "x".repeat(64 * 1024));
    let fns = (0..100).fold(String::new(), |mut text, i| {
        writeln!(text, "    pub fn f{i}() {{}}").expect("write to a string");
        text
    });
    let text = format!("pub mod {name} {{\n{fns}}}\n");
    let files = [("src/lib.rs", text.as_str())];
    // Each of the hundred item paths holds the long name.
    assert!(usage(&files).item_bytes > 100 * 64 * 1024);
    let mut options = LoadOptions::default();
    options.max_item_bytes = 1 << 20;
    let (budget, limit, line) = refused(load_with(&files, &options), "src/lib.rs");
    assert_eq!((budget, limit), (Budget::ItemBytes, 1 << 20));
    assert!(line.is_some_and(|line| line > 1), "{line:?}");
}

#[test]
fn a_file_reached_by_many_module_paths_is_charged_once_per_path_and_refused_over_the_item_budget() {
    let fns = (0..100).fold(String::new(), |mut text, i| {
        writeln!(text, "pub fn f{i}() {{}}").expect("write to a string");
        text
    });
    let decls = (0..100).fold(String::new(), |mut text, i| {
        writeln!(text, "#[path = \"leaf.rs\"] pub mod p{i};").expect("write to a string");
        text
    });
    let files = [
        ("src/lib.rs", decls.as_str()),
        ("src/leaf.rs", fns.as_str()),
    ];
    let spent = usage(&files).item_bytes;
    // Ten thousand items, a few hundred bytes each at the least.
    assert!(spent > 100 * 100 * 256, "{spent}");
    let mut options = LoadOptions::default();
    options.max_item_bytes = spent / 2;
    let (budget, _, _) = refused(load_with(&files, &options), "src/leaf.rs");
    assert_eq!(budget, Budget::ItemBytes);
}

#[test]
fn the_bytes_read_at_the_total_budget_load_and_one_byte_less_is_refused_naming_the_file() {
    let padding = format!("// {}\npub fn f() {{}}\n", "p".repeat(1000));
    let files = [
        ("src/lib.rs", "pub mod a;\n"),
        ("src/a.rs", padding.as_str()),
    ];
    let spent = usage(&files).total_bytes;
    assert_eq!(spent, DEMO.len() + "pub mod a;\n".len() + padding.len());
    let mut options = LoadOptions::default();
    options.max_total_bytes = spent;
    load_with(&files, &options).expect("at the limit");
    options.max_total_bytes = spent - 1;
    let (budget, limit, _) = refused(load_with(&files, &options), "src/a.rs");
    assert_eq!((budget, limit), (Budget::TotalBytes, spent - 1));
    // The manifests count too: a limit below the manifest refuses it.
    options.max_total_bytes = DEMO.len() - 1;
    let (budget, _, _) = refused(load_with(&files, &options), "Cargo.toml");
    assert_eq!(budget, Budget::TotalBytes);
}

#[test]
fn the_default_budgets_are_the_stated_limits() {
    let options = LoadOptions::default();
    assert_eq!(options.max_file_tokens, Budget::FileTokens.limit());
    assert_eq!(Budget::FileTokens.limit(), 2_000_000);
    // The recommended limit for a host with little memory keeps one file's
    // parse peak below 512 MiB.
    assert_eq!(PARSE_BYTES_PER_TOKEN, 1664);
    const { assert!(320_000 * PARSE_BYTES_PER_TOKEN <= 512 << 20) };
    assert_eq!(options.max_total_bytes, Budget::TotalBytes.limit());
    assert_eq!(options.max_item_bytes, Budget::ItemBytes.limit());
    assert_eq!(options.max_fact_bytes, Budget::FactBytes.limit());
    assert_eq!(options.max_glob_bytes, Budget::GlobBytes.limit());
    assert_eq!(Budget::TotalBytes.limit(), 256 << 20);
    assert_eq!(Budget::ItemBytes.limit(), 512 << 20);
    assert_eq!(Budget::FactBytes.limit(), 256 << 20);
    assert_eq!(Budget::GlobBytes.limit(), 512 << 20);
    assert_eq!(options.max_work, Budget::Work.limit());
    assert_eq!(Budget::Work.limit(), 1 << 31);
    assert_eq!(Budget::DirectoryDepth.limit(), 128);
}

#[test]
fn usage_reports_what_a_load_spent() {
    // A root package with a `[workspace]` table, so discovery walks below it.
    let manifest = format!("{DEMO}[workspace]\n");
    let tree: MemoryTree = [
        ("Cargo.toml", manifest.as_str()),
        ("src/lib.rs", "pub mod a;\n"),
        ("src/a/mod.rs", "pub fn f() {}\n"),
    ]
    .into_iter()
    .collect();
    let spent = Workspace::load(&tree, &["."]).expect("loads").usage();
    assert_eq!(
        spent.total_bytes,
        manifest.len() + "pub mod a;\n".len() + "pub fn f() {}\n".len()
    );
    assert!(spent.item_bytes > 0 && spent.fact_bytes > 0);
    // `pub fn f ( ) { }` is seven tokens.
    assert_eq!(spent.max_file_tokens, 7);
    // `fn` and `(`, then the body's `{` and the level it opens.
    assert_eq!(spent.max_recursion, 4);
    // Discovery entered `src/a`, two levels below the root.
    assert_eq!(spent.max_directory_depth, 2);
    // A load without glob imports makes no glob table work.
    assert_eq!(spent.work, 0);
}

/// A library whose `leaf.rs` is reached under 2^`levels` module paths: each
/// level's file declares the next one twice. `leaf` is the leaf's text.
fn reached_many_times(levels: usize, leaf: &str) -> Vec<(String, String)> {
    let mut files = vec![(
        "src/lib.rs".to_owned(),
        "#[path = \"l0.rs\"]\npub mod a;\n".to_owned(),
    )];
    for level in 0..levels {
        let next = if level + 1 == levels {
            "leaf.rs".to_owned()
        } else {
            format!("l{}.rs", level + 1)
        };
        files.push((
            format!("src/l{level}.rs"),
            format!("#[path = \"{next}\"]\npub mod a;\n#[path = \"{next}\"]\npub mod b;\n"),
        ));
    }
    files.push(("src/leaf.rs".to_owned(), leaf.to_owned()));
    files
}

fn item_bytes_of(files: &[(String, String)]) -> usize {
    let borrowed: Vec<(&str, &str)> = files
        .iter()
        .map(|(path, text)| (path.as_str(), text.as_str()))
        .collect();
    usage(&borrowed).item_bytes
}

#[test]
fn a_long_alias_path_in_a_file_reached_many_times_is_held_and_charged_once() {
    // Twenty thousand segments, about half a megabyte once owned.
    let long = format!("pub type T = {}a;\n", "a::".repeat(20_000));
    let short = "pub type T = a;\n";
    let arrivals = 8;
    let charged = item_bytes_of(&reached_many_times(arrivals, &long))
        - item_bytes_of(&reached_many_times(arrivals, short));
    let owned = 20_000 * (size_of::<String>() + 1);
    // Charged once, not once for each of the 256 module paths.
    assert!(
        charged >= owned && charged < 2 * owned,
        "{charged} for {owned}"
    );
}

#[test]
fn a_long_extern_crate_name_in_a_file_reached_many_times_is_held_and_charged_once() {
    let name = format!("c{}", "x".repeat(64 * 1024));
    let long = format!("extern crate {name} as x;\n");
    let short = "extern crate c as x;\n";
    let arrivals = 8;
    let charged = item_bytes_of(&reached_many_times(arrivals, &long))
        - item_bytes_of(&reached_many_times(arrivals, short));
    // The short name `c` is charged in the neighbour too.
    let owned = name.len() - 1;
    assert!(
        charged >= owned && charged < 2 * owned,
        "{charged} for {owned}"
    );
}

#[test]
fn a_chain_of_files_that_each_declare_the_next_twice_is_charged_what_it_keeps() {
    // Twelve levels: 8191 arrivals of the module walk, two modules and their
    // items at each arrival but the last, and one item at each of those.
    let files = reached_many_times(12, "pub type T = a;\n");
    let arrivals = (1 << 13) - 1;
    // A load of this shape keeps 1511 bytes of index for each arrival,
    // measured with a counting allocator in a release build over 131071
    // arrivals; what it is charged must cover that.
    let kept = 1_511 * arrivals;
    let charged = item_bytes_of(&files);
    assert!(charged >= kept, "{charged} charged for {kept} kept");
}

#[test]
fn nested_inline_modules_whose_scopes_hold_one_name_are_charged_what_they_keep() {
    // Twenty modules, each holding a chain of a hundred inline modules `a`:
    // 2020 modules whose scope tables hold one name each.
    let one = format!("{}{}", "mod a { ".repeat(100), " }".repeat(100));
    let text: String = (0..20).fold(String::new(), |mut text, i| {
        writeln!(text, "mod b{i} {{ {one} }}").expect("write to a string");
        text
    });
    let modules = 20 * 101;
    // Such a load keeps 1443 bytes of index for each module, measured with a
    // counting allocator in a release build over 202000 of them; what it is
    // charged must cover that, as every charge is an upper bound of the
    // allocations it covers.
    let kept = 1_443 * modules;
    let charged = usage(&[("src/lib.rs", &text)]).item_bytes;
    assert!(charged >= kept, "{charged} charged for {kept} kept");
}

/// A library whose module `big` defines `names` functions and whose
/// `importers` modules each glob it.
fn glob_fan(names: usize, importers: usize) -> String {
    let mut text = String::from("pub mod big {\n");
    for i in 0..names {
        writeln!(text, "    pub fn f{i}() {{}}").expect("write to a string");
    }
    text.push_str("}\n");
    for i in 0..importers {
        writeln!(text, "pub mod g{i} {{ pub use super::big::*; }}").expect("write to a string");
    }
    text
}

/// A library of `length` modules, each globbing the next, the last defining
/// one function.
fn glob_chain(length: usize) -> String {
    let mut text = String::new();
    for i in 0..length {
        writeln!(text, "mod m{i} {{ pub use super::m{}::*; }}", i + 1).expect("write to a string");
    }
    writeln!(text, "pub mod m{length} {{ pub fn f() {{}} }}").expect("write to a string");
    text
}

/// A library of `count` modules that each glob the crate root, which globs
/// each of them, each defining one function: every module brings in every
/// name of every other.
fn mutual_globs(count: usize) -> String {
    let mut text = String::new();
    for i in 0..count {
        writeln!(
            text,
            "pub use m{i}::*;\npub mod m{i} {{ pub use crate::*; pub fn g{i}() {{}} }}"
        )
        .expect("write to a string");
    }
    text
}

/// A crate in the shape of a generated binding crate: a private module of
/// `children` modules, each of a foreign type and methods, twelve of them
/// named as in every other child, each child globbing its parent, the parent
/// globbing each child and the root globbing the parent.
fn generated_bindings(children: usize) -> Vec<(String, String)> {
    let mut files = vec![(
        "src/lib.rs".to_owned(),
        "mod features;\npub use features::*;\npub fn top() {}\n".to_owned(),
    )];
    let mut parent = String::new();
    for i in 0..children {
        writeln!(parent, "mod gen_{i};\npub use gen_{i}::*;").expect("write to a string");
        let mut child = format!("use super::*;\nextern \"C\" {{\n    pub type T{i};\n");
        for m in 0..12 {
            writeln!(
                child,
                "    pub fn m{m}(this: &T{i});\n    pub fn own_{i}_{m}(this: &T{i});"
            )
            .expect("write to a string");
        }
        child.push_str("}\n");
        files.push((format!("src/features/gen_{i}.rs"), child));
    }
    files.push(("src/features/mod.rs".to_owned(), parent));
    files
}

fn glob_bytes_of(text: &str) -> usize {
    usage(&[("src/lib.rs", text)]).glob_bytes
}

#[test]
fn retained_import_reads_and_blocker_cycles_obey_exact_storage_and_work_limits() {
    for (text, path, target) in [
        (
            "pub mod a { pub struct T; }\npub use a::T as Alias;\n",
            "demo::Alias",
            Some("demo::a::T"),
        ),
        (
            "pub mod a { pub struct T; }\n\
             pub mod b { pub(crate) use crate::a::*; }\n\
             pub mod c { pub use crate::a::*; pub use crate::b::*; }\n\
             pub use c::T as Alias;\n",
            "demo::Alias",
            Some("demo::a::T"),
        ),
        (
            "pub mod a { pub struct T; }\n\
             pub mod b { pub use crate::a::*; pub use self::T; }\n",
            "demo::b::T",
            Some("demo::a::T"),
        ),
        (
            "pub mod gate {\n\
             pub mod a { pub(in crate::gate) struct T; }\n\
             pub mod b { pub(in crate::gate) use super::a::*; }\n\
             pub(in crate::gate) use b::T as Alias;\n}\n",
            "demo::gate::Alias",
            Some("demo::gate::a::T"),
        ),
        (
            "pub mod a { pub use crate::b::T; }\n\
             pub mod b { pub use crate::a::T; }\n",
            "demo::a::T",
            None,
        ),
    ] {
        let files = [("src/lib.rs", text)];
        let workspace =
            load_with(&files, &LoadOptions::default()).expect("loads without an artificial limit");
        if let Some(target) = target {
            assert_eq!(
                workspace
                    .resolve(path)
                    .expect("valid neighboring import")
                    .path,
                target
            );
        } else {
            assert!(matches!(
                workspace.resolve(path),
                Err(raf_source::ResolveError::Cyclic(_))
            ));
        }
        let spent = workspace.usage();
        assert!(
            spent.glob_bytes > 0 && spent.work > 0,
            "retained import reads are charged even without a glob"
        );
        for (budget, exact) in [
            (Budget::GlobBytes, spent.glob_bytes),
            (Budget::Work, spent.work),
        ] {
            let mut options = LoadOptions::default();
            match budget {
                Budget::GlobBytes => options.max_glob_bytes = exact,
                Budget::Work => options.max_work = exact,
                _ => unreachable!("the two resolver budgets"),
            }
            let at_limit = load_with(&files, &options)
                .expect("the exact simultaneous reservation is admitted");
            assert_eq!(at_limit.usage(), spent);
            // Query budgets remain independent of exhausted load budgets.
            assert_eq!(at_limit.resolve(path), workspace.resolve(path));
            match budget {
                Budget::GlobBytes => options.max_glob_bytes -= 1,
                Budget::Work => options.max_work -= 1,
                _ => unreachable!("the two resolver budgets"),
            }
            let (refused_budget, limit, line) = refused(load_with(&files, &options), "src/lib.rs");
            assert_eq!((refused_budget, limit), (budget, exact - 1));
            let line = line.expect("the responsible import line");
            assert!(
                text.lines()
                    .nth(line - 1)
                    .is_some_and(|line| line.contains("use ")),
                "{line}: {text}"
            );
            load_with(&files, &LoadOptions::default())
                .expect("a refusal does not contaminate another load");
        }
    }
}

#[test]
fn glob_tables_at_the_glob_budget_load_and_one_byte_less_is_refused() {
    let text = "pub mod a { pub fn f() {} pub struct S; }\n\
                pub mod b { pub use crate::a::*; }\n\
                pub mod c { pub use crate::b::*; }\n";
    let files = [("src/lib.rs", text)];
    let spent = usage(&files).glob_bytes;
    assert!(spent > 0, "a load with globs charges its glob tables");
    let mut options = LoadOptions::default();
    options.max_glob_bytes = spent;
    let ws = load_with(&files, &options).expect("at the limit");
    assert_eq!(
        ws.resolve("demo::c::f").expect("resolves").path,
        "demo::a::f"
    );
    options.max_glob_bytes = spent - 1;
    let (budget, limit, line) = refused(load_with(&files, &options), "src/lib.rs");
    assert_eq!((budget, limit), (Budget::GlobBytes, spent - 1));
    // The glob of `b` or of `c` passes the limit.
    assert!(matches!(line, Some(2 | 3)), "{line:?}");
    // A load without any import needs neither retained import reads nor tables.
    assert_eq!(glob_bytes_of("pub mod a { pub fn f() {} }\n"), 0);
}

#[test]
fn glob_table_work_at_the_work_budget_loads_and_one_step_less_is_refused() {
    let text = "pub mod a { pub fn f() {} pub struct S; }\n\
                pub mod b { pub use crate::a::*; }\n\
                pub mod c { pub use crate::b::*; }\n";
    let files = [("src/lib.rs", text)];
    // This includes retained reads and import queue work as well as table
    // reconstruction. Operation-level tests count those populations separately.
    let spent = usage(&files).work;
    assert!(spent > 0);
    let mut options = LoadOptions::default();
    options.max_work = spent;
    let ws = load_with(&files, &options).expect("at the limit");
    assert_eq!(
        ws.resolve("demo::c::f").expect("resolves").path,
        "demo::a::f"
    );
    assert_eq!(ws.usage().work, spent);
    options.max_work = spent - 1;
    let (budget, limit, line) = refused(load_with(&files, &options), "src/lib.rs");
    assert_eq!((budget, limit), (Budget::Work, spent - 1));
    // The final retained-read traversal is attributed to the glob of `b`.
    assert_eq!(line, Some(2));
    let error = load_with(&files, &options).expect_err("over the budget");
    assert!(
        error.to_string().contains(&format!(
            "exceeds the budget for glob table work steps ({})",
            spent - 1
        )),
        "{error}"
    );
    // No import means no import-settling work. Named-only import boundaries
    // are exercised with the same two budgets above.
    options.max_work = 0;
    let ws = load_with(&[("src/lib.rs", "pub mod a { pub fn f() {} }\n")], &options)
        .expect("no import-settling work");
    assert_eq!(ws.usage().work, 0);
}

#[test]
fn a_module_that_many_modules_glob_is_kept_once_for_all_of_them() {
    // A thousand names globbed by one module and by four hundred: each more
    // importer reads the one table of the module, and costs that read, not a
    // copy of the thousand names.
    let one = glob_bytes_of(&glob_fan(1000, 1));
    let many = glob_bytes_of(&glob_fan(1000, 400));
    let per_importer = (many - one) / 399;
    assert!(
        per_importer < 1024,
        "{per_importer} bytes for each importer of a thousand names"
    );
    assert!(one > 1000 * 64, "{one} bytes for a thousand names");
}

#[test]
fn a_chain_of_globs_is_charged_what_each_link_brings_in() {
    // Each link of a chain of globs brings in one name, so twice the links
    // cost twice the bytes, not four times.
    let short = glob_bytes_of(&glob_chain(1000));
    let long = glob_bytes_of(&glob_chain(2000));
    assert!(
        long < 2 * short + short / 10,
        "{long} bytes for 2000 links, {short} for 1000"
    );
    let ws = load_with(
        &[("src/lib.rs", &glob_chain(2000))],
        &LoadOptions::default(),
    )
    .expect("loads");
    assert_eq!(
        ws.resolve("demo::m0::f").expect("resolves").path,
        "demo::m2000::f"
    );
}

#[test]
fn modules_that_glob_one_another_are_refused_over_the_glob_budget_naming_a_glob() {
    // Each of 200 modules brings in all 400 names of the others, which the
    // tables hold once for each module; a limit of 4 MiB refuses them, and
    // allows 20.
    let mut options = LoadOptions::default();
    options.max_glob_bytes = 4 << 20;
    let text = mutual_globs(200);
    let (budget, limit, line) =
        refused(load_with(&[("src/lib.rs", &text)], &options), "src/lib.rs");
    assert_eq!((budget, limit), (Budget::GlobBytes, 4 << 20));
    let line = line.expect("the line of a glob");
    assert!(
        text.lines()
            .nth(line - 1)
            .is_some_and(|glob| glob.contains("::*;")),
        "{line}"
    );
    let ws = load_with(&[("src/lib.rs", &mutual_globs(20))], &options).expect("loads");
    assert_eq!(
        ws.resolve("demo::m0::g19").expect("resolves").path,
        "demo::m19::g19"
    );
}

#[test]
fn glob_tables_of_a_generated_binding_crate_are_charged_what_they_keep() {
    // Two hundred children of one module, each globbing it, read one table
    // of all that the module brings in. Such a load keeps 1976740 bytes of
    // glob tables, measured with a counting allocator in a release build;
    // what it is charged must cover that, as every charge is an upper bound
    // of the allocations it covers.
    let files = generated_bindings(200);
    let borrowed: Vec<(&str, &str)> = files
        .iter()
        .map(|(path, text)| (path.as_str(), text.as_str()))
        .collect();
    let ws = load_with(&borrowed, &LoadOptions::default()).expect("loads");
    let charged = ws.usage().glob_bytes;
    assert!(charged >= 1_976_740, "{charged} charged");
    assert_eq!(
        ws.resolve("demo::T7").expect("resolves").path,
        "demo::features::gen_7::T7"
    );
}

/// A library whose module `a` defines `names` structs, whose module `t` globs
/// `a` `globs` times over and whose module `u` globs `t`, with `u` declared
/// first when `u_first`.
fn repeated_globs(names: usize, globs: usize, u_first: bool) -> Vec<(String, String)> {
    let mut a = String::new();
    for i in 0..names {
        writeln!(a, "pub struct S{i};").expect("write to a string");
    }
    let lib = if u_first {
        "pub mod u;\npub mod a;\npub mod t;\n"
    } else {
        "pub mod a;\npub mod t;\npub mod u;\n"
    };
    vec![
        ("src/lib.rs".to_owned(), lib.to_owned()),
        ("src/a.rs".to_owned(), a),
        (
            "src/t.rs".to_owned(),
            "pub use crate::a::*;\n".repeat(globs),
        ),
        ("src/u.rs".to_owned(), "pub use crate::t::*;\n".to_owned()),
    ]
}

fn borrowed(files: &[(String, String)]) -> Vec<(&str, &str)> {
    files
        .iter()
        .map(|(path, text)| (path.as_str(), text.as_str()))
        .collect()
}

#[test]
fn repeated_globs_of_one_module_are_charged_once_for_what_it_holds() {
    // `t` globs a module of 2000 names 400 times over, which rustc accepts,
    // and `u` globs `t`. Every glob of `t` reads the one table of `a`, and
    // gathering what `t` exports reads that table once, so each more glob
    // costs its read and not a copy of the 2000 names, whichever module is
    // declared first.
    for u_first in [false, true] {
        let one = usage(&borrowed(&repeated_globs(2000, 1, u_first))).glob_bytes;
        let files = repeated_globs(2000, 400, u_first);
        let ws = load_with(&borrowed(&files), &LoadOptions::default()).expect("loads");
        let many = ws.usage().glob_bytes;
        let per_glob = (many - one) / 399;
        assert!(
            per_glob < 1024,
            "{per_glob} bytes for each more glob of two thousand names ({u_first})"
        );
        assert_eq!(
            ws.resolve("demo::u::S1999").expect("resolves").path,
            "demo::a::S1999"
        );
        // Below what the tables take, the load is refused by the glob budget.
        let mut options = LoadOptions::default();
        options.max_glob_bytes = many - 1;
        let error = load_with(&borrowed(&files), &options).expect_err("over the budget");
        assert!(
            matches!(
                error.kind,
                LoadErrorKind::Budget {
                    budget: Budget::GlobBytes,
                    ..
                }
            ),
            "{error}"
        );
    }
}

#[test]
fn an_impl_block_is_charged_its_record_and_what_it_holds() {
    let without = usage(&[("src/lib.rs", "pub struct S;\n")]).item_bytes;
    let with = usage(&[("src/lib.rs", "pub struct S;\nimpl S {}\n")]).item_bytes;
    // Native amortized storage holds multiple complete records, in addition
    // to what attaching the impl retains.
    assert!(
        with - without >= 2 * size_of::<raf_source::ImplBlock>(),
        "{} charged for a record of {}",
        with - without,
        size_of::<raf_source::ImplBlock>()
    );
    let source = "pub struct S;\n\
        impl S { pub fn a() {} }\n\
        impl S { pub fn b() {} }\n\
        impl S { pub fn c() {} }\n\
        impl S { pub fn d() {} }\n\
        impl S { pub fn e() {} }\n\
        impl S { pub fn f() {} }\n\
        impl S { pub fn g() {} }\n\
        impl S { pub fn h() {} }\n\
        impl S { pub fn i() {} }\n";
    let files = [("src/lib.rs", source)];
    let exact = usage(&files).item_bytes;
    let mut options = LoadOptions::default();
    options.max_item_bytes = exact;
    assert_eq!(
        load_with(&files, &options)
            .expect("all retained arrays admitted at the exact grant")
            .impls()
            .count(),
        9
    );
    options.max_item_bytes = exact - 1;
    assert_eq!(
        refused(load_with(&files, &options), "src/lib.rs"),
        (Budget::ItemBytes, exact - 1, Some(10))
    );
}