1use std::mem::take;
13use std::ops::Range;
14
15use serde::Serialize;
16
17use crate::base::{
18 BodyVarId, BodyVarKind, ChanId, Entry, EventDecl, EventId, FfnId, IdVec, Idx, PdId, ProcId,
19 ProcessDecl, TypeRef,
20};
21use crate::error::Diagnostic;
22use crate::rast::{self, Env};
23
24use super::body::{no_value, BodyVar, Proc, Stmt};
25use super::env::{Channel, ForeignFn, LocalVar, LocalVars};
26use super::ty::{lower, FfnSig, Values};
27
28pub type Bodies = IdVec<PdId, Body>;
31
32#[derive(Debug, Clone, Serialize)]
35pub struct Body {
36 pub events: IdVec<EventId, EventBody>,
38 pub processes: IdVec<ProcId, ProcBody>,
40 pub entries: Vec<Entry>,
42}
43
44#[derive(Debug, Clone, Serialize)]
46pub struct EventBody {
47 pub sig: EventDecl,
49 pub body_vars: IdVec<BodyVarId, BodyVar>,
51 pub body: Vec<Stmt>,
53}
54
55#[derive(Debug, Clone, Serialize)]
57pub struct ProcBody {
58 pub sig: ProcessDecl,
60 pub body_vars: IdVec<BodyVarId, BodyVar>,
63 pub body: Proc,
65}
66
67pub(super) struct VarTables {
70 pub events: IdVec<EventId, IdVec<BodyVarId, BodyVar>>,
71 pub processes: IdVec<ProcId, IdVec<BodyVarId, BodyVar>>,
72}
73
74pub(super) fn type_locals(
76 env: &Env,
77 pd: PdId,
78 values: &Values,
79 errors: &mut Vec<Diagnostic>,
80) -> Option<LocalVars> {
81 let file = env.pds[pd].fi.display().to_string();
82 let mut out = IdVec::new();
83 let mut ok = true;
84 for g in env.locals[pd].iter() {
85 match lower(&g.ty, values, env) {
86 Ok(ty) => {
87 out.push(LocalVar {
88 name: g.name.clone(),
89 ty,
90 span: g.span.clone(),
91 });
92 }
93 Err(m) => {
94 errors.push(Diagnostic::at(
95 format!("variable '{}': {m}", g.name),
96 g.span.clone(),
97 &file,
98 ));
99 ok = false;
100 }
101 }
102 }
103 ok.then_some(out)
104}
105
106pub(super) fn variables(
109 env: &Env,
110 pd: PdId,
111 rast: &mut rast::Body,
112 values: &Values,
113 chans: &IdVec<ChanId, Channel>,
114 errors: &mut Vec<Diagnostic>,
115) -> Option<VarTables> {
116 let file = env.pds[pd].fi.display().to_string();
117 let mut typed = |who: String, sig: Sig<'_>, table| {
118 vars(table, &who, sig, values, chans, env, &file, errors)
119 };
120 let events: Vec<Option<IdVec<BodyVarId, BodyVar>>> = rast
121 .events
122 .iter_mut()
123 .map(|e| {
124 let table = take(&mut e.body_vars);
125 let sig = Sig {
126 types: &e.sig.carriers,
127 span: &e.sig.span,
128 };
129 typed(format!("event '{}'", e.sig.name), sig, table)
130 })
131 .collect();
132 let processes: Vec<Option<IdVec<BodyVarId, BodyVar>>> = rast
133 .processes
134 .iter_mut()
135 .map(|q| {
136 let table = take(&mut q.body_vars);
137 let sig = Sig {
138 types: &q.sig.params,
139 span: &q.sig.span,
140 };
141 typed(format!("process '{}'", q.sig.name), sig, table)
142 })
143 .collect();
144 Some(VarTables {
145 events: events.into_iter().collect::<Option<_>>()?,
146 processes: processes.into_iter().collect::<Option<_>>()?,
147 })
148}
149
150pub(super) fn type_ffis(env: &Env, values: &Values) -> IdVec<FfnId, ForeignFn> {
152 let ty = |t: &TypeRef| lower(t, values, env).expect("a foreign type has no array");
155 env.ffis
156 .iter()
157 .map(|f| ForeignFn {
158 name: f.name.clone(),
159 sig: FfnSig {
160 params: f.params.iter().map(ty).collect(),
161 ret: f.ret.as_ref().map(ty),
162 variadic: f.variadic,
163 },
164 })
165 .collect()
166}
167
168#[derive(Clone, Copy)]
172struct Sig<'a> {
173 types: &'a [TypeRef],
174 span: &'a Range<usize>,
175}
176
177#[allow(clippy::too_many_arguments)]
181fn vars(
182 table: IdVec<BodyVarId, rast::BodyVar>,
183 who: &str,
184 sig: Sig<'_>,
185 values: &Values,
186 chans: &IdVec<ChanId, Channel>,
187 env: &Env,
188 file: &str,
189 errors: &mut Vec<Diagnostic>,
190) -> Option<IdVec<BodyVarId, BodyVar>> {
191 let mut out = IdVec::new();
192 let mut ok = true;
193 for (id, l) in table.into_iter_enumerated() {
194 let ty = match (&l.ty, l.kind) {
195 (Some(t), _) => lower(t, values, env),
196 (None, BodyVarKind::Param | BodyVarKind::Carrier) => {
197 lower(&sig.types[id.index()], values, env)
198 }
199 (None, BodyVarKind::Binder { chan }) => match &chans[chan].payload {
200 Some(payload) => Ok(payload.clone()),
201 None => Err(no_value(&chans[chan], "?")),
202 },
203 (None, _) => unreachable!("rast types every declared variable"),
204 };
205 match ty {
206 Ok(ty) => {
207 out.push(BodyVar {
208 name: l.name,
209 ty,
210 kind: l.kind,
211 span: l.span,
212 });
213 }
214 Err(m) => {
215 let span = if l.span.is_empty() { sig.span } else { &l.span };
216 errors.push(Diagnostic::at(
217 format!("{who}, {} '{}': {m}", role(l.kind), l.name),
218 span.clone(),
219 file,
220 ));
221 ok = false;
222 }
223 }
224 }
225 ok.then_some(out)
226}
227
228fn role(kind: BodyVarKind) -> &'static str {
230 match kind {
231 BodyVarKind::Param => "parameter",
232 BodyVarKind::Carrier => "carrier",
233 BodyVarKind::Binder { .. } => "receive binder",
234 BodyVarKind::Decl | BodyVarKind::EventDecl => "variable",
235 }
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241 use crate::ast::PrimitiveType;
242 use crate::base::{
243 ChanId, Endpoint, FfnId, Idx, LocalVarId, Mapping, MappingId, PdId, StructId,
244 };
245 use crate::tast::env::{built, built_with};
246 use crate::tast::{ProgramView, Tast, Ty};
247
248 const FIS: &str = "struct Slot { seq: uint16; }
249 const N: int = 4;
250 MemoryRegion mr(0x1000);
251 MemoryRegion ring(0x1000);
252 ProtectionDomain a(1);
253 ProtectionDomain b(2);
254 ProtectionDomain c(3);
255 Chan ab = a --> b via ring<Slot>;
256 Chan bc = b <-> c;";
257
258 const A: &str = r#"import "io.pnk" as io;
259 Mapping m(mr, "rw");
260 d: Slot;
261 n: int;
262 buf: byte[N];
263 @bind(microkit.init)
264 proc Init() { Skip; }
265 @bind(microkit.notified)
266 proc Notified() { Skip; }
267 proc Helper(k: uint8) { t: Address; Skip; }
268 evt e.|p: Slot|: { q: int; io.g(); }"#;
269
270 fn program() -> Tast {
271 built_with(
272 FIS,
273 &[("a", A)],
274 "io.pnk",
275 "export fun 1 f(1 x) { return x; }\nexport fun 1 g() { return 0; }\n",
276 )
277 .expect("builds")
278 .0
279 }
280
281 #[test]
282 fn declarations_are_typed_by_id() {
283 let tast = program();
284 let locals = &tast.tenv.locals[PdId::new(0)];
285 let bodies = &tast.bodies[PdId::new(0)];
286 assert_eq!(locals[LocalVarId::new(0)].ty, Ty::Struct(StructId::new(0)));
287 assert_eq!(
288 locals[LocalVarId::new(1)].ty,
289 Ty::Prim(PrimitiveType::Int64)
290 );
291 let Ty::Array { len, .. } = &locals[LocalVarId::new(2)].ty else {
292 panic!("an array");
293 };
294 assert_eq!(
295 (len.len, len.written),
296 (4, Some(crate::base::ConstId::new(0)))
297 );
298 let helper = &bodies.processes[ProcId::new(2)];
299 assert_eq!(
300 helper.body_vars[BodyVarId::new(0)].ty,
301 Ty::Prim(PrimitiveType::UInt8)
302 );
303 assert_eq!(helper.body_vars[BodyVarId::new(1)].ty, Ty::Addr(None));
304 let e = &bodies.events[EventId::new(0)];
305 assert_eq!(
306 e.body_vars[BodyVarId::new(0)].ty,
307 Ty::Struct(StructId::new(0))
308 );
309 assert_eq!(
310 e.body_vars[BodyVarId::new(1)].ty,
311 Ty::Prim(PrimitiveType::Int64)
312 );
313 assert_eq!(bodies.entries.len(), 2);
314 }
315
316 #[test]
317 fn a_receive_binder_takes_its_channels_payload() {
318 let fis = FIS.replace(
320 "Chan bc = b <-> c;",
321 "MemoryRegion ring2(0x1000);\n Chan bc = c --> b via ring2<uint8>;",
322 );
323 let (tast, _) = built(
324 &fis,
325 &[(
326 "b",
327 "@bind(microkit.init) proc Init() { Skip; }
328 @bind(microkit.notified) proc Notified() { ab?s -> bc?x -> Skip; }",
329 )],
330 )
331 .expect("builds");
332 let notified = &tast.bodies[PdId::new(1)].processes[ProcId::new(1)];
333 assert_eq!(
334 notified.body_vars[BodyVarId::new(0)].ty,
335 Ty::Struct(StructId::new(0))
336 );
337 assert_eq!(
338 notified.body_vars[BodyVarId::new(1)].ty,
339 Ty::Prim(PrimitiveType::UInt8)
340 );
341 }
342
343 #[test]
344 fn a_program_maps_its_buffers_then_its_own_mappings() {
345 let (tast, _) = built(
346 FIS,
347 &[(
348 "b",
349 "Mapping m(mr, \"rw\");\nx: Address;\nevt e: x = m.paddr;",
350 )],
351 )
352 .expect("builds");
353 let view = ProgramView::new(&tast, PdId::new(1));
354 let mappings: Vec<(MappingId, &Mapping)> = view.mappings().collect();
357 assert_eq!(mappings.len(), 2);
358 let ab = tast.tenv.chans[ChanId::new(0)]
359 .buffer
360 .as_ref()
361 .expect("buffered");
362 assert_eq!(mappings[0].0, ab.mapping(Endpoint::Receiver));
363 assert_eq!(mappings[0].1.name, "ring");
364 assert_eq!(mappings[1].1.name, "m");
365 assert!(!mappings[0].1.paddr_read);
366 assert!(mappings[1].1.paddr_read);
367 }
368
369 #[test]
370 fn each_program_sees_its_end_of_every_channel() {
371 let ends = |pd: &str| -> Vec<Option<Endpoint>> {
372 let (tast, _) = built(FIS, &[(pd, "proc Init() { Skip; }")]).expect("builds");
373 let (at, _) = tast
374 .tenv
375 .pds
376 .iter_enumerated()
377 .find(|(_, d)| d.name == pd)
378 .expect("a PD");
379 tast.tenv
380 .chans
381 .iter()
382 .map(|ch| ch.end(at).map(|(endpoint, _)| endpoint))
383 .collect()
384 };
385 assert_eq!(
386 ends("b"),
387 vec![Some(Endpoint::Receiver), Some(Endpoint::Sender)]
388 );
389 assert_eq!(ends("c"), vec![None, Some(Endpoint::Receiver)]);
390 }
391
392 #[test]
393 fn each_called_function_is_typed_once() {
394 let tast = program();
395 assert_eq!(tast.tenv.ffis.len(), 1);
397 let g = &tast.tenv.ffis[FfnId::new(0)];
398 assert_eq!(g.name, "g");
399 assert!(g.sig.params.is_empty(), "{:?}", g.sig.params);
400 assert_eq!(g.sig.ret, Some(Ty::Prim(PrimitiveType::UInt64)));
401 }
402
403 #[test]
404 fn an_unlowerable_declared_type_is_reported_at_the_declaration() {
405 let rejected = |fi: &str| {
406 built(
407 "const NOPE: bool = true;\nProtectionDomain a(10);",
408 &[("a", fi)],
409 )
410 .expect_err("rejected")
411 };
412 let e = rejected("buf: byte[NOPE];\nproc Init() { Skip; }");
413 assert_eq!(
414 e.0[0].message(),
415 "variable 'buf': array length 'NOPE' is a bool, not an integer"
416 );
417 assert_eq!(e.0[0].filename(), Some("a.fi"));
418 let e = rejected("proc Init() { Skip; }\nevt e.|p: byte[NOPE]|: x: int;");
419 assert_eq!(
420 e.0[0].message(),
421 "event 'e', carrier 'p': array length 'NOPE' is a bool, not an integer"
422 );
423 assert_eq!(e.0[0].filename(), Some("a.fi"));
424 }
425}