1use std::ops::Range;
12
13use serde::Serialize;
14
15use crate::ast::{BinaryOp, Lit, UnaryOp};
16use crate::base::{FfnId, MappingId, VarRef};
17use crate::error::Diagnostic;
18use crate::rast;
19
20use super::ops::{binary, unary};
21use super::scope::Scope;
22use super::ty::{lower, size_of, Ty};
23
24#[derive(Debug, Clone, Serialize)]
26pub struct Expr {
27 pub kind: ExprKind,
29 pub ty: Ty,
31 pub span: Range<usize>,
33}
34
35#[derive(Debug, Clone, Serialize)]
37pub enum ExprKind {
38 Lit(Lit),
40 Var(VarRef),
42 Vaddr(MappingId),
44 Paddr(MappingId),
46 Call(Call),
48 Cast {
51 expr: Box<Expr>,
53 ty: Ty,
55 },
56 Sizeof {
58 ty: Ty,
60 size: u64,
62 },
63 Unary {
65 op: UnaryOp,
67 operand: Box<Expr>,
69 },
70 Binary {
72 op: BinaryOp,
74 lhs: Box<Expr>,
76 rhs: Box<Expr>,
78 },
79 Field {
81 base: Box<Expr>,
83 field: u32,
85 offset: u64,
87 },
88}
89
90#[derive(Debug, Clone, Serialize)]
92pub struct Call {
93 pub callee: FfnId,
95 pub args: Vec<Expr>,
97 pub ret: Option<Ty>,
100 pub span: Range<usize>,
102}
103
104pub(super) fn expr(
109 e: &rast::Expr,
110 expect: Option<&Ty>,
111 cx: &Scope<'_>,
112 errors: &mut Vec<Diagnostic>,
113) -> Option<Expr> {
114 use rast::ExprKind as K;
115 let (kind, ty) = match &e.kind {
116 K::Lit(Lit::Int(v)) => (
117 ExprKind::Lit(Lit::Int(*v)),
118 integer(*v, expect, &e.span, cx, errors)?,
119 ),
120 K::Lit(Lit::Hex(v)) => (
121 ExprKind::Lit(Lit::Hex(*v)),
122 hex(*v, expect, &e.span, cx, errors)?,
123 ),
124 K::Lit(Lit::Bool(b)) => (ExprKind::Lit(Lit::Bool(*b)), Ty::BOOL),
125 K::Var(v) => match cx.var(*v) {
126 Ok(ty) => (ExprKind::Var(*v), ty.clone()),
127 Err(m) => {
128 cx.fail(errors, &m, &e.span);
129 return None;
130 }
131 },
132 K::Vaddr(m) => {
133 let region = cx.env.mappings[*m].region;
134 (ExprKind::Vaddr(*m), Ty::Addr(Some(region)))
135 }
136 K::Paddr(m) => (ExprKind::Paddr(*m), Ty::Addr(None)),
137 K::Sizeof(t) => {
138 let size = size_of(t, cx.values, cx.env, &|id| cx.struct_size(id));
139 let (size, ty) = match (size, lower(t, cx.values, cx.env)) {
140 (Ok(size), Ok(ty)) => (size, ty),
141 (Err(m), _) | (_, Err(m)) => {
142 cx.fail(errors, &m, &e.span);
143 return None;
144 }
145 };
146 (
147 ExprKind::Sizeof { ty, size },
148 unsigned(size, expect, &e.span, cx, errors)?,
149 )
150 }
151 K::Cast { expr: inner, ty } => {
152 let target = match lower(ty, cx.values, cx.env) {
153 Ok(t) => t,
154 Err(m) => {
155 cx.fail(errors, &m, &e.span);
156 return None;
157 }
158 };
159 if target.integer().is_none() && target != Ty::Addr(None) {
160 cx.fail(
161 errors,
162 &format!("cannot cast to '{}'", cx.show(&target)),
163 &e.span,
164 );
165 return None;
166 }
167 let inner = expr(inner, None, cx, errors)?;
168 if inner.ty.integer().is_none() && !matches!(inner.ty, Ty::Addr(_)) {
169 cx.fail(
170 errors,
171 &format!("cannot cast a value of type '{}'", cx.show(&inner.ty)),
172 &e.span,
173 );
174 return None;
175 }
176 (
177 ExprKind::Cast {
178 expr: Box::new(inner),
179 ty: target.clone(),
180 },
181 target,
182 )
183 }
184 K::Unary { op, operand } => unary(*op, operand, expect, &e.span, cx, errors)?,
185 K::Binary { op, lhs, rhs } => binary(*op, lhs, rhs, expect, &e.span, cx, errors)?,
186 K::Field { base, name } => field(base, name, &e.span, cx, errors)?,
187 K::Call { callee, args } => {
188 let call = call(*callee, args, true, &e.span, cx, errors)?;
189 let ty = call
190 .ret
191 .clone()
192 .expect("a call in value position has a value");
193 (ExprKind::Call(call), ty)
194 }
195 };
196 check(kind, ty, expect, &e.span, cx, errors)
197}
198
199fn check(
201 kind: ExprKind,
202 ty: Ty,
203 expect: Option<&Ty>,
204 span: &Range<usize>,
205 cx: &Scope<'_>,
206 errors: &mut Vec<Diagnostic>,
207) -> Option<Expr> {
208 if let Some(x) = expect {
209 if !ty.is_subtype(x) {
210 cx.fail(
211 errors,
212 &format!("expected '{}', found '{}'", cx.show(x), cx.show(&ty)),
213 span,
214 );
215 return None;
216 }
217 }
218 Some(Expr {
219 kind,
220 ty,
221 span: span.clone(),
222 })
223}
224
225fn unsigned(
228 v: u64,
229 expect: Option<&Ty>,
230 span: &Range<usize>,
231 cx: &Scope<'_>,
232 errors: &mut Vec<Diagnostic>,
233) -> Option<Ty> {
234 let ty = match expect {
235 Some(t) if t.integer().is_some_and(|p| !p.is_signed()) => t.clone(),
236 _ => Ty::UINT,
237 };
238 match ty.fits_u64(v, cx.env) {
239 Ok(()) => Some(ty),
240 Err(m) => {
241 cx.fail(errors, &m, span);
242 None
243 }
244 }
245}
246
247pub(super) fn rank(e: &rast::Expr) -> u8 {
251 use rast::ExprKind as K;
252 match &e.kind {
253 K::Lit(Lit::Int(_) | Lit::Hex(_)) => 0,
254 K::Sizeof(_) => 1,
255 _ => 2,
256 }
257}
258
259fn literal_type(expect: Option<&Ty>) -> Ty {
262 match expect {
263 Some(t) if t.integer().is_some() || matches!(t, Ty::Addr(_)) => t.clone(),
264 _ => Ty::INT,
265 }
266}
267
268pub(super) fn integer(
270 v: i64,
271 expect: Option<&Ty>,
272 span: &Range<usize>,
273 cx: &Scope<'_>,
274 errors: &mut Vec<Diagnostic>,
275) -> Option<Ty> {
276 let ty = literal_type(expect);
277 match ty.fits_i64(v, cx.env) {
278 Ok(()) => Some(ty),
279 Err(m) => {
280 cx.fail(errors, &m, span);
281 None
282 }
283 }
284}
285
286fn hex(
288 v: u64,
289 expect: Option<&Ty>,
290 span: &Range<usize>,
291 cx: &Scope<'_>,
292 errors: &mut Vec<Diagnostic>,
293) -> Option<Ty> {
294 let ty = literal_type(expect);
295 match ty.fits_u64(v, cx.env) {
296 Ok(()) => Some(ty),
297 Err(m) => {
298 cx.fail(errors, &m, span);
299 None
300 }
301 }
302}
303
304fn field(
305 base: &rast::Expr,
306 name: &str,
307 span: &Range<usize>,
308 cx: &Scope<'_>,
309 errors: &mut Vec<Diagnostic>,
310) -> Option<(ExprKind, Ty)> {
311 let base = expr(base, None, cx, errors)?;
312 let Ty::Struct(r) = base.ty else {
313 cx.fail(
314 errors,
315 &format!(
316 "'.{name}' on a value of type '{}', not a struct",
317 cx.show(&base.ty)
318 ),
319 span,
320 );
321 return None;
322 };
323 let s = match cx.struct_of(r) {
324 Ok(s) => s,
325 Err(m) => {
326 cx.fail(errors, &m, span);
327 return None;
328 }
329 };
330 let Some(index) = s.fields.iter().position(|f| f.name == name) else {
331 cx.fail(
332 errors,
333 &format!("struct '{}' has no field '{name}'", s.name),
334 span,
335 );
336 return None;
337 };
338 let f = &s.fields[index];
339 Some((
340 ExprKind::Field {
341 base: Box::new(base),
342 field: u32::try_from(index).expect("fewer than 2^32 fields"),
343 offset: f.offset,
344 },
345 f.ty.clone(),
346 ))
347}
348
349pub(super) fn call(
353 callee: FfnId,
354 args: &[rast::Expr],
355 value: bool,
356 span: &Range<usize>,
357 cx: &Scope<'_>,
358 errors: &mut Vec<Diagnostic>,
359) -> Option<Call> {
360 let name = cx.callee_name(callee);
361 let sig = cx.signature(callee);
362 let arity = if sig.variadic {
363 args.len() >= sig.params.len()
364 } else {
365 args.len() == sig.params.len()
366 };
367 if !arity {
368 cx.fail(
369 errors,
370 &format!(
371 "'{name}' takes {} argument(s), found {}",
372 sig.params.len(),
373 args.len()
374 ),
375 span,
376 );
377 return None;
378 }
379 if value && sig.ret.is_none() {
380 cx.fail(errors, &format!("'{name}' returns no value"), span);
381 return None;
382 }
383 let mut typed = Vec::with_capacity(args.len());
384 let mut ok = true;
385 for (i, a) in args.iter().enumerate() {
386 let param = sig.params.get(i);
388 let at = Scope {
389 context: format!("{}argument {} of '{name}': ", cx.base, i + 1),
390 ..cx.clone()
391 };
392 match expr(a, param, &at, errors) {
393 Some(a) => typed.push(a),
394 None => ok = false,
395 }
396 }
397 if !ok {
398 return None;
399 }
400 Some(Call {
401 callee,
402 args: typed,
403 ret: sig.ret.clone(),
404 span: span.clone(),
405 })
406}
407
408#[cfg(test)]
409mod tests {
410 use super::*;
411 use crate::ast::PrimitiveType;
412 use crate::base::{EventId, Idx, LocalVarId, MrId, PdId};
413 use crate::tast::env::{built, built_with};
414 use crate::tast::Stmt;
415
416 const FIS: &str = "struct Slot { len: uint16; seq: uint32; }
417 const N: int = 4;
418 MemoryRegion ring(0x1000);
419 ProtectionDomain a(1);";
420
421 fn src(rest: &str) -> String {
423 format!(
424 "Mapping m(ring, \"rw\");
425 i: int; u: uint8; w: uint32; q: uint64; b: bool; s: Slot; p: Address;
426 {rest}"
427 )
428 }
429
430 fn rhs(target: &str, value: &str) -> Expr {
432 let body = format!("evt e: {target} = {value};");
433 let (tast, _) = built(FIS, &[("a", &src(&body))]).expect("types");
434 let event = &tast.bodies[PdId::new(0)].events[EventId::new(0)];
435 let Stmt::Assign { rhs, .. } = &event.body[0] else {
436 panic!("an assignment");
437 };
438 rhs.clone()
439 }
440
441 fn errors(rest: &str) -> Vec<String> {
443 built(FIS, &[("a", &src(rest))])
444 .expect_err("rejected")
445 .0
446 .iter()
447 .map(|d| d.message().to_owned())
448 .collect()
449 }
450
451 fn rejects(rest: &str, needle: &str) {
452 let e = errors(rest);
453 assert!(
454 e.iter().any(|m| m.contains(needle)),
455 "missing {needle:?} in {e:?}"
456 );
457 }
458
459 #[test]
460 fn a_literal_takes_the_expected_type_and_must_fit_it() {
461 assert_eq!(rhs("u", "200").ty, Ty::Prim(PrimitiveType::UInt8));
462 assert_eq!(rhs("p", "0x4000_0000").ty, Ty::Addr(None));
463 rejects(
464 "evt e: u = 300;",
465 "event 'e': assignment to 'u': value 300 is out of range for uint8 (0..=255)",
466 );
467 rejects(
468 "evt e: b = 1;",
469 "event 'e': assignment to 'b': expected 'bool', found 'int64'",
470 );
471 rejects("evt e: s = 0;", "expected 'Slot', found 'int64'");
472 }
473
474 #[test]
475 fn widths_are_strict() {
476 rejects(
477 "evt e: i = w;",
478 "assignment to 'i': expected 'int64', found 'uint32'",
479 );
480 rejects("evt e: w = u;", "expected 'uint32', found 'uint8'");
481 assert_eq!(rhs("i", "N").ty, Ty::Prim(PrimitiveType::Int64));
482 }
483
484 #[test]
485 fn an_operand_takes_the_other_sides_type() {
486 let e = rhs("w", "w + 1");
488 assert_eq!(e.ty, Ty::Prim(PrimitiveType::UInt32));
489 let ExprKind::Binary { rhs: one, .. } = &e.kind else {
490 panic!("binary");
491 };
492 assert_eq!(one.ty, Ty::Prim(PrimitiveType::UInt32));
493 assert_eq!(rhs("w", "1 + w").ty, Ty::Prim(PrimitiveType::UInt32));
494 assert_eq!(rhs("b", "w == 2").ty, Ty::BOOL);
496 assert_eq!(rhs("b", "i < N && !b").ty, Ty::BOOL);
497 rejects(
498 "evt e: b = 2 + 2 == true;",
499 "expected 'int64', found 'bool'",
500 );
501 rejects(
503 "evt e: i = w + i;",
504 "assignment to 'i': expected 'int64', found 'uint32'",
505 );
506 rejects("evt e: b = b + b;", "'+' is not defined on 'bool'");
507 rejects(
509 "evt e: u = u + (200 + 100);",
510 "event 'e': assignment to 'u': '+' overflows uint8: 200 + 100",
511 );
512 assert_eq!(
513 rhs("u", "u + (200 + 55)").ty,
514 Ty::Prim(PrimitiveType::UInt8)
515 );
516 rejects("evt e: b = b < b;", "'<' is not defined on 'bool'");
517 rejects("evt e: b = s == s;", "cannot compare values of type 'Slot'");
518 rejects("evt e: b = i && b;", "expected 'bool', found 'int64'");
519 }
520
521 #[test]
524 fn a_cast_is_explicit_and_typed_by_its_target() {
525 assert_eq!(rhs("w", "q as uint32").ty, Ty::Prim(PrimitiveType::UInt32));
526 assert_eq!(rhs("i", "w as int").ty, Ty::INT);
527 assert_eq!(rhs("q", "p as uint").ty, Ty::UINT);
528 assert_eq!(rhs("p", "q as Address").ty, Ty::Addr(None));
529 assert_eq!(
531 rhs("p", "m.vaddr + w as uint").ty,
532 Ty::Addr(Some(MrId::new(0)))
533 );
534 let (tast, _) =
536 built(FIS, &[("a", &src("evt e: i = 255 as int8 as int;"))]).expect("types");
537 let e = &tast.bodies[PdId::new(0)].events[EventId::new(0)];
538 assert_eq!(e.body.len(), 1);
539 assert_eq!(rhs("u", "300 as uint8").ty, Ty::Prim(PrimitiveType::UInt8));
541 rejects(
542 "evt e: q = s as uint;",
543 "cannot cast a value of type 'Slot'",
544 );
545 rejects("evt e: b = i as bool;", "cannot cast to 'bool'");
546 rejects("evt e: i = q as Slot;", "cannot cast to 'Slot'");
547 rejects("evt e: i = w as uint;", "expected 'int64', found 'uint64'");
548 }
549
550 #[test]
551 fn unary_operators_need_their_kind_of_operand() {
552 assert_eq!(rhs("i", "-i").ty, Ty::Prim(PrimitiveType::Int64));
553 assert!(matches!(rhs("i", "-5").kind, ExprKind::Lit(Lit::Int(-5))));
555 assert_eq!(rhs("u", "-0").ty, Ty::Prim(PrimitiveType::UInt8));
556 assert_eq!(rhs("u", "~u").ty, Ty::Prim(PrimitiveType::UInt8));
557 assert_eq!(rhs("b", "!b").ty, Ty::BOOL);
558 rejects(
559 "evt e: u = -u;",
560 "'-' is not defined on unsigned type 'uint8'",
561 );
562 rejects("evt e: b = ~b;", "'~' is not defined on 'bool'");
563 rejects("evt e: b = !i;", "'!' is not defined on 'int64'");
564 }
565
566 #[test]
567 fn a_field_is_its_index_and_offset() {
568 let e = rhs("w", "s.seq");
569 assert_eq!(e.ty, Ty::Prim(PrimitiveType::UInt32));
570 let ExprKind::Field { field, offset, .. } = e.kind else {
571 panic!("a field");
572 };
573 assert_eq!((field, offset), (1, 4), "seq at uint32's alignment");
574 rejects("evt e: w = s.nope;", "struct 'Slot' has no field 'nope'");
575 rejects(
576 "evt e: w = w.seq;",
577 "'.seq' on a value of type 'uint32', not a struct",
578 );
579 }
580
581 #[test]
582 fn addresses_and_sizes() {
583 assert_eq!(rhs("p", "m.vaddr").ty, Ty::Addr(Some(MrId::new(0))));
584 assert_eq!(rhs("p", "m.paddr").ty, Ty::Addr(None));
585 assert_eq!(rhs("p", "m.vaddr + 8").ty, Ty::Addr(Some(MrId::new(0))));
586 assert_eq!(rhs("p", "m.vaddr + q").ty, Ty::Addr(Some(MrId::new(0))));
588 assert_eq!(rhs("p", "m.vaddr - i").ty, Ty::Addr(Some(MrId::new(0))));
589 rejects(
590 "evt e: p = m.vaddr + w;",
591 "'+' is not defined on 'Addr(ring)' and 'uint32'",
592 );
593 assert_eq!(rhs("b", "m.vaddr == 0x1000").ty, Ty::BOOL);
596 assert_eq!(rhs("b", "0x1000 < m.vaddr").ty, Ty::BOOL);
597 rejects(
598 "evt e: p = 8 + m.vaddr;",
599 "'+' is not defined on 'int64' and 'Addr(ring)'",
600 );
601 assert_eq!(
603 rhs("q", "0xFFFF_FFFF_FFFF_FFFF").ty,
604 Ty::Prim(PrimitiveType::UInt64)
605 );
606 rejects(
607 "evt e: i = 0xFFFF_FFFF_FFFF_FFFF;",
608 "value 18446744073709551615 is out of range for int64",
609 );
610 let e = rhs("w", "sizeof(Slot)");
613 assert_eq!(e.ty, Ty::Prim(PrimitiveType::UInt32));
614 assert!(matches!(e.kind, ExprKind::Sizeof { size: 8, .. }));
615 assert_eq!(rhs("q", "sizeof(Slot)").ty, Ty::UINT);
616 assert_eq!(rhs("b", "sizeof(Slot) < 8").ty, Ty::BOOL);
617 rejects(
618 "evt e: i = sizeof(Slot);",
619 "expected 'int64', found 'uint64'",
620 );
621 rejects(
622 "evt e: q = -sizeof(Slot);",
623 "'-' is not defined on unsigned type 'uint64'",
624 );
625 rejects("evt e: i = sizeof(int);", "'int' has no fixed size");
626 rejects(
627 "evt e: w = m.vaddr;",
628 "expected 'uint32', found 'Addr(ring)'",
629 );
630 }
631
632 #[test]
633 fn a_call_is_typed_by_its_signature() {
634 let pnk = "export fun 1 inc(1 r) { return r + 1; }\n";
635 let ok = |body: &str| {
636 built_with(
637 FIS,
638 &[("a", &format!("import \"io.pnk\" as io;\n{}", src(body)))],
639 "io.pnk",
640 pnk,
641 )
642 };
643 let (tast, _) = ok("g: uint; evt e: g = io.inc(g);").expect("types");
644 let event = &tast.bodies[PdId::new(0)].events[EventId::new(0)];
645 let Stmt::Assign { rhs, .. } = &event.body[0] else {
646 panic!("an assignment");
647 };
648 assert_eq!(rhs.ty, Ty::Prim(PrimitiveType::UInt64));
649 let messages = |body: &str| -> Vec<String> {
650 ok(body)
651 .expect_err("rejected")
652 .0
653 .iter()
654 .map(|d| d.message().to_owned())
655 .collect()
656 };
657 let e = messages("evt e: i = io.inc(i);");
658 assert!(
659 e.iter()
660 .any(|m| m == "event 'e': argument 1 of 'inc': expected 'uint64', found 'int64'"),
661 "{e:?}"
662 );
663 let e = messages("g: uint; evt e: g = io.inc(g, g);");
664 assert!(
665 e.iter()
666 .any(|m| m.contains("'inc' takes 1 argument(s), found 2")),
667 "{e:?}"
668 );
669 assert_eq!(tast.tenv.locals[PdId::new(0)][LocalVarId::new(7)].name, "g");
670 }
671
672 #[test]
673 fn a_procedure_has_no_value_but_may_be_a_statement() {
674 let header = "void poke(int v);\n";
675 let ok = |body: &str| {
676 built_with(
677 FIS,
678 &[("a", &format!("import \"x.h\" as x;\n{}", src(body)))],
679 "x.h",
680 header,
681 )
682 };
683 let (tast, _) = ok("v: int32; evt e: x.poke(v);").expect("a statement call types");
684 let Stmt::Call(call) = &tast.bodies[PdId::new(0)].events[EventId::new(0)].body[0] else {
685 panic!("a call");
686 };
687 assert_eq!(call.ret, None);
688 let e = ok("v: int32; evt e: v = x.poke(v);").expect_err("no value");
689 assert!(e.to_string().contains("'poke' returns no value"), "{e}");
690 }
691
692 #[test]
696 fn an_inexpressible_signature_is_an_error_when_called() {
697 let header = "float scale(int v, float by);\nfloat ratio(void);\nint ok(int v);\n";
698 let ok = |body: &str| {
699 built_with(
700 FIS,
701 &[("a", &format!("import \"x.h\" as x;\n{}", src(body)))],
702 "x.h",
703 header,
704 )
705 };
706 let e = ok("v: int32; evt e: x.scale(v, v);").expect_err("inexpressible");
707 assert!(
708 e.to_string().contains(
709 "'x.scale' has a type fic cannot express: parameter 2 ('by') has type 'float', which has no fic type"
710 ),
711 "{e}"
712 );
713 let e = ok("v: int32; evt e: v = x.ratio();").expect_err("inexpressible");
714 assert!(
715 e.to_string().contains(
716 "'x.ratio' has a type fic cannot express: it returns 'float', which has no fic type"
717 ),
718 "{e}"
719 );
720 assert_eq!(e.0[0].filename(), Some("a.fi"));
721 ok("v: int32; evt e: v = x.ok(v);").expect("the uncalled float functions are no error");
722 }
723}