Skip to main content

fic/rast/
scope.rs

1//! What a name in a body denotes: the body's frames, innermost first,
2//! then the program's locals, then the system's consts (`BodyScope`);
3//! and the program's and system's declarations a body can name
4//! (`Outer`). The scope rules themselves are `body.rs`'s walk.
5
6use std::cell::RefCell;
7use std::collections::{BTreeSet, HashMap};
8
9use crate::ast::Type;
10use crate::base::{
11    BodyVarId, EventId, FfnId, IdVec, LocalVarId, MappingId, ModuleId, ProcId, TypeRef, VarRef,
12};
13use crate::foreign::{ForeignFnRef, ForeignModules};
14use crate::ty::foreign::signature;
15
16use super::env::{type_ref, Names};
17use super::expr::Scope;
18use super::ForeignFn;
19
20/// The foreign functions called so far, each once, by `FfnId`: its
21/// signature, for `Env.ffis`, and where it is, for the store's `ffis`.
22pub(super) struct Called {
23    pub sigs: IdVec<FfnId, ForeignFn>,
24    pub at: IdVec<FfnId, ForeignFnRef>,
25}
26
27/// What a body's names can denote beyond its own frames: the program's
28/// declarations and the system's.
29pub(super) struct Outer<'a, 's> {
30    pub names: &'a Names<'s>,
31    pub file: &'a str,
32    pub locals: HashMap<&'s str, LocalVarId>,
33    pub mappings: HashMap<&'s str, MappingId>,
34    pub events: HashMap<&'s str, EventId>,
35    pub processes: HashMap<&'s str, ProcId>,
36    /// Each process's parameter count, and each event's carrier count.
37    pub arity: (IdVec<ProcId, usize>, IdVec<EventId, usize>),
38    /// Each import alias, to the file it names.
39    pub aliases: HashMap<&'s str, ModuleId>,
40    pub foreign: &'a ForeignModules,
41    /// The foreign functions called so far, each once.
42    pub called: &'a RefCell<Called>,
43    /// Each process variable's name, to the process declaring it: the hint
44    /// when an event names one.
45    pub process_vars: HashMap<String, String>,
46    /// The mappings whose `.paddr` a body of the program reads.
47    pub paddr_reads: RefCell<BTreeSet<MappingId>>,
48}
49
50/// A body's names at one point of the walk: the frames in scope, inside
51/// the program and the system.
52pub(super) struct BodyScope<'w, 'a, 's> {
53    pub outer: &'w Outer<'a, 's>,
54    /// `process 'P': ` or `event 'e': `.
55    pub context: String,
56    pub event: bool,
57    /// Each variable in scope, innermost last.
58    pub frames: Vec<(String, BodyVarId)>,
59}
60
61impl Scope for BodyScope<'_, '_, '_> {
62    fn var(&self, name: &str) -> Option<VarRef> {
63        if let Some((_, id)) = self.frames.iter().rev().find(|(n, _)| n == name) {
64            return Some(VarRef::Body(*id));
65        }
66        if let Some(&g) = self.outer.locals.get(name) {
67            return Some(VarRef::Local(g));
68        }
69        self.outer.names.consts.get(name).map(|&c| VarRef::Const(c))
70    }
71
72    fn mapping(&self, name: &str) -> Option<MappingId> {
73        self.outer.mappings.get(name).copied()
74    }
75
76    fn paddr_read(&self, m: MappingId) {
77        self.outer.paddr_reads.borrow_mut().insert(m);
78    }
79
80    fn callee(&self, alias: &str, name: &str) -> Result<FfnId, String> {
81        let Some(&module) = self.outer.aliases.get(alias) else {
82            return Err(format!("import alias '{alias}' is not declared"));
83        };
84        let file = &self.outer.foreign.modules[module];
85        let Some(index) = file.exports.iter().position(|f| f.name == name) else {
86            return Err(format!("foreign function '{alias}.{name}' is not declared"));
87        };
88        let at = ForeignFnRef {
89            module,
90            index: u32::try_from(index).expect("fewer than 2^32 exports"),
91        };
92        let mut called = self.outer.called.borrow_mut();
93        if let Some(id) = called
94            .at
95            .iter_enumerated()
96            .find_map(|(id, &r)| (r == at).then_some(id))
97        {
98            return Ok(id);
99        }
100        let structs = |s: &str| self.outer.names.structs.get(s).copied();
101        let (params, ret) = signature(&file.exports[index], file.lang(), &structs)
102            .map_err(|why| format!("'{alias}.{name}' has a type fic cannot express: {why}"))?;
103        called.sigs.push(ForeignFn {
104            name: name.to_owned(),
105            params,
106            ret,
107            variadic: file.exports[index].variadic,
108        });
109        Ok(called.at.push(at))
110    }
111
112    fn type_ref(&self, ty: &Type) -> Result<TypeRef, String> {
113        type_ref(ty, self.outer.names)
114    }
115
116    fn undeclared(&self, name: &str) -> String {
117        match self.outer.process_vars.get(name) {
118            Some(p) if self.event => format!(
119                "variable '{name}' is not declared (process '{p}' declares '{name}'; \
120                 an event sees only its carriers)"
121            ),
122            _ => format!("variable '{name}' is not declared"),
123        }
124    }
125
126    fn file(&self) -> &str {
127        self.outer.file
128    }
129
130    fn context(&self) -> &str {
131        &self.context
132    }
133}
134
135impl Outer<'_, '_> {
136    /// What a body variable called `name` would shadow, if anything.
137    pub(super) fn shadowed(&self, name: &str) -> Option<&'static str> {
138        if self.locals.contains_key(name) {
139            Some("local variable")
140        } else if self.mappings.contains_key(name) {
141            Some("mapping")
142        } else if self.names.consts.contains_key(name) {
143            Some("constant")
144        } else {
145            None
146        }
147    }
148}