Skip to main content

fic/rast/
env.rs

1//! The resolved AST, [`Rast`], and its environment, [`Env`]: the
2//! declarations resolution builds and typing changes again ([`Channel`],
3//! [`Struct`] and its [`Field`]s, [`Const`], [`LocalVar`]), and [`build`],
4//! which builds them from a checked AST. What typing leaves as resolved is
5//! `base`'s.
6//!
7//! [`Env`] holds the system's arenas, each program's locals by its
8//! protection domain, and the foreign functions the programs call
9//! ([`ForeignFn`], each once). It owns its data: names, spans and
10//! signatures are copied, so it outlives the AST and the store of loaded
11//! files it was built from.
12//!
13//! `build` resolves every name (`system.rs` the `.fis`, `program.rs` each
14//! `.fi`), rejecting duplicates and validating the system as it goes
15//! (`validation.rs`), and lays out the vaddrs (`vaddr.rs`). A
16//! declaration's id is its position in the AST: any error fails the build,
17//! so on success every declaration was built. A program's id is its
18//! protection domain's: `build` walks the PDs and takes each one's `.fi`
19//! by name, so a PD without a program, a file naming no PD, and a second
20//! file for one PD are each an error.
21
22use std::collections::{HashMap, HashSet};
23use std::ops::Range;
24
25use serde::Serialize;
26
27use crate::ast::{ArraySize, ChannelKind, MemoryRegionDecl, ProtectionDomainDecl, RawAst, Type};
28use crate::base::{
29    ArrayLen, Buffer, ChanId, ChannelEnd, Composition, ConstId, FfnId, IdVec, Idx, LocalVarId,
30    Mapping, MappingId, MrId, PdId, StructId, TypeRef,
31};
32use crate::error::{Diagnostic, Diagnostics};
33use crate::foreign::ForeignModules;
34
35use super::data::resolve_data;
36use super::program::resolve_program;
37use super::system::resolve_system;
38use super::validation::{mapped_buffers, shared_buffers};
39use super::{mkids, vaddr};
40use super::{Bodies, Expr};
41
42/// The resolved AST: the environment and the bodies.
43#[derive(Debug, Clone, Serialize)]
44pub struct Rast {
45    /// Every declaration.
46    pub env: Env,
47    /// Every program's body.
48    pub bodies: Bodies,
49}
50
51/// The environment: every declaration of a resolved project, each name a
52/// reference to the node it denotes.
53#[derive(Debug, Clone, Serialize)]
54pub struct Env {
55    /// The `.fis` file, for diagnostics.
56    pub file: String,
57    /// Memory regions, in source order.
58    pub mrs: IdVec<MrId, MemoryRegionDecl>,
59    /// Protection domains, in source order.
60    pub pds: IdVec<PdId, ProtectionDomainDecl>,
61    /// Channels, in source order.
62    pub chans: IdVec<ChanId, Channel>,
63    /// System structs, in source order.
64    pub structs: IdVec<StructId, Struct>,
65    /// System consts, in source order.
66    pub consts: IdVec<ConstId, Const>,
67    /// The `System =` composition, if written.
68    pub composition: Option<Composition>,
69    /// Each PD's IRQ channel id, for a PD with an IRQ: what its
70    /// `notified(ch)` receives for the interrupt. Deprecated, with
71    /// `mkids.rs`: Microkit's, not the language's.
72    pub irq_ids: IdVec<PdId, Option<u32>>,
73    /// Each program's local variables, by its protection domain: its
74    /// PD's state.
75    pub locals: IdVec<PdId, LocalVars>,
76    /// Every mapping, each in its protection domain, in declaration order:
77    /// each channel buffer at its two ends, in channel order, then the
78    /// programs' own, in PD order.
79    pub mappings: IdVec<MappingId, Mapping>,
80    /// Every foreign function some program calls, each once, in the order
81    /// its first call resolves.
82    pub ffis: IdVec<FfnId, ForeignFn>,
83}
84
85/// A foreign function a program calls: its name, and its signature in
86/// fic's types as written, lowered from its file's language
87/// (`ty::foreign::signature`). The store says where it is
88/// ([`ForeignModules::function`]).
89#[derive(Debug, Clone, Serialize)]
90pub struct ForeignFn {
91    /// The symbol name.
92    pub name: String,
93    /// Parameter types, in order.
94    pub params: Vec<TypeRef>,
95    /// Result type; `None` for a procedure.
96    pub ret: Option<TypeRef>,
97    /// Trailing `...` (C only): extra arguments are untyped.
98    pub variadic: bool,
99}
100
101/// A channel between two protection domains.
102#[derive(Debug, Clone, Serialize)]
103pub struct Channel {
104    /// Its name.
105    pub name: String,
106    /// Synchrony and direction.
107    pub kind: ChannelKind,
108    /// The sending end.
109    pub sender: ChannelEnd,
110    /// The receiving end.
111    pub receiver: ChannelEnd,
112    /// The shared buffer, if the channel has one.
113    pub buffer: Option<Buffer>,
114    /// The value a `Sync Chan<T>` carries; `None` for every other channel.
115    pub payload: Option<TypeRef>,
116    /// Byte span in the `.fis`.
117    pub span: Range<usize>,
118}
119
120/// A struct.
121#[derive(Debug, Clone, Serialize)]
122pub struct Struct {
123    /// Its name.
124    pub name: String,
125    /// Packed: no padding, alignment 1.
126    pub packed: bool,
127    /// Fields, in source order.
128    pub fields: Vec<Field>,
129    /// Byte span in its file.
130    pub span: Range<usize>,
131}
132
133/// A struct field.
134#[derive(Debug, Clone, Serialize)]
135pub struct Field {
136    /// Its name.
137    pub name: String,
138    /// Its type.
139    pub ty: TypeRef,
140    /// Byte span in its file.
141    pub span: Range<usize>,
142}
143
144/// A system const.
145#[derive(Debug, Clone, Serialize)]
146pub struct Const {
147    /// Its name.
148    pub name: String,
149    /// Its declared type.
150    pub ty: TypeRef,
151    /// Its value as written, references resolved.
152    pub value: Expr,
153    /// Byte span in the `.fis`.
154    pub span: Range<usize>,
155}
156
157/// A local variable: the program's, its PD's state.
158#[derive(Debug, Clone, Serialize)]
159pub struct LocalVar {
160    /// Its name.
161    pub name: String,
162    /// Its declared type.
163    pub ty: TypeRef,
164    /// Byte span in the `.fi`.
165    pub span: Range<usize>,
166}
167
168/// A program's local variables, in source order.
169pub type LocalVars = IdVec<LocalVarId, LocalVar>;
170
171/// Build the resolved AST of a project the front end has checked on `env`,
172/// which holds its data layer ([`build_data`]), over the store of the files
173/// its imports loaded, recording in it where each called function is
174/// (`ffis`).
175///
176/// Returns the declarations, the bodies, and the warnings (a body variable
177/// shadowing a local, a mapping or a const).
178///
179/// The system ([`build_system`]), the programs ([`build_programs`]), then
180/// the vaddrs ([`lay_out`]), each stage reporting its faults before the
181/// next starts.
182///
183/// # Errors
184///
185/// - a declaration of a name already declared, of the same kind;
186/// - more protection domains than [`PdId::MAX`] allows;
187/// - a hand-built project whose programs and protection domains differ in
188///   number;
189/// - an import whose file was not read;
190/// - a Pancake export C cannot call (more than four arguments) or named
191///   like a Microkit entry point;
192/// - a name that does not resolve;
193/// - a call to a foreign function whose signature fic cannot express;
194/// - a body variable redeclared in scope;
195/// - an assignment to a carrier or a const;
196/// - an entry point with parameters.
197pub fn build(
198    rawast: &RawAst,
199    env: Env,
200    foreign: &mut ForeignModules,
201) -> Result<(Rast, Diagnostics), Diagnostics> {
202    let (env, mut warnings) = build_system(rawast, env)?;
203    let (rast, more) = build_programs(rawast, env, foreign)?;
204    warnings.0.extend(more.0);
205    let rast = lay_out(rast)?;
206    Ok((rast, warnings))
207}
208
209/// Build the environment's data layer, [`build`]'s first stage: the structs and
210/// consts resolved, each struct validated, in an environment with no system
211/// or program yet. Returns it and its warnings.
212///
213/// # Errors
214///
215/// A struct or const declared twice or that does not resolve, a struct's
216/// field repeated, a struct containing itself.
217pub fn build_data(rawast: &RawAst) -> Result<(Env, Diagnostics), Diagnostics> {
218    let mut errors = Vec::new();
219    let system = &rawast.system;
220    let file = system.filename.as_str();
221    let structs = system.structs.iter().map(|s| (s.name.as_str(), &s.span));
222    reject_duplicates("struct", structs, file, &mut errors);
223    let consts = system.consts.iter().map(|c| (c.name.as_str(), &c.span));
224    reject_duplicates("constant", consts, file, &mut errors);
225    let names = Names::new(rawast);
226    let mut env = Env {
227        file: rawast.system.filename.clone(),
228        mrs: IdVec::new(),
229        pds: IdVec::new(),
230        chans: IdVec::new(),
231        structs: IdVec::new(),
232        consts: IdVec::new(),
233        composition: None,
234        irq_ids: IdVec::new(),
235        locals: IdVec::new(),
236        mappings: IdVec::new(),
237        ffis: IdVec::new(),
238    };
239    resolve_data(&rawast.system, &names, &mut env, &mut errors);
240    let warnings = Diagnostics::warnings(&mut errors);
241    Diagnostics::finish(errors, (env, warnings))
242}
243
244/// Build the system on `env`, which holds the data layer ([`build_data`]):
245/// [`build`]'s second stage, its memory regions,
246/// protection domains and channels resolved and validated, the channels'
247/// ids allocated. Returns it and its warnings.
248///
249/// # Errors
250///
251/// A memory region, protection domain or channel declared twice, more
252/// protection domains than ids or a PD's channels than its ids, a name
253/// that does not resolve, an IRQ claimed twice, a channel rule broken, a
254/// buffer region backing two channels.
255pub fn build_system(rawast: &RawAst, mut env: Env) -> Result<(Env, Diagnostics), Diagnostics> {
256    let mut errors = Vec::new();
257    let system = &rawast.system;
258    let file = system.filename.as_str();
259    let mrs = system.memory_regions.iter();
260    reject_duplicates(
261        "memory region",
262        mrs.map(|m| (m.name.as_str(), &m.span)),
263        file,
264        &mut errors,
265    );
266    let pds = system.protection_domains.iter();
267    reject_duplicates(
268        "protection domain",
269        pds.map(|p| (p.name.as_str(), &p.span)),
270        file,
271        &mut errors,
272    );
273    let chans = system.channels.iter().map(|c| (c.name.as_str(), &c.span));
274    reject_duplicates("channel", chans, file, &mut errors);
275    let names = Names::new(rawast);
276    let ids = mkids::allocate(rawast, &names, &mut errors);
277    resolve_system(&rawast.system, &names, &ids, &mut env, &mut errors);
278    shared_buffers(&env, &mut errors);
279    let warnings = Diagnostics::warnings(&mut errors);
280    Diagnostics::finish(errors, (env, warnings))
281}
282
283/// Build the resolved AST on `env`, which holds the data layer and the system
284/// ([`build_system`]): each program resolved, then the buffers' regions
285/// checked against the programs' mappings. Its vaddrs are laid out after
286/// ([`lay_out`]).
287///
288/// # Errors
289///
290/// As [`build`], for the programs.
291pub fn build_programs(
292    rawast: &RawAst,
293    mut env: Env,
294    foreign: &mut ForeignModules,
295) -> Result<(Rast, Diagnostics), Diagnostics> {
296    let mut errors = Vec::new();
297    // A store already resolved against keeps its files and links, never
298    // an earlier build's called functions.
299    foreign.ffis = IdVec::new();
300    let names = Names::new(rawast);
301    let bodies = resolve_programs(rawast, &names, &mut env, foreign, &mut errors);
302    mapped_buffers(&env, &mut errors);
303    let warnings = Diagnostics::warnings(&mut errors);
304    Diagnostics::finish(errors, (Rast { env, bodies }, warnings))
305}
306
307/// Lay out the vaddrs of `rast`'s mappings, the system's buffers and the
308/// programs' own, once [`build_programs`] has them all: each pinned one
309/// checked, the rest allocated, none overlapping in its protection domain.
310///
311/// # Errors
312///
313/// A pinned vaddr misaligned or out of range, a protection domain out of
314/// address space, two mappings overlapping.
315pub fn lay_out(mut rast: Rast) -> Result<Rast, Diagnostics> {
316    let mut errors = Vec::new();
317    vaddr::allocate(&mut rast.env, &mut errors);
318    Diagnostics::finish(errors, rast)
319}
320
321/// Each PD's program resolved into `env`: its body, its locals and its
322/// mappings.
323fn resolve_programs(
324    rawast: &RawAst,
325    names: &Names<'_>,
326    env: &mut Env,
327    foreign: &mut ForeignModules,
328    errors: &mut Vec<Diagnostic>,
329) -> Bodies {
330    let mut bodies = Bodies::default();
331    let pds = &rawast.system.protection_domains;
332    // A project with no program at all is the `.fis` alone; with programs,
333    // the front end binds one per PD, and only a hand-built project can be
334    // out of step.
335    if !rawast.programs.is_empty() && rawast.programs.len() != pds.len() {
336        errors.push(Diagnostic::at(
337            format!(
338                "{} programs for {} protection domains",
339                rawast.programs.len(),
340                pds.len()
341            ),
342            0..0,
343            rawast.system.filename.clone(),
344        ));
345    }
346    for (index, (decl, program)) in pds.iter().zip(&rawast.programs).enumerate() {
347        let pd = PdId::new(index);
348        if names.pds.get(decl.name.as_str()) != Some(&pd) {
349            // A duplicate declaration, which `Names::new` reported: the
350            // name's first declaration has the program.
351            continue;
352        }
353        bodies.push(resolve_program(pd, program, env, names, foreign, errors));
354    }
355    bodies
356}
357
358/// The system's names, each to its id: a declaration's position in the
359/// AST, the first of a name winning.
360pub(super) struct Names<'s> {
361    pub mrs: HashMap<&'s str, MrId>,
362    pub pds: HashMap<&'s str, PdId>,
363    pub chans: HashMap<&'s str, ChanId>,
364    pub structs: HashMap<&'s str, StructId>,
365    pub consts: HashMap<&'s str, ConstId>,
366}
367
368impl<'s> Names<'s> {
369    fn new(rawast: &'s RawAst) -> Self {
370        let system = &rawast.system;
371        Self {
372            mrs: index(system.memory_regions.iter().map(|m| m.name.as_str())),
373            pds: index(system.protection_domains.iter().map(|p| p.name.as_str())),
374            chans: index(system.channels.iter().map(|c| c.name.as_str())),
375            structs: index(system.structs.iter().map(|s| s.name.as_str())),
376            consts: index(system.consts.iter().map(|c| c.name.as_str())),
377        }
378    }
379}
380
381/// Report each declaration of a name already declared, of the same kind,
382/// at its own span; the first declaration is the one every use resolves to.
383pub(super) fn reject_duplicates<'s>(
384    kind: &str,
385    decls: impl Iterator<Item = (&'s str, &'s Range<usize>)>,
386    file: &str,
387    errors: &mut Vec<Diagnostic>,
388) {
389    let mut seen = HashSet::new();
390    for (name, span) in decls {
391        if !seen.insert(name) {
392            errors.push(Diagnostic::at(
393                format!("{kind} '{name}' declared more than once"),
394                span.clone(),
395                file,
396            ));
397        }
398    }
399}
400
401/// Each name to the position of its first occurrence.
402pub(super) fn index<'s, I: Idx>(names: impl Iterator<Item = &'s str>) -> HashMap<&'s str, I> {
403    let mut map = HashMap::new();
404    for (i, name) in names.enumerate() {
405        map.entry(name).or_insert_with(|| I::new(i));
406    }
407    map
408}
409
410/// Resolve the names in a type: structs and array lengths against the
411/// system's.
412pub(super) fn type_ref(ty: &Type, names: &Names<'_>) -> Result<TypeRef, String> {
413    Ok(match ty {
414        Type::Primitive(p) => TypeRef::Prim(*p),
415        Type::Struct(name) => match names.structs.get(name.as_str()) {
416            Some(&id) => TypeRef::Struct(id),
417            None => return Err(format!("struct '{name}' is not declared")),
418        },
419        Type::Array { elem, size } => TypeRef::Array {
420            elem: Box::new(type_ref(elem, names)?),
421            len: array_len(size, names)?,
422        },
423    })
424}
425
426/// Resolve a count written as a literal or a const's name: an array's
427/// length, a ring's capacity.
428pub(super) fn array_len(size: &ArraySize, names: &Names<'_>) -> Result<ArrayLen, String> {
429    Ok(match size {
430        ArraySize::Lit(n) => ArrayLen::Lit(*n),
431        ArraySize::Named(c) => match names.consts.get(c.as_str()) {
432            Some(&id) => ArrayLen::Const(id),
433            None => return Err(format!("constant '{c}' is not declared")),
434        },
435    })
436}
437
438/// Test support: the resolved AST of inline sources, no import read.
439#[cfg(test)]
440pub(crate) fn built(
441    fis: &str,
442    programs: &[(&str, &str)],
443) -> Result<(Rast, Diagnostics), Diagnostics> {
444    built_with(fis, programs, &[])
445}
446
447/// Test support: as [`built`], with each of `modules` read as the imported
448/// file `path` from `source`: a `.pnk` by the Pancake reader, which needs
449/// no toolchain; a `.h` or `.c` through libclang.
450#[cfg(test)]
451pub(crate) fn built_with(
452    fis: &str,
453    programs: &[(&str, &str)],
454    modules: &[(&str, &str)],
455) -> Result<(Rast, Diagnostics), Diagnostics> {
456    let rawast = ast_of(fis, programs);
457    let (env, mut warnings) = build_data(&rawast)?;
458    let (rast, more) = build(&rawast, env, &mut store(&rawast, modules))?;
459    warnings.0.extend(more.0);
460    Ok((rast, warnings))
461}
462
463/// Test support: each of `modules` read as the imported file `path` from
464/// `source`, as [`built_with`] reads them, `ast`'s programs linked to
465/// them.
466#[cfg(test)]
467pub(crate) fn store(rawast: &RawAst, modules: &[(&str, &str)]) -> ForeignModules {
468    use std::path::Path;
469
470    use crate::foreign::{parse as parse_foreign, ForeignLang};
471
472    let mut foreign = ForeignModules::new();
473    for (path, source) in modules {
474        let lang = if Path::new(path).extension().is_some_and(|x| x == "pnk") {
475            ForeignLang::Pancake
476        } else {
477            ForeignLang::C
478        };
479        let module = parse_foreign(source, Path::new(path), Path::new(path).into(), lang, &[])
480            .unwrap_or_else(|e| panic!("failed to read {path} (a .h needs libclang): {e}"));
481        foreign.insert(module);
482    }
483    foreign.bind(rawast);
484    foreign
485}
486
487/// Test support: the project of inline sources, its files named
488/// `test.fis` and `<pd>.fi`, imports resolved as written. With no source
489/// at all the project is the `.fis` alone; with some, a PD given none has
490/// the least program that is a Microkit PD ([`least_program`]).
491/// Test support: the least program that is a Microkit PD, for a PD a test
492/// gives no source: both entry points bound, the handler receive-headed
493/// on `pd`'s IRQ or a channel it receives on, `Skip` when it has neither
494/// (the front end then rejects it).
495#[cfg(test)]
496fn least_program(system: &crate::ast::System, pd: &ProtectionDomainDecl) -> String {
497    let head = if let Some(irq) = pd.irq {
498        format!("irq?{irq} -> Notified()")
499    } else if let Some(ch) = system.channels.iter().find(|c| {
500        c.receiver == pd.name || (c.kind == crate::ast::ChannelKind::AsyncBi && c.sender == pd.name)
501    }) {
502        let binder = if ch.buffer.is_some() { "x" } else { "" };
503        format!("{}?{binder} -> Notified()", ch.name)
504    } else {
505        "Skip".to_owned()
506    };
507    format!(
508        "@bind(microkit.init)\nproc Init() {{ Skip; }}\n\
509         @bind(microkit.notified)\nproc Notified() {{ {head}; }}\n"
510    )
511}
512
513#[cfg(test)]
514pub(crate) fn ast_of(fis: &str, programs: &[(&str, &str)]) -> RawAst {
515    use crate::parser::{parse_program, parse_system};
516
517    let mut system = parse_system(fis).expect("fis parses");
518    system.filename = "test.fis".to_owned();
519    let given = programs;
520    for pd in &mut system.protection_domains {
521        pd.fi = format!("{}.fi", pd.name).into();
522    }
523    let programs = system
524        .protection_domains
525        .iter()
526        .filter(|_| !given.is_empty())
527        .map(|pd| {
528            let src = given
529                .iter()
530                .find(|(name, _)| *name == pd.name)
531                .map_or_else(|| least_program(&system, pd), |(_, src)| (*src).to_owned());
532            parse_program(&src).expect("fi parses")
533        })
534        .collect();
535    RawAst { system, programs }
536}
537
538#[cfg(test)]
539mod tests {
540    use std::path::Path;
541
542    use super::*;
543
544    const FIS: &str = "
545        struct Slot { tag: byte; }
546        const N: uint32 = 4;
547        MemoryRegion buf(0x1000);
548        ProtectionDomain client(100);
549        ProtectionDomain server(200);
550        Chan link = client <-> server;
551    ";
552
553    #[test]
554    fn duplicate_system_declarations_are_each_reported_at_the_later_one() {
555        let fis = "MemoryRegion buf(0x1000);
556                   MemoryRegion buf(0x2000);
557                   ProtectionDomain a(100);
558                   ProtectionDomain a(101);
559                   ProtectionDomain b(102);
560                   Chan link = a --> b;
561                   Chan link = a --> b;";
562        let err = built(fis, &[]).expect_err("three duplicates");
563        let text = err.to_string();
564        for expected in [
565            "memory region 'buf' declared more than once",
566            "protection domain 'a' declared more than once",
567            "channel 'link' declared more than once",
568        ] {
569            assert!(text.contains(expected), "missing `{expected}` in:\n{text}");
570        }
571        assert_eq!(text.matches("declared more than once").count(), 3, "{text}");
572        // Each points at the second declaration, in the .fis.
573        let seconds = [
574            fis.rfind("MemoryRegion buf").unwrap(),
575            fis.rfind("ProtectionDomain a").unwrap(),
576            fis.rfind("Chan link").unwrap(),
577        ];
578        for d in err
579            .0
580            .iter()
581            .filter(|d| d.message().contains("more than once"))
582        {
583            assert_eq!(d.filename(), Some("test.fis"));
584            let start = d.span().start;
585            assert!(
586                seconds.iter().any(|&s| start <= s && s < start + 40),
587                "span start {start} does not sit on a second declaration"
588            );
589        }
590    }
591
592    #[test]
593    fn the_sixty_fourth_protection_domain_is_one_too_many() {
594        let max = PdId::MAX.index() + 1;
595        let pds = |n: usize| {
596            (0..n).fold(String::new(), |fis, i| {
597                fis + &format!("ProtectionDomain pd{i}({});", 100 + i)
598            })
599        };
600        built(&pds(max), &[]).expect("63 protection domains fit");
601        let err = built(&pds(max + 1), &[]).expect_err("the 64th does not");
602        let text = err.to_string();
603        assert!(
604            text.contains(
605                "protection domain 'pd63' is one too many: at most 63 protection domains"
606            ),
607            "{text}"
608        );
609        assert_eq!(err.0.len(), 1, "{text}");
610    }
611
612    #[test]
613    fn a_constant_without_an_upper_case_name_is_warned_about() {
614        let (Rast { .. }, warnings) = built(
615            "const rounds: int = 5;\nconst Limit: int = 1;\nconst SLOT_2: int = 2;\n\
616             ProtectionDomain a(1);",
617            &[],
618        )
619        .expect("a warning, not an error");
620        let messages: Vec<&str> = warnings.0.iter().map(Diagnostic::message).collect();
621        assert_eq!(
622            messages,
623            [
624                "constant 'rounds' should have an upper-case name: 'ROUNDS'",
625                "constant 'Limit' should have an upper-case name: 'LIMIT'",
626            ]
627        );
628        assert_eq!(warnings.0[0].filename(), Some("test.fis"));
629    }
630
631    #[test]
632    fn duplicate_program_declarations_are_reported_in_that_file() {
633        let fi = r#"import "c/a.h" as io;
634                    import "c/b.h" as io;
635                    Mapping m(buf, "rw");
636                    Mapping m(buf, "r");
637                    counter: uint32;
638                    counter: uint32;
639                    evt tick: counter = 1;
640                    evt tick: counter = 2;
641                    proc Init() { Skip; }
642                    proc Init() { Skip; }"#;
643        let err = built(FIS, &[("client", fi)]).expect_err("duplicates");
644        let duplicates: Vec<_> = err
645            .0
646            .iter()
647            .filter(|d| d.message().contains("declared more than once"))
648            .collect();
649        let text: Vec<&str> = duplicates.iter().map(|d| d.message()).collect();
650        for expected in [
651            "import alias 'io' declared more than once",
652            "mapping 'm' declared more than once",
653            "variable 'counter' declared more than once",
654            "event 'tick' declared more than once",
655            "process 'Init' declared more than once",
656        ] {
657            assert!(text.contains(&expected), "missing `{expected}` in {text:?}");
658        }
659        assert_eq!(duplicates.len(), 5, "{text:?}");
660        assert!(duplicates.iter().all(|d| d.filename() == Some("client.fi")));
661    }
662
663    #[test]
664    fn duplicate_system_structs_and_consts_are_reported() {
665        let fis = "struct S { a: byte; }
666                   struct S { b: byte; }
667                   const N: uint32 = 1;
668                   const N: uint32 = 2;";
669        let text = built(fis, &[]).expect_err("duplicates").to_string();
670        assert!(
671            text.contains("struct 'S' declared more than once"),
672            "{text}"
673        );
674        assert!(
675            text.contains("constant 'N' declared more than once"),
676            "{text}"
677        );
678    }
679
680    #[test]
681    fn programs_are_indexed_by_their_pd() {
682        // `b`'s file given first: each program lands at its PD's id.
683        let (Rast { env, bodies }, _) = built(
684            "ProtectionDomain a(1);\nProtectionDomain b(2);",
685            &[("b", "x: int;"), ("a", "")],
686        )
687        .expect("builds");
688        assert_eq!((env.locals.len(), bodies.len()), (2, 2));
689        assert!(env.locals[PdId::new(0)].is_empty());
690        assert_eq!(env.locals[PdId::new(1)].len(), 1);
691        assert_eq!(env.pds[PdId::new(1)].fi, Path::new("b.fi"));
692    }
693
694    #[test]
695    fn a_project_out_of_step_with_its_pds_is_rejected() {
696        // The front end binds one program per PD; a hand-built project
697        // with fewer is an error.
698        let mut rawast = ast_of(
699            "ProtectionDomain a(1);\nProtectionDomain b(2);",
700            &[("a", ""), ("b", "")],
701        );
702        rawast.programs.pop();
703        let (env, _) = build_data(&rawast).expect("builds the data layer");
704        let err = build(&rawast, env, &mut ForeignModules::new()).expect_err("one program short");
705        assert!(
706            err.to_string()
707                .contains("1 programs for 2 protection domains"),
708            "{err}"
709        );
710    }
711
712    #[test]
713    fn the_same_name_across_kinds_is_legal() {
714        let fis = "MemoryRegion a(0x1000);
715                   ProtectionDomain a(100);
716                   ProtectionDomain b(101);
717                   Chan a = a --> b;";
718        assert!(built(fis, &[]).is_ok());
719    }
720}