zoning 1.2.0

An import-topology gate: declare the zones a package's imports may cross, and judge the real import graph against them.
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
//! Tokens → parse tree. Recursive descent, one declaration per call.
//!
//! The grammar, in full:
//!
//! ```text
//! file     = { decl } END
//! decl     = package | zones | seal | keep | use | limit | forbid | variance
//! package  = "package" WORD "{" BREAK { setting BREAK } "}" BREAK
//! setting  = "root" WORD | "language" WORD | "facade" paths | "exclude" paths
//! zones    = "zones" "{" BREAK { WORD paths BREAK } "}" BREAK
//! paths    = WORD... | "{" BREAK { WORD... BREAK } "}"
//! seal     = "seal" WORD "through" WORD [ "open" "to" paths ] BREAK
//! keep     = "keep" WORD "to" ( paths | "nobody" ) BREAK
//! use      = "use" WORD... [ "by" paths ] BREAK
//! limit    = "limit" "reach" "to" INT "hops" BREAK
//! forbid   = "forbid" "cycles" "across" "directories" BREAK
//! variance = "variance" ( edge | cycle )
//! edge     = LAW WORD "->" WORD "because" TEXT BREAK
//! cycle    = "cycle" "{" BREAK { WORD BREAK } "}" "because" TEXT BREAK
//! LAW      = "zone" | "seal" | "keep" | "cycle" | "reach" | "use" | "escape"
//! ```
//!
//! `keep` takes a single subject rather than a `paths` list so the inline form
//! stays unambiguous against its own `to` — and because one claim per line is what
//! lets each keep carry the comment that justifies it.
//!
//! `use` is the one declaration whose subjects are not paths: a module name the
//! build system resolves, not a file this package owns. Its `by` list is scopes —
//! zone names, or path globs where a grant is narrower than a whole zone.
//!
//! Zones are listed low to high, and that vertical order *is* the stack: reading
//! down the block is reading up the architecture. `because` sits in the grammar
//! rather than in a validation pass because an unexplained exception is the thing
//! this language most wants to make unsayable.

use std::path::Path;

use super::fault::{Fault, Span};
use super::law::Law;
use super::lex::{Kind, Token, tokenize};

/// The `package { … }` header: what this file governs.
pub(super) struct Package {
    pub name: Token,
    pub root: Option<Token>,
    pub language: Option<Token>,
    pub facade: Vec<Token>,
    pub exclude: Vec<Token>,
}

/// One `name  paths…` row of the zones block.
pub(super) struct Zone {
    pub name: Token,
    pub globs: Vec<Token>,
}

/// One `seal DIR through FILE [open to …]`.
pub(super) struct Seal {
    pub path: Token,
    pub entry: Token,
    pub open: Vec<Token>,
}

/// One `keep REGION to IMPORTERS…`. An empty list is `to nobody`, written out.
pub(super) struct Keep {
    pub subject: Token,
    pub importers: Vec<Token>,
}

/// One `use MODULE… [by SCOPE…]`. An empty `by` list grants every zone.
pub(super) struct Use {
    pub modules: Vec<Token>,
    pub scope: Vec<Token>,
    /// The `use` keyword itself, for locating a fault or a stale grant.
    pub lead: Token,
}

/// One ratified exception. `because` is grammar, so `reason` is never empty.
pub(super) struct Variance {
    pub law: Token,
    /// Two words for an edge, N for a cycle.
    pub subject: Vec<Token>,
    pub reason: Token,
}

/// One parsed `.zone` file, exactly as written, before it means anything.
pub(super) struct Tree {
    pub package: Package,
    pub zones: Vec<Zone>,
    pub seals: Vec<Seal>,
    pub keeps: Vec<Keep>,
    pub uses: Vec<Use>,
    pub variances: Vec<Variance>,
    pub reach: Option<(u32, Span)>,
}

/// Spellings that changed when `ward` became `zoning`, and what they became.
/// A contract written against the old tool should say so, not fail as gibberish.
const RENAMED: [(&str, &str); 3] = [("tiers", "zones"), ("tier", "zone"), ("allow", "variance")];

struct Reader<'a> {
    source: &'a str,
    tokens: Vec<Token>,
    at: usize,
}

impl Reader<'_> {
    fn head(&self) -> &Token {
        &self.tokens[self.at]
    }

    fn bump(&mut self) -> Token {
        let token = self.tokens[self.at].clone();
        self.at = (self.at + 1).min(self.tokens.len() - 1);
        token
    }

    fn fail(&self, want: &str) -> Fault {
        let token = self.head();
        let renamed = RENAMED.iter().find(|(old, _)| *old == token.text);
        let message = match renamed {
            Some((old, new)) => format!(
                "expected {want}, found `{old}` — this is a `.zone` file, where `{old}` \
                 is spelled `{new}`"
            ),
            None => format!("expected {want}, found {token}"),
        };
        Fault::at(message, token.span.clone(), self.source)
    }

    fn at(&self, token: &Token, message: impl Into<String>) -> Fault {
        Fault::at(message, token.span.clone(), self.source)
    }

    fn take(&mut self, kind: Kind, want: &str) -> Result<Token, Fault> {
        if self.head().kind == kind { Ok(self.bump()) } else { Err(self.fail(want)) }
    }

    fn word(&mut self, want: &str) -> Result<Token, Fault> {
        self.take(Kind::Word, want)
    }

    fn keyword(&mut self, allowed: &[&str]) -> Result<Token, Fault> {
        if self.looking_at(allowed) {
            return Ok(self.bump());
        }
        let spelled = allowed.iter().map(|a| format!("`{a}`")).collect::<Vec<_>>().join(" or ");
        Err(self.fail(&spelled))
    }

    fn looking_at(&self, allowed: &[&str]) -> bool {
        self.head().kind == Kind::Word && allowed.contains(&self.head().text.as_str())
    }

    /// One or more paths: inline to end of line, or a `{ … }` block.
    ///
    /// The block form exists because a zone is often a hand-listed partition too
    /// wide for one line, and wrapping it is worth more than the brevity.
    fn paths(&mut self, want: &str) -> Result<Vec<Token>, Fault> {
        if self.head().kind != Kind::Open {
            let mut out = vec![self.word(want)?];
            while self.head().kind == Kind::Word {
                out.push(self.bump());
            }
            return Ok(out);
        }
        self.bump();
        self.endline()?;
        let mut out = Vec::new();
        while self.head().kind != Kind::Close {
            if self.head().kind == Kind::End {
                return Err(self.fail("`}` to close the list"));
            }
            out.push(self.word(want)?);
            if self.head().kind == Kind::Break {
                self.bump();
            }
        }
        let close = self.bump();
        if out.is_empty() {
            return Err(self.at(&close, format!("expected {want}, found {close}")));
        }
        Ok(out)
    }

    fn endline(&mut self) -> Result<(), Fault> {
        self.take(Kind::Break, "end of line").map(drop)
    }

    fn skip_blank(&mut self) {
        while self.head().kind == Kind::Break {
            self.bump();
        }
    }

    /// Consume `{` and the break after it, reporting the opener if absent.
    fn block(&mut self, opener: &Token) -> Result<(), Fault> {
        if self.head().kind != Kind::Open {
            return Err(self.fail(&format!("`{{` to open the `{}` block", opener.text)));
        }
        self.bump();
        self.endline()
    }

    fn parse(mut self) -> Result<Tree, Fault> {
        let mut package = None;
        let mut zones = Vec::new();
        let mut seen_zones = false;
        let (mut seals, mut keeps, mut uses) = (Vec::new(), Vec::new(), Vec::new());
        let mut variances = Vec::new();
        let mut reach = None;

        self.skip_blank();
        while self.head().kind != Kind::End {
            let lead = self.keyword(&[
                "package", "zones", "seal", "keep", "use", "limit", "forbid", "variance",
            ])?;
            match lead.text.as_str() {
                "package" => {
                    if package.is_some() {
                        return Err(self.at(
                            &lead,
                            "a second `package` block — a zone file governs exactly one \
                             package",
                        ));
                    }
                    package = Some(self.package(&lead)?);
                }
                "zones" => {
                    if seen_zones {
                        return Err(self.at(
                            &lead,
                            "a second `zones` block — merge them so the stack has one \
                             readable order",
                        ));
                    }
                    zones = self.zones(&lead)?;
                    seen_zones = true;
                }
                "seal" => seals.push(self.seal()?),
                "keep" => keeps.push(self.keep()?),
                "use" => uses.push(self.uses(lead)?),
                "limit" => reach = Some(self.limit()?),
                "forbid" => self.forbid()?,
                _ => variances.push(self.variance()?),
            }
            self.skip_blank();
        }

        let head = self.tokens[0].clone();
        let Some(package) = package else {
            return Err(self.at(&head, "no `package` block — a zone file must say what it governs"));
        };
        if zones.is_empty() {
            return Err(
                self.at(&head, "no `zones` block — a contract with no zones governs nothing")
            );
        }
        Ok(Tree { package, zones, seals, keeps, uses, variances, reach })
    }

    fn package(&mut self, lead: &Token) -> Result<Package, Fault> {
        let name = self.word("the package name")?;
        self.block(lead)?;
        let (mut root, mut language) = (None, None);
        let (mut facade, mut exclude) = (Vec::new(), Vec::new());
        while self.head().kind != Kind::Close {
            if self.head().kind == Kind::End {
                return Err(self.fail("`}` to close the `package` block"));
            }
            match self.keyword(&["root", "language", "facade", "exclude"])?.text.as_str() {
                "root" => root = Some(self.word("the source root directory")?),
                "language" => language = Some(self.word("the language name")?),
                "facade" => facade.extend(self.paths("a facade path")?),
                _ => exclude.extend(self.paths("a path to exclude")?),
            }
            self.endline()?;
            self.skip_blank();
        }
        self.bump();
        self.endline()?;
        Ok(Package { name, root, language, facade, exclude })
    }

    fn zones(&mut self, lead: &Token) -> Result<Vec<Zone>, Fault> {
        self.block(lead)?;
        let mut out = Vec::new();
        while self.head().kind != Kind::Close {
            if self.head().kind == Kind::End {
                return Err(self.fail("`}` to close the `zones` block"));
            }
            let name = self.word("a zone name")?;
            let want = format!("a path for zone `{}`", name.text);
            out.push(Zone { name, globs: self.paths(&want)? });
            self.endline()?;
            self.skip_blank();
        }
        self.bump();
        self.endline()?;
        Ok(out)
    }

    fn seal(&mut self) -> Result<Seal, Fault> {
        let path = self.word("the directory to seal")?;
        self.keyword(&["through"])?;
        let entry = self.word("the entry filename")?;
        let mut open = Vec::new();
        if self.looking_at(&["open"]) {
            self.bump();
            self.keyword(&["to"])?;
            open = self.paths("a path allowed past the seal")?;
        }
        self.endline()?;
        Ok(Seal { path, entry, open })
    }

    /// `keep REGION to IMPORTERS…`, or `to nobody` for a region with no way in.
    ///
    /// `nobody` is spelled rather than expressed as an empty list because a guest
    /// list nobody is on is a strong claim — the region is reachable only from
    /// inside itself — and it should read like one instead of looking like a line
    /// somebody forgot to finish.
    fn keep(&mut self) -> Result<Keep, Fault> {
        let subject = self.word("the region to keep")?;
        self.keyword(&["to"])?;
        if self.looking_at(&["nobody"]) {
            self.bump();
            self.endline()?;
            return Ok(Keep { subject, importers: Vec::new() });
        }
        let importers = self.paths("an importer allowed to reach it, or `nobody`")?;
        self.endline()?;
        Ok(Keep { subject, importers })
    }

    /// `use MODULE… [by SCOPE…]` — what this package may reach outside itself.
    ///
    /// Several modules may share one line because they usually share one reason
    /// (`use gist irregex by face`), and an omitted `by` grants every zone, which is
    /// the common case and should cost one word.
    fn uses(&mut self, lead: Token) -> Result<Use, Fault> {
        let mut modules = vec![self.word("an outside module name")?];
        while self.head().kind == Kind::Word && self.head().text != "by" {
            modules.push(self.bump());
        }
        let mut scope = Vec::new();
        if self.looking_at(&["by"]) {
            self.bump();
            scope = self.paths("a zone name or path glob the grant covers")?;
        }
        self.endline()?;
        Ok(Use { modules, scope, lead })
    }

    fn limit(&mut self) -> Result<(u32, Span), Fault> {
        self.keyword(&["reach"])?;
        self.keyword(&["to"])?;
        let hops = self.word("a hop count")?;
        let Ok(count) = hops.text.parse::<u32>() else {
            return Err(self.at(&hops, format!("`{}` is not a hop count", hops.text)));
        };
        self.keyword(&["hops", "hop"])?;
        self.endline()?;
        Ok((count, hops.span))
    }

    /// `forbid cycles across directories` — documentary, and the only phrasing.
    ///
    /// Cycles have no off switch: a contract cannot opt out of the law, only ratify
    /// individual cycles with `variance cycle … because`. The statement exists so a
    /// reader sees the full set of laws in force without having to know which ones
    /// are implicit.
    fn forbid(&mut self) -> Result<(), Fault> {
        self.keyword(&["cycles"])?;
        self.keyword(&["across"])?;
        self.keyword(&["directories"])?;
        self.endline()
    }

    fn variance(&mut self) -> Result<Variance, Fault> {
        let law = self.keyword(&Law::NAMES)?;
        let subject = if law.text == "cycle" {
            self.cycle_members(&law)?
        } else {
            let src = self.word("the importing file")?;
            self.take(Kind::Arrow, "`->`")?;
            vec![src, self.word("the imported file")?]
        };
        self.skip_blank(); // `because` may wrap onto its own line
        self.keyword(&["because"])?;
        self.skip_blank(); // and a `\\` folded reason onto the line after that
        let reason = self.take(
            Kind::Text,
            "a reason — every exception must say how it gets retired (\"…\" or a `\\\\` block)",
        )?;
        if reason.text.trim().is_empty() {
            return Err(self.at(&reason, "an empty reason ratifies nothing"));
        }
        self.endline()?;
        Ok(Variance { law, subject, reason })
    }

    fn cycle_members(&mut self, lead: &Token) -> Result<Vec<Token>, Fault> {
        self.block(lead)?;
        let mut out = Vec::new();
        while self.head().kind != Kind::Close {
            if self.head().kind == Kind::End {
                return Err(self.fail("`}` to close the cycle members"));
            }
            out.push(self.word("a cycle member path")?);
            self.endline()?;
            self.skip_blank();
        }
        let close = self.bump();
        if out.len() < 2 {
            return Err(
                self.at(&close, format!("a cycle needs at least two members, found {}", out.len()))
            );
        }
        Ok(out)
    }
}

/// Parse one `.zone` file, faulting with a caret on the first problem.
pub(super) fn parse(source: &str, file: &Path) -> Result<Tree, Fault> {
    let tokens = tokenize(source, file)?;
    Reader { source, tokens, at: 0 }.parse()
}