1use 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
20pub(super) struct Called {
23 pub sigs: IdVec<FfnId, ForeignFn>,
24 pub at: IdVec<FfnId, ForeignFnRef>,
25}
26
27pub(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 pub arity: (IdVec<ProcId, usize>, IdVec<EventId, usize>),
38 pub aliases: HashMap<&'s str, ModuleId>,
40 pub foreign: &'a ForeignModules,
41 pub called: &'a RefCell<Called>,
43 pub process_vars: HashMap<String, String>,
46 pub paddr_reads: RefCell<BTreeSet<MappingId>>,
48}
49
50pub(super) struct BodyScope<'w, 'a, 's> {
53 pub outer: &'w Outer<'a, 's>,
54 pub context: String,
56 pub event: bool,
57 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 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}