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
use super::constitution::*;
use crate::module_scan::{SymbolPrefix, canonical_module_path, package_name_to_import_ident};
use serde_json::Value;
use xuanji::{Polarity, RuleKey, ScanDepth, Severity};
/// A boundary over the intra-crate module import graph — the layering Cargo cannot
/// see. Observed from the target crate's source `use` declarations (PROJECT.md).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModuleBoundary {
/// The crate the governed module lives in, by package name.
pub(crate) crate_package: String,
/// The governed module path as declared; a spelling other than the canonical one is refused at evaluation.
pub(crate) module: String,
/// What the boundary forbids, restricts, or confines.
pub(crate) rule: ModuleRule,
/// The declared intent the boundary protects, carried on every violation as the repair direction.
pub(crate) reason: String,
/// Whether a violation fails the reaction (`Enforce`) or is only reported (`Warn`).
pub(crate) severity: Severity,
/// A durable governance pointer, distinct from `reason`; `None` unless `with_anchor` sets one.
pub(crate) anchor: Option<String>,
/// How far below `module` the boundary observes; a `Shallow` depth enters its rule key, `Subtree` does not.
pub(crate) depth: ScanDepth,
}
impl ModuleBoundary {
/// Begin a module boundary within the crate named `package`.
pub fn in_crate(package: &str) -> ModuleBoundaryBuilder {
ModuleBoundaryBuilder {
crate_package: package.to_string(),
}
}
/// The scan depth / granularity recorded with the boundary.
pub fn scan_depth(&self) -> ScanDepth {
self.depth
}
/// Stable semantic identity for this declared module boundary.
pub fn rule_key(&self) -> RuleKey {
let key = self.rule.key();
if self.depth == ScanDepth::Shallow {
RuleKey::of(
key.rule_type(),
key.fields()
.chain(std::iter::once(("scan_depth", self.depth.as_str()))),
)
} else {
key
}
}
/// The rule this boundary declares, exposed read-only for projection and model inspection.
pub fn rule(&self) -> &ModuleRule {
&self.rule
}
/// The human-readable reason recorded with the boundary (the repair hint).
pub fn reason(&self) -> &str {
&self.reason
}
/// The governed module path (e.g. `"crate::kernel"`).
pub fn module(&self) -> &str {
&self.module
}
}
/// What a module boundary forbids.
///
/// Rules are constructed through [`ModuleBoundary::in_crate`], not variant struct expressions. A
/// consumer can inspect a builder-produced rule without closing over its complete representation:
///
/// ```
/// use guibiao::{ModuleBoundary, ModuleRule};
///
/// let boundary = ModuleBoundary::in_crate("app")
/// .module("crate::core")
/// .must_not_import("crate::adapter")
/// .because("core depends inward only");
/// match boundary.rule() {
/// ModuleRule::MustNotImport { module, .. } => assert_eq!(module, "crate::adapter"),
/// _ => unreachable!(),
/// }
/// ```
///
/// ```compile_fail
/// use guibiao::ModuleRule;
///
/// let _ = ModuleRule::MustNotImport { module: "crate::adapter".to_string() };
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ModuleRule {
/// The governed module must not import this module (or anything beneath it).
#[non_exhaustive]
MustNotImport {
/// The forbidden module path (e.g. `"crate::projection"`).
module: String,
},
/// The governed module may import only these modules (each "or beneath"), plus its
/// own subtree; any other internal import is a violation. An empty allowlist permits
/// only the module's own subtree.
#[non_exhaustive]
RestrictImportsTo {
/// The closed allowlist of importable module paths (e.g. `["crate::types"]`).
allowed: Vec<String>,
},
/// The governed (protected) module must not be imported by this module (or anything
/// beneath it) — an inbound encapsulation rule, the mirror of `MustNotImport`. A
/// module within the protected module's own subtree is never an importer.
#[non_exhaustive]
MustNotBeImportedBy {
/// The forbidden importer module path (e.g. `"crate::http"`).
importer: String,
},
/// The governed (protected) module may be imported only by these importers (each "or
/// beneath") or by its own subtree; any other module that imports it (or anything beneath
/// it) is a violation — the inbound dual of `RestrictImportsTo`. An empty allowlist permits
/// only the protected module's own subtree.
#[non_exhaustive]
MustOnlyBeImportedBy {
/// The closed allowlist of importer module paths (e.g. `["crate::facade"]`).
allowed: Vec<String>,
},
/// An **external** crate may be imported only within the governed module's own subtree
/// (the permitted subtree, or beneath it); any `use <crate_name>::…` from a module
/// outside that subtree is a violation. The first module rule that observes external
/// imports — every other rule ignores them. The confined crate is the violation target,
/// so identity stays injective across different confined crates on the same subtree.
#[non_exhaustive]
ConfineExternalCrate {
/// The confined external crate name (e.g. `"libc"`).
crate_name: String,
},
/// Within the governed module's subtree, forbid inline symbol-path **calls** resolving under
/// a declared module-path prefix — the inline-symbol-path (layer b) sibling of
/// [`ConfineExternalCrate`](ModuleRule::ConfineExternalCrate), observing *calls* rather than
/// `use` imports. The "core reads no ambient clock; time is injected" pattern. The confined
/// prefix is the violation target, so identity stays injective across nested prefixes on the
/// same subtree.
#[non_exhaustive]
ConfineInlineSymbolPath {
/// The confined module-path prefix (e.g. `"std::time"`).
prefix: String,
/// If `Some`, react only on calls whose terminal segment (leaf-exact) is one of these
/// verbs (e.g. `["now"]`); `None` reacts on every call under the prefix. Adopter-owned:
/// a read reachable only through an undeclared verb is a false negative the adopter
/// accepts by narrowing.
ending_with: Option<Vec<String>>,
/// If `true`, react on **any** path under the prefix (mentions included — type
/// annotations, constants, value captures), not only calls. Mutually exclusive with
/// `ending_with` (both set is a constitution error).
strict: bool,
/// If `true`, resolve a bare path head matching a declared dependency as external after
/// local precedence checks. Projection metadata and scan breadth only; never identity.
strict_external: bool,
},
/// Inline symbol-path **calls** resolving under a declared module-path prefix are **permitted only** within the
/// governed module's subtree: a call anywhere else in any compiled root of the package is a violation. The
/// permitting dual of [`ConfineInlineSymbolPath`](ModuleRule::ConfineInlineSymbolPath), as
/// [`ConfineExternalCrate`](ModuleRule::ConfineExternalCrate) permits a crate's imports only within its
/// subtree. The same scanner, the same facts and the same modifiers; the governed module names the permitted
/// region rather than the judged one, so its perimeter is the whole package and a root without the module has
/// an empty permitted region. The confined prefix is the violation target.
#[non_exhaustive]
ConfineInlineCall {
/// The confined module-path prefix (e.g. `"std::process::Command"`).
prefix: String,
/// If `Some`, react only on calls whose terminal segment (leaf-exact) is one of these verbs; `None` reacts
/// on every call under the prefix.
ending_with: Option<Vec<String>>,
/// If `true`, react on any path under the prefix outside the permitted region, mentions included.
/// Mutually exclusive with `ending_with`.
strict: bool,
/// If `true`, resolve a bare path head matching a declared dependency as external. Projection metadata and
/// scan breadth only; never identity.
strict_external: bool,
},
}
/// The permitting inline-confinement text projection: where the confined prefix may be used, rather than where it
/// may not.
pub(crate) fn inline_permission_text(
prefix: &str,
ending_with: &Option<Vec<String>>,
strict: bool,
) -> String {
match (ending_with, strict) {
(_, true) => {
format!(
"confines naming inline under {prefix} to this module's subtree (strict: mentions too)"
)
}
(Some(verbs), false) => format!(
"confines inline calls under {prefix} ending with {} to this module's subtree",
verbs.join(", ")
),
(None, false) => format!("confines inline calls under {prefix} to this module's subtree"),
}
}
/// The inline-confinement text projection. Neither it nor [`ModuleRule::label`] is identity;
/// [`ModuleRule::key`] carries the semantic rule identity.
pub(crate) fn inline_confinement_text(
prefix: &str,
ending_with: &Option<Vec<String>>,
strict: bool,
) -> String {
match (ending_with, strict) {
(_, true) => format!("must not name inline under {prefix} (strict: mentions too)"),
(Some(verbs), false) => format!(
"must not call inline under {prefix} ending with: {}",
verbs.join(", ")
),
(None, false) => format!("must not call inline under {prefix}"),
}
}
/// The inline-confinement JSON parameters. `strict_external` is emitted only when set, matching the emit-when-set
/// discipline of `ending_with`/`strict` — a strict boundary must not project byte-identically to a
/// default one. This is projection metadata only; it never leaks into [`ModuleRule::label`].
pub(crate) fn inline_confinement_json(
prefix: &str,
ending_with: &Option<Vec<String>>,
strict: bool,
external: bool,
) -> Vec<(&'static str, Value)> {
let mut params = vec![("confined_prefix", serde_json::json!(prefix))];
if let Some(verbs) = ending_with {
params.push(("ending_with", serde_json::json!(verbs)));
}
if strict {
params.push(("strict", serde_json::json!(true)));
}
if external {
params.push(("strict_external", serde_json::json!(true)));
}
params
}
impl ModuleRule {
/// Stable semantic identity for this declared module rule.
pub fn key(&self) -> RuleKey {
match self {
ModuleRule::MustNotImport { module } => RuleKey::of(
"tianheng.rule/guibiao/must-not-import",
[("module", canonical_module_path(module))],
),
ModuleRule::RestrictImportsTo { allowed } => RuleKey::of(
"tianheng.rule/guibiao/restrict-imports-to",
[("allowed", canonical_module_set(allowed))],
),
ModuleRule::MustNotBeImportedBy { importer } => RuleKey::of(
"tianheng.rule/guibiao/must-not-be-imported-by",
[("importer", canonical_module_path(importer))],
),
ModuleRule::MustOnlyBeImportedBy { allowed } => RuleKey::of(
"tianheng.rule/guibiao/must-only-be-imported-by",
[("allowed", canonical_module_set(allowed))],
),
ModuleRule::ConfineExternalCrate { crate_name } => RuleKey::of(
"tianheng.rule/guibiao/confine-external-crate",
[(
"crate",
package_name_to_import_ident(&canonical_module_path(crate_name)),
)],
),
ModuleRule::ConfineInlineSymbolPath {
prefix,
ending_with,
strict,
strict_external: _,
} => RuleKey::of(
"tianheng.rule/guibiao/confine-inline-symbol-path",
[
(
"ending_with",
canonical_set(
ending_with
.iter()
.flat_map(|values| values.iter())
.map(|verb| canonical_module_path(verb)),
),
),
("prefix", SymbolPrefix::of(prefix).path),
("strict", strict.to_string()),
],
),
ModuleRule::ConfineInlineCall {
prefix,
ending_with,
strict,
strict_external: _,
} => RuleKey::of(
"tianheng.rule/guibiao/confine-inline-call",
[
(
"ending_with",
canonical_set(
ending_with
.iter()
.flat_map(|values| values.iter())
.map(|verb| canonical_module_path(verb)),
),
),
("prefix", SymbolPrefix::of(prefix).path),
("strict", strict.to_string()),
],
),
}
}
/// The label feeding the violation `rule` string and the projection — one source.
pub(crate) fn label(&self) -> &'static str {
match self {
ModuleRule::MustNotImport { .. } => "module must not import",
ModuleRule::RestrictImportsTo { .. } => "restrict imports to",
ModuleRule::MustNotBeImportedBy { .. } => "module must not be imported by",
ModuleRule::MustOnlyBeImportedBy { .. } => "module may only be imported by",
ModuleRule::ConfineExternalCrate { .. } => "external crate confined to module",
ModuleRule::ConfineInlineSymbolPath { .. } => "inline symbol path confined to module",
ModuleRule::ConfineInlineCall { .. } => "inline symbol path permitted only in module",
}
}
/// The inline-confinement payload — `(prefix, ending_with, strict, external)` — or `None` for a
/// non-inline rule. Dispatch and the exit-2 constitution checks route through this accessor; the only
/// `external`-conditional behavior lives in the scan (`UnitScan::findings` / `resolve_written`).
pub(crate) fn inline_payload(&self) -> Option<(&str, Option<&[String]>, bool, bool)> {
match self {
ModuleRule::ConfineInlineSymbolPath {
prefix,
ending_with,
strict,
strict_external,
} => Some((prefix, ending_with.as_deref(), *strict, *strict_external)),
ModuleRule::ConfineInlineCall {
prefix,
ending_with,
strict,
strict_external,
} => Some((prefix, ending_with.as_deref(), *strict, *strict_external)),
_ => None,
}
}
/// Where a violation of this rule can lie, which decides whether a compiled root without the
/// governed module is judged at all.
pub(crate) fn perimeter(&self) -> Perimeter {
match self {
ModuleRule::MustNotImport { .. }
| ModuleRule::RestrictImportsTo { .. }
| ModuleRule::MustNotBeImportedBy { .. }
| ModuleRule::MustOnlyBeImportedBy { .. }
| ModuleRule::ConfineInlineSymbolPath { .. } => Perimeter::GovernedModule,
ModuleRule::ConfineExternalCrate { .. } | ModuleRule::ConfineInlineCall { .. } => {
Perimeter::WholeRoot
}
}
}
/// The repair-direction [`Polarity`] of a violation of this rule. The two `MustNot*` rules
/// forbid a specific module edge (repair: remove the import) → `DenyBreach`; `RestrictImportsTo`,
/// `MustOnlyBeImportedBy`, and `ConfineExternalCrate` permit a region and react to an edge
/// outside it (repair: move the import into the permitted subtree, or widen) → `AllowlistGap`.
pub(crate) fn polarity(&self) -> Polarity {
match self {
ModuleRule::MustNotImport { .. } | ModuleRule::MustNotBeImportedBy { .. } => {
Polarity::DenyBreach
}
ModuleRule::RestrictImportsTo { .. }
| ModuleRule::MustOnlyBeImportedBy { .. }
| ModuleRule::ConfineExternalCrate { .. }
| ModuleRule::ConfineInlineCall { .. } => Polarity::AllowlistGap,
ModuleRule::ConfineInlineSymbolPath { .. } => Polarity::DenyBreach,
}
}
/// The human-readable rule text with its parameter, for the text projection.
pub(crate) fn text(&self) -> String {
match self {
ModuleRule::MustNotImport { module } => format!("must not import {module}"),
ModuleRule::RestrictImportsTo { allowed } if allowed.is_empty() => {
"restrict imports to nothing".to_string()
}
ModuleRule::RestrictImportsTo { allowed } => {
format!("restrict imports to: {}", allowed.join(", "))
}
ModuleRule::MustNotBeImportedBy { importer } => {
format!("must not be imported by {importer}")
}
ModuleRule::MustOnlyBeImportedBy { allowed } if allowed.is_empty() => {
"may only be imported by nothing".to_string()
}
ModuleRule::MustOnlyBeImportedBy { allowed } => {
format!("may only be imported by: {}", allowed.join(", "))
}
ModuleRule::ConfineExternalCrate { crate_name } => {
format!("confines external crate {crate_name} to this module's subtree")
}
ModuleRule::ConfineInlineSymbolPath {
prefix,
ending_with,
strict,
strict_external,
} => {
let text = inline_confinement_text(prefix, ending_with, *strict);
if *strict_external {
format!("{text} (strict-external)")
} else {
text
}
}
ModuleRule::ConfineInlineCall {
prefix,
ending_with,
strict,
strict_external,
} => {
let text = inline_permission_text(prefix, ending_with, *strict);
if *strict_external {
format!("{text} (strict-external)")
} else {
text
}
}
}
}
/// The JSON parameter fields for the projection. `must_not_import` names its single
/// `forbidden` path; `restrict_imports_to` emits its closed set as `only` (always,
/// as `[]` when empty), matching the crate-level restrict-to vocabulary;
/// `must_not_be_imported_by` names its declared forbidden `importer`;
/// `confine_external_crate` names the confined `external_crate`.
pub(crate) fn json_params(&self) -> Vec<(&'static str, Value)> {
match self {
ModuleRule::MustNotImport { module } => {
vec![("forbidden", serde_json::json!(module))]
}
ModuleRule::RestrictImportsTo { allowed } => {
vec![("only", serde_json::json!(allowed))]
}
ModuleRule::MustNotBeImportedBy { importer } => {
vec![("importer", serde_json::json!(importer))]
}
ModuleRule::MustOnlyBeImportedBy { allowed } => {
vec![("only_importers", serde_json::json!(allowed))]
}
ModuleRule::ConfineExternalCrate { crate_name } => {
vec![("external_crate", serde_json::json!(crate_name))]
}
ModuleRule::ConfineInlineSymbolPath {
prefix,
ending_with,
strict,
strict_external,
} => inline_confinement_json(prefix, ending_with, *strict, *strict_external),
ModuleRule::ConfineInlineCall {
prefix,
ending_with,
strict,
strict_external,
} => inline_confinement_json(prefix, ending_with, *strict, *strict_external),
}
}
}
/// Fluent builder for a [`ModuleBoundary`].
pub struct ModuleBoundaryBuilder {
/// The crate the governed module lives in, by package name.
crate_package: String,
}
impl ModuleBoundaryBuilder {
/// The module whose imports are governed (e.g. `"crate::kernel"`).
///
/// Every module path a module boundary carries — this one, and each module its rule names — is
/// written `crate` or `crate::` followed by `::`-separated identifiers (`r#x` is read as `x`). Any
/// other spelling is a constitution error suggesting the canonical one, and a named module must be
/// one some compiled root of the crate declares.
pub fn module(self, module: &str) -> ModuleTargetDraft {
ModuleTargetDraft {
crate_package: self.crate_package,
module: module.to_string(),
}
}
}
/// A module boundary awaiting its module rule.
pub struct ModuleTargetDraft {
/// The crate the governed module lives in, by package name.
crate_package: String,
/// The governed module as written; its spelling is judged when the boundary is checked.
module: String,
}
impl ModuleTargetDraft {
/// Forbid the governed module from importing `module` (or anything beneath it).
///
/// A `use`-glob is observed at its base module and retains its glob shape. A glob whose base is
/// equal to or an ancestor of the forbidden module (`use crate::*;` while forbidding
/// `crate::secret`) therefore reacts fail-closed, as do the narrow forms
/// (`use crate::secret;`, `use crate::secret::*;`). A plain non-glob ancestor import
/// (`use crate;`) remains clean because it does not bring the descendant into scope.
pub fn must_not_import(self, module: &str) -> ModuleBoundaryDraft {
self.with_rule(ModuleRule::MustNotImport {
module: module.to_string(),
})
}
/// Restrict the governed module's internal imports to a closed allowlist: any
/// internal `use` reaching a module that is neither within the governed module's
/// own subtree nor within an allowlist entry (each matched "or beneath") is a
/// violation. An empty allowlist permits only the module's own subtree. Governs
/// new internal modules by default, the module-level mirror of the crate-level
/// [`restrict_dependencies_to`](crate::CrateBoundaryBuilder::restrict_dependencies_to).
pub fn restrict_imports_to<I, S>(self, allowed: I) -> ModuleBoundaryDraft
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.with_rule(ModuleRule::RestrictImportsTo {
allowed: allowed.into_iter().map(Into::into).collect(),
})
}
/// Forbid the governed (protected) module from being imported by `importer` (or
/// anything beneath it) — an inbound encapsulation rule, the mirror of
/// [`must_not_import`](Self::must_not_import). A module within the protected module's
/// own subtree is never treated as an importer.
pub fn must_not_be_imported_by(self, importer: &str) -> ModuleBoundaryDraft {
self.with_rule(ModuleRule::MustNotBeImportedBy {
importer: importer.to_string(),
})
}
/// Restrict who may import the governed (protected) module to a closed allowlist: only a
/// listed importer (each "or beneath") or the protected module's own subtree may import it;
/// any other importer is a violation — the inbound dual of
/// [`restrict_imports_to`](Self::restrict_imports_to). An empty allowlist permits only the
/// module's own subtree.
pub fn must_only_be_imported_by<I, S>(self, allowed: I) -> ModuleBoundaryDraft
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.with_rule(ModuleRule::MustOnlyBeImportedBy {
allowed: allowed.into_iter().map(Into::into).collect(),
})
}
/// Confine an **external** crate's imports to the governed module's own subtree: any
/// `use <crate_name>::…` written from a module outside this module (or beneath it) is a
/// violation. This is the first module rule that observes external-crate imports — every
/// other rule ignores them. Only the named crate is observed (a `cargo metadata`
/// cross-check is deliberately *not* performed: confining a crate the target never imports
/// is simply clean). The confined crate is the violation target, so declaring two
/// confinements of different crates on the same module stays injective. Confining on
/// `crate` (the root) is a constitution error, since it would permit the crate everywhere.
///
/// The crate name may be written in either **package** form (`"windows-sys"`) or **import
/// identifier** form (`"windows_sys"`): the rule observes the source `use` identifier, in
/// which Cargo maps a package's `-` to `_`, so the confined name is matched with that same
/// fold. A raw identifier (`r#name`) is canonicalized as elsewhere.
pub fn confine_external_crate(self, crate_name: &str) -> ModuleBoundaryDraft {
self.with_rule(ModuleRule::ConfineExternalCrate {
crate_name: crate_name.to_string(),
})
}
/// Within the governed subtree, forbid inline symbol-path **calls** resolving under the
/// module-path `prefix` (e.g. `"std::time"`) — the inline-symbol-path (layer b) sibling of
/// [`confine_external_crate`](Self::confine_external_crate), for the "core reads no ambient
/// clock; time is injected" pattern. By default only a **call** (`prefix::…::verb(...)`)
/// reacts; a type annotation, a bare constant reference, and any non-call mention pass (so the
/// core may *receive* injected time), keeping 圭表 free of a built-in read-verb heuristic. The
/// returned [`InlineConfinementDraft`] is a dedicated draft — its `.ending_with` /
/// `.strict_prefix_only` modifiers cannot be applied to the other module rules.
///
/// A path's head resolves from its lexical scope — the nearest block or module binding, glob
/// edges followed to a fixed point, and the local `type`-alias and `pub use` re-export closure —
/// and a glob that can bring a prefix-resolving name into scope reacts fail-closed. Where the scan
/// stops, it says so: every stated bound is declared by [`crate::observation_bounds`] and projected
/// into `docs/observation-bounds.md`, never a silent pass.
///
/// The prefix of this and of [`confine_inline_call`](Self::confine_inline_call) is written as
/// `::`-separated identifiers (`r#x` is read as `x`), and a `crate::` prefix must name a module some
/// compiled root declares or an item one defines. A prefix starting elsewhere names another crate and is
/// not verified, unless the same path rooted at `crate` names something — then it is a constitution
/// error suggesting that spelling, as is any other spelling.
pub fn must_not_call_inline(self, prefix: &str) -> InlineConfinementDraft {
InlineConfinementDraft {
crate_package: self.crate_package,
module: self.module,
prefix: prefix.to_string(),
ending_with: None,
strict: false,
external: false,
permitted: false,
severity: Severity::Enforce,
depth: ScanDepth::Subtree,
}
}
/// Permit inline symbol-path **calls** resolving under the module-path `prefix` (e.g.
/// `"std::process::Command"`) **only** within the governed subtree: a call anywhere else in any compiled root
/// of the package is a violation. The permitting dual of [`must_not_call_inline`](Self::must_not_call_inline),
/// as [`confine_external_crate`](Self::confine_external_crate) permits a crate's imports only within its
/// subtree — "only `crate::exec` spawns a process".
///
/// The observation is `must_not_call_inline`'s: the same scanner, the same call-versus-mention default, the
/// same alias and glob resolution, and the same [`InlineConfinementDraft`] modifiers. What differs is the
/// region judged — every file of every compiled root outside the governed subtree — so a root whose graph has
/// no governed module is judged with an empty permitted region, and a package where no root declares it is a
/// constitution error. Confining to `crate` (the root) is a constitution error, since its subtree is the whole
/// crate and the rule could never react.
pub fn confine_inline_call(self, prefix: &str) -> InlineConfinementDraft {
InlineConfinementDraft {
permitted: true,
..self.must_not_call_inline(prefix)
}
}
/// The draft every non-inline rule method returns: `rule` over this target, enforced, at `Subtree` depth.
fn with_rule(self, rule: ModuleRule) -> ModuleBoundaryDraft {
ModuleBoundaryDraft {
crate_package: self.crate_package,
module: self.module,
rule,
severity: Severity::Enforce,
depth: ScanDepth::Subtree,
}
}
}
/// A module boundary awaiting its severity and reason.
pub struct ModuleBoundaryDraft {
/// The crate the governed module lives in, by package name.
crate_package: String,
/// The governed module as written; its spelling is judged when the boundary is checked.
module: String,
/// The rule the target draft's method chose, moved unchanged into the boundary.
rule: ModuleRule,
/// `Enforce` until `warn` makes the boundary advisory.
severity: Severity,
/// `Subtree` until `depth` changes it.
depth: ScanDepth,
}
impl ModuleBoundaryDraft {
/// Configure the observation scan depth / granularity level.
pub fn depth(mut self, depth: ScanDepth) -> Self {
self.depth = depth;
self
}
/// Convenience modifier setting the scan depth to [`ScanDepth::Subtree`].
///
/// Module rules retain their legacy subtree default, so this is a source-compatible
/// ergonomic spelling for existing declarations and an explicit override when a draft was
/// previously changed to [`ScanDepth::Shallow`].
pub fn including_submodules(self) -> Self {
self.depth(ScanDepth::Subtree)
}
/// Finish the boundary, recording the human-readable `reason` (the repair hint).
pub fn because(self, reason: &str) -> ModuleBoundary {
ModuleBoundary {
crate_package: self.crate_package,
module: self.module,
rule: self.rule,
reason: reason.to_string(),
severity: self.severity,
anchor: None,
depth: self.depth,
}
}
}
/// A dedicated draft for an inline-symbol-path confinement (from
/// [`must_not_call_inline`](ModuleTargetDraft::must_not_call_inline)). Distinct from
/// [`ModuleBoundaryDraft`] so its narrowing / escalation modifiers cannot be applied to the other
/// module rules (no modifier pollution). Chain [`ending_with`](Self::ending_with) **or**
/// [`strict_prefix_only`](Self::strict_prefix_only) (they are mutually exclusive), and
/// [`warn`](Self::warn), before [`because`](Self::because).
pub struct InlineConfinementDraft {
/// The crate the governed module lives in, by package name.
crate_package: String,
/// The governed module as written; its spelling is judged when the boundary is checked.
module: String,
/// The prefix as written, moved unchanged into the rule.
prefix: String,
/// The read verbs `ending_with` declares; `None` does not narrow by verb.
ending_with: Option<Vec<String>>,
/// Set by `strict_prefix_only`: any mention under the prefix reacts, not only a call.
strict: bool,
/// Set by `strict_external`: a bare head no scope binds that matches a declared dependency resolves as that crate.
external: bool,
/// Whether the governed module is the permitted region ([`ModuleRule::ConfineInlineCall`]) rather than the
/// judged one ([`ModuleRule::ConfineInlineSymbolPath`]).
permitted: bool,
/// `Enforce` until `warn` makes the boundary advisory.
severity: Severity,
/// `Subtree` until `depth` changes it.
depth: ScanDepth,
}
impl InlineConfinementDraft {
/// Configure the observation scan depth / granularity level.
pub fn depth(mut self, depth: ScanDepth) -> Self {
self.depth = depth;
self
}
/// Narrow the confinement to react only on calls whose **terminal segment** (leaf-exact) is
/// one of `verbs` (e.g. `["now"]`) — the adopter's declared read verbs. The adopter owns any
/// false negative from omitting a verb (a future `::current()` passes); the engine bakes in no
/// default verb set. Mutually exclusive with [`strict_prefix_only`](Self::strict_prefix_only):
/// declaring both is a constitution error (exit 2).
pub fn ending_with<I, S>(mut self, verbs: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.ending_with = Some(verbs.into_iter().map(Into::into).collect());
self
}
/// Escalate the confinement to react on **any** path under the prefix — mentions included
/// (type annotations, constants, value-position captures), not only calls. The whole-surface
/// isolation posture for a subtree that may not even name the module. Mutually exclusive with
/// [`ending_with`](Self::ending_with): declaring both is a constitution error (exit 2).
pub fn strict_prefix_only(mut self) -> Self {
self.strict = true;
self
}
/// **Opt-in.** Resolve a written path's bare head that matches a **declared dependency name**
/// (rename-aware, `-`→`_`-normalized to its import identifier) as that external crate — so a
/// **fully-qualified, un-`use`d external call** (`chrono::Utc::now()` with no `use chrono`)
/// resolving under the confined prefix reacts. Without it a sysroot head (`std`/`core`/`alloc`)
/// is caught while a fully-qualified external head, which no scope binds, names nothing — a
/// stated non-observation under the default.
///
/// The flag has a second effect: the existing glob-hazard reaction **extends** to external-crate
/// globs. A `use chrono::*;` under a `chrono::…` confinement now resolves its glob head as
/// external `chrono` (an ancestor of the prefix) and reacts fail-closed; under the default it
/// names nothing, since no scope binds `chrono`, and does not react.
///
/// The reclassification honors **local precedence**, and local precedence is the scope lookup
/// every path goes through, from the scope the call stands in up to its TRUE inline module
/// (`{module}::inner…`, following any `mod name { … }` around it): an import, a `type` alias, a
/// name a glob brings, a child module or a top-level item definition
/// (mod/struct/enum/union/trait/type/fn/const/static) of that name — only a head none of them
/// binds is matched against the dependency names.
/// A local item shadows a same-named external call only within its OWN module: a file-top
/// `fn rand` does not mask a `rand::random()` call inside an inline `mod tests { … }`, and a
/// submodule-local `fn rand` masks only calls in that submodule.
///
/// It catches fully-qualified external calls **by the crate's real name**; an `extern crate dep as
/// alias;` binds `alias` as `use dep as alias;` does, so a call through it reacts with or without the
/// flag. It does NOT close glob-brought names beyond the glob-hazard reaction, or macro-constructed
/// names. Do not read this as "all external calls caught."
///
/// One further stated bound, strict-external only: a `mod name {` **inside a macro-invocation
/// body** opens a module scope for the calls inside that body, while no declaration inside a
/// macro's group is recorded, so a call's true module may be mis-attributed. Rare and declared,
/// never a silent pass.
///
/// One stated **over-**reaction bound is this flag's, only under a **single-segment** bare crate prefix
/// (`must_not_call_inline("rand")`) — a multi-segment prefix (`chrono::Utc`) is immune, as is every
/// prefix under the default, where a head no scope binds names nothing: 圭表's text scan cannot tell
/// a local binding from a call, so a local `let rand = …; rand()` may false-positive here. A `fn` item's
/// own name (`fn rand(…)`) is read as its definition, never a call, and module-top-level definitions
/// resolve to the local item. Separately, and in every mode, a `fn` or closure parameter or a `let`
/// binding sharing its name with an import or an item in scope is read as that import or item, so
/// `use crate::clock::now; fn s(now: fn()) { now(); }` reports under `crate::clock`. Both are declared,
/// not silent.
///
/// Orthogonal to [`ending_with`](Self::ending_with) / [`strict_prefix_only`](Self::strict_prefix_only):
/// it changes head *resolution*, not call-vs-mention breadth, and composes with either — it is
/// **not** itself part of their mutual exclusion (but the contradictory
/// `.ending_with(…).strict_prefix_only()` pair is still a constitution error under the flag).
/// When not set, the fully-qualified external call remains a stated non-observation and
/// behavior is byte-identical to a confinement without the flag.
pub fn strict_external(mut self) -> Self {
self.external = true;
self
}
/// Finish the boundary, recording the human-readable `reason` (the repair hint).
pub fn because(self, reason: &str) -> ModuleBoundary {
let rule = if self.permitted {
ModuleRule::ConfineInlineCall {
prefix: self.prefix,
ending_with: self.ending_with,
strict: self.strict,
strict_external: self.external,
}
} else {
ModuleRule::ConfineInlineSymbolPath {
prefix: self.prefix,
ending_with: self.ending_with,
strict: self.strict,
strict_external: self.external,
}
};
ModuleBoundary {
crate_package: self.crate_package,
module: self.module,
rule,
reason: reason.to_string(),
severity: self.severity,
anchor: None,
depth: self.depth,
}
}
}
boundary_common!(ModuleBoundary);
draft_common!(ModuleBoundaryDraft);
draft_common!(InlineConfinementDraft);
/// Where a module rule's violations can lie within one compiled root.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Perimeter {
/// Every violation involves the governed module itself — as the importer, the module imported, or
/// the subtree a call is made in — so a root whose graph lacks that module holds none, and is not
/// judged.
GovernedModule,
/// The governed module is only the region where an otherwise-forbidden construct is permitted, and a
/// violation can lie anywhere in the root. A root whose graph lacks that module has an empty
/// permitted region, and is judged like any other.
WholeRoot,
}