wsb 0.258.6441

Workspace tools for every project under $PRJ: git across submodules, template stamping, GitHub, and the workbench
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
//! What a `.wstemplate` file references, parsed from its Tera source.
//!
//! Reference extraction has to be delimiter-aware. A `.wstemplate` renders a
//! real file, and that file's own syntax collides with ours: a `pyproject.toml`
//! carries `[project.optional-dependencies]`, a JSON fixture may quote the
//! literal text `projects.foo.version`, and neither is a template reference.
//! Scanning raw text would reject valid templates and, worse, would resolve
//! projects nobody asked about.
//!
//! Only code inside `{{ … }}` and `{% … %}` is a reference. `{# … #}` comments,
//! `{% raw %}` bodies, and quoted strings inside a block are literal content.
//!
//! This is the single place references are recognised. Template selection
//! ("does this file mention my alias?") and context building ("which fields does
//! it need?") are two questions about one parse, so they cannot drift apart.

use crate::prelude::*;
use regex::Regex;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::OnceLock;

/// A reference to the context object `project` or `projects`, and the dotted
/// path applied to it.
///
/// Matched as one unit so the arity of the path decides the meaning: `projects`
/// alone is an iteration, `projects.lib` names a project, `projects.lib.version`
/// names a field of one.
fn reference_pattern() -> &'static Regex {
    static PATTERN: OnceLock<Regex> = OnceLock::new();
    PATTERN.get_or_init(|| {
        Regex::new(r"\b(projects?)((?:\.[A-Za-z_][A-Za-z0-9_]*)*)")
            .expect("static regex must compile")
    })
}

/// A reference to the context object `env`, and the variable named after it.
///
/// Collected for one reason: Tera raises an error for a key that is missing
/// from a map, so `{% if env.MFR_LOCAL_LIBS %}` would FAIL when the variable is
/// unset — which is the ordinary case and the one that has to render. Knowing
/// which names a template asks about lets the renderer put them in the context
/// as empty, so an unset variable reads false and a set one reads its value,
/// the way `[ -n "$X" ]` does in a shell.
fn env_pattern() -> &'static Regex {
    static PATTERN: OnceLock<Regex> = OnceLock::new();
    PATTERN.get_or_init(|| {
        Regex::new(r"\benv\.([A-Za-z_][A-Za-z0-9_]*)").expect("static regex must compile")
    })
}

/// A reference to the context object `declared`, and the dotted path into the
/// workspace's own declaration.
///
/// Some of what a template needs is not a fact about a project and not an
/// environment variable: it is something the workspace states about itself.
/// The version of a library a GUEST can install is the case that forced this —
/// it is not this tree's version, which is unpublished by construction, and it
/// is not a fact any git remote can be asked for. It is a decision, written
/// down in `workspace.json`, and a template that could not read it left the
/// declaration inert while the rendered file went on stamping the wrong number.
fn declared_pattern() -> &'static Regex {
    static PATTERN: OnceLock<Regex> = OnceLock::new();
    PATTERN.get_or_init(|| {
        Regex::new(r"\bdeclared((?:\.[A-Za-z_][A-Za-z0-9_]*)+)")
            .expect("static regex must compile")
    })
}

/// A reference to the context object `build`: where the workspace's build root
/// is, from the file being rendered.
///
/// A local render names things the workspace BUILDS — a distribution built from
/// a sibling project, say — and those live under the build root, whose layout
/// is the platform's (a Windows build root is spelled differently). So the
/// renderer computes the path, as it does `path_from_here`, rather than a
/// template spelling one layout.
fn build_pattern() -> &'static Regex {
    static PATTERN: OnceLock<Regex> = OnceLock::new();
    PATTERN.get_or_init(|| {
        Regex::new(r"\bbuild((?:\.[A-Za-z_][A-Za-z0-9_]*)*)").expect("static regex must compile")
    })
}

/// The fields of `build` a template may read.
pub const BUILD_FIELDS: &[&str] = &["root_from_here"];

fn endraw_pattern() -> &'static Regex {
    static PATTERN: OnceLock<Regex> = OnceLock::new();
    PATTERN
        .get_or_init(|| Regex::new(r"\{%-?\s*endraw\s*-?%\}").expect("static regex must compile"))
}

/// Every `project` / `projects` reference one template makes, with the line each
/// was first seen on so errors can point at it.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct TemplateReferences {
    own_fields: BTreeMap<String, usize>,
    aliases: BTreeMap<String, usize>,
    peer_fields: BTreeMap<String, BTreeMap<String, usize>>,
    iterates_projects: bool,
    env_names: BTreeSet<String>,
    declared_paths: BTreeMap<String, usize>,
    build_fields: BTreeMap<String, usize>,
}

impl TemplateReferences {
    /// Parse `text` as a Tera template and collect its references.
    ///
    /// Fails on a template that cannot be scanned unambiguously — an unclosed
    /// delimiter, a path too deep to mean anything, or a dynamically indexed
    /// alias. Guessing at any of those would resolve the wrong projects or
    /// silently resolve none.
    pub fn parse(text: &str) -> Result<Self> {
        let mut references = Self::default();
        for block in blocks(text)? {
            // Quoted text inside a block is data, not code: `{{ "project.x" }}`
            // renders that string and references nothing.
            let code = mask_strings(block.body);
            references.collect(text, block.offset, &code)?;
        }
        Ok(references)
    }

    /// Whether the template names `alias` — the template-selection question.
    pub fn references_alias(&self, alias: &str) -> bool {
        self.aliases.contains_key(alias)
    }

    /// Every alias named with `projects.ALIAS`, in deterministic order.
    pub fn aliases(&self) -> impl Iterator<Item = &str> {
        self.aliases.keys().map(String::as_str)
    }

    /// Fields referenced as `project.FIELD`, mapped to the line each is on.
    pub fn own_fields(&self) -> &BTreeMap<String, usize> {
        &self.own_fields
    }

    /// Fields referenced as `projects.ALIAS.FIELD`, mapped to the line each is on.
    pub fn peer_fields(&self, alias: &str) -> Option<&BTreeMap<String, usize>> {
        self.peer_fields.get(alias)
    }

    /// Whether the template iterates `projects` as a whole, which means every
    /// project in the workspace has to be in the context rather than just the
    /// ones named literally.
    pub fn iterates_projects(&self) -> bool {
        self.iterates_projects
    }

    /// Every environment variable the template names as `env.NAME`.
    ///
    /// The renderer puts each of these in the context whether or not it is set,
    /// so an unset one is empty rather than an error.
    pub fn env_names(&self) -> &BTreeSet<String> {
        &self.env_names
    }

    /// Every `declared.A.B.C` path the template reads, mapped to its line.
    ///
    /// Checked against the workspace declaration before rendering, so a path
    /// that is not there names itself rather than arriving as Tera's "variable
    /// not found".
    pub fn declared_paths(&self) -> &BTreeMap<String, usize> {
        &self.declared_paths
    }

    /// Every `build.FIELD` the template reads, mapped to its line.
    pub fn build_fields(&self) -> &BTreeMap<String, usize> {
        &self.build_fields
    }

    /// Extract references from one block's code, with `offset` locating that
    /// code inside the whole template.
    fn collect(&mut self, text: &str, offset: usize, code: &str) -> Result<()> {
        for capture in env_pattern().captures_iter(code) {
            let whole = capture.get(0).expect("group 0 always participates");
            // `foo.env.BAR` is a member of `foo`, not this.
            if code[..whole.start()].ends_with('.') {
                continue;
            }
            self.env_names.insert(capture[1].to_string());
        }

        for capture in build_pattern().captures_iter(code) {
            let whole = capture.get(0).expect("group 0 always participates");
            // `foo.build.bar` is a member of `foo`, not this.
            if code[..whole.start()].ends_with('.') {
                continue;
            }
            let line = line_at(text, offset + whole.start());
            let field = capture[1].trim_start_matches('.');
            if !BUILD_FIELDS.contains(&field) {
                bail!(
                    "line {line}: '{}' is not a build field (build has: {})",
                    whole.as_str(),
                    BUILD_FIELDS.join(", ")
                );
            }
            self.build_fields.entry(field.to_string()).or_insert(line);
        }

        for capture in declared_pattern().captures_iter(code) {
            let whole = capture.get(0).expect("group 0 always participates");
            // `foo.declared.bar` is a member of `foo`, not this.
            if code[..whole.start()].ends_with('.') {
                continue;
            }
            if code[whole.end()..].starts_with('[') {
                bail!(
                    "line {}: 'declared{}' is indexed dynamically. A declaration \
                     path must be written literally so it can be checked against \
                     the workspace before rendering starts",
                    line_at(text, offset + whole.start()),
                    &capture[1]
                );
            }
            let path = capture[1].trim_start_matches('.').to_string();
            self.declared_paths
                .entry(path)
                .or_insert_with(|| line_at(text, offset + whole.start()));
        }

        for capture in reference_pattern().captures_iter(code) {
            let whole = capture.get(0).expect("group 0 always participates");

            // `\b` rules out a preceding word character but not a preceding dot:
            // in `foo.project.bar`, `project` is a member of `foo`, not ours.
            if code[..whole.start()].ends_with('.') {
                continue;
            }

            let line = line_at(text, offset + whole.start());
            let root = &capture[1];
            let segments: Vec<&str> = capture[2]
                .split('.')
                .filter(|segment| !segment.is_empty())
                .collect();

            if code[whole.end()..].starts_with('[') {
                bail!(
                    "line {line}: '{}' is indexed dynamically. Aliases must be \
                     written literally, as '{root}.my_alias', so the project can \
                     be resolved before rendering starts",
                    whole.as_str()
                );
            }

            if root == "project" {
                match segments.len() {
                    // The whole object; every field is in the context already.
                    0 => {}
                    1 => {
                        self.own_fields
                            .entry(segments[0].to_string())
                            .or_insert(line);
                    }
                    _ => bail!(
                        "line {line}: '{}' is too deep. Project fields are single \
                         values, so 'project.{}' has no members",
                        whole.as_str(),
                        segments[0]
                    ),
                }
                continue;
            }

            match segments.len() {
                0 => self.iterates_projects = true,
                1 => {
                    self.aliases.entry(segments[0].to_string()).or_insert(line);
                }
                2 => {
                    self.aliases.entry(segments[0].to_string()).or_insert(line);
                    self.peer_fields
                        .entry(segments[0].to_string())
                        .or_default()
                        .entry(segments[1].to_string())
                        .or_insert(line);
                }
                _ => bail!(
                    "line {line}: '{}' is too deep. Project fields are single \
                     values, so 'projects.{}.{}' has no members",
                    whole.as_str(),
                    segments[0],
                    segments[1]
                ),
            }
        }
        Ok(())
    }
}

/// One `{{ … }}` or `{% … %}` block: its code, and where that code starts.
struct Block<'a> {
    body: &'a str,
    offset: usize,
}

/// Split a template into the blocks that carry code.
///
/// Comments are skipped and `{% raw %}` bodies are passed over whole, matching
/// how Tera itself treats them.
fn blocks(text: &str) -> Result<Vec<Block<'_>>> {
    let bytes = text.as_bytes();
    let mut blocks = Vec::new();
    let mut index = 0usize;

    while index + 1 < bytes.len() {
        if bytes[index] != b'{' {
            index += 1;
            continue;
        }
        match bytes[index + 1] {
            // A comment runs to `#}` and can contain anything, quotes included.
            b'#' => index = find_close(text, index, index + 2, b'#', false)? + 2,
            b'{' => {
                let close = find_close(text, index, index + 2, b'}', true)?;
                blocks.push(Block {
                    body: &text[index + 2..close],
                    offset: index + 2,
                });
                index = close + 2;
            }
            b'%' => {
                let close = find_close(text, index, index + 2, b'%', true)?;
                let body = &text[index + 2..close];
                if is_raw_opener(body) {
                    index = skip_raw(text, index, close + 2)?;
                } else {
                    blocks.push(Block {
                        body,
                        offset: index + 2,
                    });
                    index = close + 2;
                }
            }
            _ => index += 1,
        }
    }

    Ok(blocks)
}

/// Whether a statement body opens a raw block, allowing for whitespace control.
fn is_raw_opener(body: &str) -> bool {
    body.trim()
        .trim_start_matches('-')
        .trim_end_matches('-')
        .trim()
        == "raw"
}

/// Skip past the `{% endraw %}` that closes a raw block opened at `opener`.
fn skip_raw(text: &str, opener: usize, from: usize) -> Result<usize> {
    match endraw_pattern().find_at(text, from) {
        Some(found) => Ok(found.end()),
        None => bail!(
            "line {}: a '{{% raw %}}' block is never closed with '{{% endraw %}}'",
            line_at(text, opener)
        ),
    }
}

/// Find the delimiter closing a block, returning the index of its first byte.
///
/// `first` is the byte before the closing brace (`}`, `%` or `#`). Blocks that
/// carry code skip quoted strings, so a `}}` inside a string literal does not
/// end the block early.
fn find_close(
    text: &str,
    opener: usize,
    from: usize,
    first: u8,
    skip_strings: bool,
) -> Result<usize> {
    let bytes = text.as_bytes();
    let mut index = from;
    let mut quote: Option<u8> = None;

    while index < bytes.len() {
        let byte = bytes[index];

        if let Some(active) = quote {
            if byte == b'\\' {
                index += 2;
                continue;
            }
            if byte == active {
                quote = None;
            }
            index += 1;
            continue;
        }

        if skip_strings && (byte == b'"' || byte == b'\'') {
            quote = Some(byte);
            index += 1;
            continue;
        }

        if byte == first && index + 1 < bytes.len() && bytes[index + 1] == b'}' {
            return Ok(index);
        }
        index += 1;
    }

    bail!(
        "line {}: '{}' is never closed",
        line_at(text, opener),
        &text[opener..opener + 2]
    )
}

/// Blank out quoted string literals, preserving every byte position so offsets
/// still locate the original text.
fn mask_strings(body: &str) -> String {
    let mut masked = body.as_bytes().to_vec();
    let mut index = 0usize;
    let mut quote: Option<u8> = None;

    while index < masked.len() {
        let byte = masked[index];
        match quote {
            Some(active) => {
                masked[index] = b' ';
                if byte == b'\\' {
                    // Blank the escaped byte too, so a `\"` cannot close the string.
                    if index + 1 < masked.len() {
                        masked[index + 1] = b' ';
                    }
                    index += 2;
                    continue;
                }
                if byte == active {
                    quote = None;
                }
                index += 1;
            }
            None => {
                if byte == b'"' || byte == b'\'' {
                    quote = Some(byte);
                    masked[index] = b' ';
                }
                index += 1;
            }
        }
    }

    // Every replaced byte became an ASCII space, and multi-byte characters are
    // replaced whole, so the result is still valid UTF-8 of the same length.
    String::from_utf8(masked).expect("masking only substitutes ASCII spaces")
}

/// The 1-based line `offset` falls on.
fn line_at(text: &str, offset: usize) -> usize {
    text.as_bytes()[..offset.min(text.len())]
        .iter()
        .filter(|byte| **byte == b'\n')
        .count()
        + 1
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(text: &str) -> TemplateReferences {
        TemplateReferences::parse(text).unwrap()
    }

    /// TEST11348: a template can read what the workspace declares about itself.
    ///
    /// The reference kind that exists because some values are neither a fact
    /// about a project nor an environment variable. The version of a library a
    /// guest can install is one: not this tree's version, which is unpublished
    /// by construction, and not something a git remote can be asked for.
    #[test]
    fn a_declaration_path_is_collected() {
        let refs = parse("capdag=={{ declared.mg_test.bootstrap.published_capdag }}\n");
        assert_eq!(
            refs.declared_paths().keys().cloned().collect::<Vec<_>>(),
            vec!["mg_test.bootstrap.published_capdag".to_string()]
        );
        // And it is not mistaken for a project reference.
        assert!(refs.own_fields().is_empty());
        assert_eq!(refs.aliases().count(), 0);
    }

    /// TEST11349: a declaration path is collected with the line it is on.
    ///
    /// The line is the whole point of collecting these ahead of rendering: a
    /// path that is not in the workspace has to name where it was asked for.
    #[test]
    fn a_declaration_path_remembers_its_line() {
        let refs = parse("one\ntwo\n{{ declared.mg_test.targets }}\n");
        assert_eq!(refs.declared_paths()["mg_test.targets"], 3);
    }

    /// TEST11350: `declared` reached through something else is that thing's.
    ///
    /// `\b` rules out a preceding word character but not a preceding dot, so
    /// without the explicit check a loop variable with a member of this name
    /// would be read as a workspace declaration and then fail a lookup against
    /// a file it has nothing to do with.
    #[test]
    fn a_member_named_declared_is_not_this() {
        let refs = parse("{% for item in things %}{{ item.declared.thing }}{% endfor %}\n");
        assert!(refs.declared_paths().is_empty(), "{:?}", refs.declared_paths());
    }

    /// TEST11351: a bare `declared` names nothing and is not collected.
    ///
    /// Handing the whole declaration to a template would make every key in
    /// `workspace.json` reachable without anything checking it existed, which
    /// is exactly what the pre-render check is for.
    #[test]
    fn a_bare_declared_is_not_a_path() {
        let refs = parse("{{ declared }}\n");
        assert!(refs.declared_paths().is_empty());
    }

    /// TEST11352: a dynamically indexed declaration is refused, not guessed.
    #[test]
    fn a_dynamically_indexed_declaration_is_refused() {
        let error = TemplateReferences::parse("{{ declared.mg_test[name] }}\n")
            .expect_err("a dynamic index must be refused");
        let said = error.to_string();
        assert!(said.contains("indexed dynamically"), "{said}");
        assert!(said.contains("line 1"), "{said}");
    }

    /// TEST11353: a path inside a quoted string is data, not a reference.
    #[test]
    fn a_quoted_declaration_path_is_text() {
        let refs = parse("{{ \"declared.mg_test.bootstrap\" }}\n");
        assert!(refs.declared_paths().is_empty(), "{:?}", refs.declared_paths());
    }

    #[test]
    fn text_outside_delimiters_is_not_a_reference() {
        // The case that motivated delimiter-aware parsing: a pyproject.toml
        // section header is not a reference to the owning project.
        let refs =
            parse("[project]\nname = \"demo\"\n\n[project.optional-dependencies]\ndev = []\n");
        assert!(
            refs.own_fields().is_empty(),
            "TOML section headers must not be read as template references: {:?}",
            refs.own_fields()
        );
        assert_eq!(refs.aliases().count(), 0);
    }

    #[test]
    fn a_literal_alias_in_prose_is_not_a_reference() {
        let refs = parse("# Set projects.mylib.version in your template\nvalue = 1\n");
        assert!(!refs.references_alias("mylib"));
    }

    #[test]
    fn references_inside_expressions_are_collected() {
        let refs = parse("version = \"{{ projects.mylib.latest_version }}\"\n");
        assert!(refs.references_alias("mylib"));
        assert_eq!(
            refs.peer_fields("mylib")
                .unwrap()
                .keys()
                .collect::<Vec<_>>(),
            vec!["latest_version"]
        );
    }

    #[test]
    fn references_inside_statements_are_collected() {
        let refs = parse("{% if projects.mylib.is_dirty %}dirty{% endif %}");
        assert!(refs.references_alias("mylib"));
        assert!(refs.peer_fields("mylib").unwrap().contains_key("is_dirty"));
    }

    #[test]
    fn quoted_text_inside_a_block_is_data_not_code() {
        let refs = parse("{{ \"projects.ghost.version\" }}");
        assert!(
            !refs.references_alias("ghost"),
            "a string literal must not resolve a project"
        );
    }

    #[test]
    fn an_escaped_quote_does_not_end_the_literal_early() {
        let refs = parse(r#"{{ "a\"projects.ghost.version" }}"#);
        assert!(!refs.references_alias("ghost"));
    }

    #[test]
    fn comments_are_not_code() {
        let refs = parse("{# projects.ghost.version #}value");
        assert!(!refs.references_alias("ghost"));
    }

    #[test]
    fn raw_blocks_are_literal_content() {
        // Documentation templates show template syntax; that syntax is output,
        // not a reference.
        let refs =
            parse("{% raw %}{{ projects.ghost.version }}{% endraw %}{{ projects.real.version }}");
        assert!(!refs.references_alias("ghost"), "raw content is literal");
        assert!(
            refs.references_alias("real"),
            "code after endraw still counts"
        );
    }

    #[test]
    fn whitespace_control_does_not_hide_a_raw_block() {
        let refs = parse("{%- raw -%}{{ projects.ghost.version }}{%- endraw -%}");
        assert!(!refs.references_alias("ghost"));
    }

    #[test]
    fn a_dotted_owner_is_not_our_context_object() {
        let refs = parse("{{ meta.project.version }} {{ other.projects.lib.version }}");
        assert!(
            refs.own_fields().is_empty(),
            "'meta.project' is a member of meta, got: {:?}",
            refs.own_fields()
        );
        assert!(!refs.references_alias("lib"));
    }

    #[test]
    fn a_word_ending_in_project_is_not_a_reference() {
        let refs = parse("{{ subproject.version }} {{ myprojects.lib.version }}");
        assert!(refs.own_fields().is_empty());
        assert!(!refs.references_alias("lib"));
    }

    #[test]
    fn own_and_peer_references_are_kept_apart() {
        let refs = parse("{{ project.version }} {{ projects.lib.version }}");
        assert!(refs.own_fields().contains_key("version"));
        assert!(refs.peer_fields("lib").unwrap().contains_key("version"));
        assert!(
            !refs.own_fields().contains_key("lib"),
            "'projects.lib' must not be read as 'project.lib'"
        );
    }

    #[test]
    fn an_alias_named_without_a_field_still_resolves_the_project() {
        let refs = parse("{{ projects.lib | json_encode }}");
        assert!(refs.references_alias("lib"));
        assert!(refs.peer_fields("lib").is_none());
    }

    #[test]
    fn iterating_projects_is_recognised_as_needing_all_of_them() {
        let refs = parse("{% for alias, entry in projects %}{{ alias }}{% endfor %}");
        assert!(refs.iterates_projects());
        assert_eq!(refs.aliases().count(), 0);
    }

    #[test]
    fn naming_a_project_does_not_imply_iterating_all_of_them() {
        let refs = parse("{{ projects.lib.version }}");
        assert!(!refs.iterates_projects());
    }

    #[test]
    fn lines_are_reported_for_error_messages() {
        let refs = parse("line one\nline two\n{{ projects.lib.version }}\n");
        assert_eq!(refs.peer_fields("lib").unwrap()["version"], 3);
    }

    #[test]
    fn a_reference_spanning_lines_reports_where_it_starts() {
        let refs = parse("{{\n  projects.lib.version\n}}");
        assert_eq!(refs.peer_fields("lib").unwrap()["version"], 2);
    }

    #[test]
    fn a_closing_brace_inside_a_string_does_not_end_the_block() {
        let refs = parse(r#"{{ projects.lib.version | default(value="}}") }}"#);
        assert!(refs.peer_fields("lib").unwrap().contains_key("version"));
    }

    #[test]
    fn multibyte_content_does_not_shift_line_numbers() {
        let refs = parse("café ☕\n{{ projects.lib.version }}");
        assert_eq!(refs.peer_fields("lib").unwrap()["version"], 2);
    }

    #[test]
    fn multibyte_text_inside_a_string_is_masked_without_corrupting_the_block() {
        let refs = parse("{{ projects.lib.version }}{{ \"caf\u{e9} projects.ghost.version\" }}");
        assert!(refs.references_alias("lib"));
        assert!(!refs.references_alias("ghost"));
    }

    // ── states that must fail rather than be guessed at ───────────────────────

    #[test]
    fn an_unclosed_expression_is_an_error() {
        let error = TemplateReferences::parse("{{ projects.lib.version").unwrap_err();
        let message = error.to_string();
        assert!(message.contains("never closed"), "got: {message}");
        assert!(message.contains("line 1"), "got: {message}");
    }

    #[test]
    fn an_unclosed_raw_block_is_an_error() {
        let error = TemplateReferences::parse("{% raw %}{{ x }}").unwrap_err();
        assert!(error.to_string().contains("endraw"), "got: {error}");
    }

    #[test]
    fn a_dynamically_indexed_alias_is_an_error() {
        // The alias would only be known during rendering, by which time the
        // project it names can no longer be resolved.
        let error = TemplateReferences::parse("{{ projects[name].version }}").unwrap_err();
        let message = error.to_string();
        assert!(message.contains("indexed dynamically"), "got: {message}");
    }

    #[test]
    fn a_path_deeper_than_a_field_is_an_error() {
        let error = TemplateReferences::parse("{{ projects.lib.version.major }}").unwrap_err();
        assert!(error.to_string().contains("too deep"), "got: {error}");

        let error = TemplateReferences::parse("{{ project.version.major }}").unwrap_err();
        assert!(error.to_string().contains("too deep"), "got: {error}");
    }

    #[test]
    fn an_unclosed_comment_is_an_error() {
        let error = TemplateReferences::parse("{# never closed").unwrap_err();
        assert!(error.to_string().contains("never closed"), "got: {error}");
    }

    #[test]
    fn a_lone_brace_is_ordinary_content() {
        let refs = parse("{ not a block } {{ projects.lib.version }}");
        assert!(refs.references_alias("lib"));
    }
}