logicaffeine_compile/analysis/dimension_check.rs
1//! Dimension-aware static analysis — rejects dimension-incoherent quantity arithmetic at COMPILE
2//! time, before any code is generated. `2 meters + 1 gram` is a *type error*, not a runtime panic:
3//! a length and a mass have no common dimension, so adding them cannot mean anything.
4//!
5//! This is a dedicated pass in the [`crate::analysis::escape::EscapeChecker`] /
6//! [`crate::analysis::ownership`] mold, wired as a gate in `compile.rs`. It runs on the SAME AST the
7//! interpreter and the AOT compiler share, so a dimension error is reported identically on every tier
8//! before execution.
9//!
10//! **Soundness is conservative.** Every quantity *value* already carries its dimension at runtime;
11//! this pass only adds a *static* rejection where it can PROVE incompatibility — i.e. when both
12//! operands' dimensions are statically known and differ. A quantity of unknown dimension (a
13//! `Quantity` function parameter, a collection element, a value from an opaque call) is treated as
14//! dimension-polymorphic and deferred to the existing runtime check. So this pass never rejects a
15//! correct program; it only promotes provable runtime failures to compile-time errors.
16
17use std::collections::HashMap;
18
19use logicaffeine_base::quantity::units;
20use logicaffeine_base::Dimension;
21
22use crate::ast::stmt::{BinaryOpKind, Expr, Literal, Stmt, StmtId, TypeExpr};
23use crate::intern::{Interner, Symbol};
24
25/// The dimensional nature of an expression's value.
26#[derive(Clone, Copy, PartialEq)]
27enum QDim {
28 /// A quantity whose dimension is statically known (e.g. a literal `2 meters`).
29 Known(Dimension),
30 /// A quantity whose dimension is not statically known (a `Quantity` parameter, a collection
31 /// element, …) — dimension-polymorphic, deferred to the runtime check.
32 Unknown,
33 /// Not a quantity (a plain number, text, struct, …).
34 NotQuantity,
35}
36
37impl QDim {
38 fn is_quantity(self) -> bool {
39 !matches!(self, QDim::NotQuantity)
40 }
41}
42
43/// The currency nature of an expression — money's analogue of [`QDim`]. The same pass that proves
44/// dimension coherence also proves currency coherence (`5 USD + 1 EUR` has no answer without a rate
45/// context, exactly like `meter + gram`).
46#[derive(Clone, PartialEq, Eq)]
47enum CurInfo {
48 /// Money whose currency is statically known (a `19.99 USD` / `money(_,"USD")` literal).
49 Known(String),
50 /// Money whose currency is not statically known (a `Money` parameter, a collection element).
51 Unknown,
52 /// Not money.
53 NotMoney,
54}
55
56impl CurInfo {
57 fn is_money(&self) -> bool {
58 !matches!(self, CurInfo::NotMoney)
59 }
60}
61
62/// A dimension coherence error. `trail` names the statements it propagated out through,
63/// innermost first — the statement that holds the incoherent arithmetic, then each block
64/// statement around it — so a diagnostic can point at the sentence at fault.
65pub struct DimensionError {
66 pub message: String,
67 pub trail: Vec<StmtId>,
68}
69
70impl std::fmt::Display for DimensionError {
71 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72 write!(f, "{}", self.message)
73 }
74}
75
76pub struct DimensionChecker<'a> {
77 /// Variables (and parameters) whose dimensional nature is known in the current scope.
78 vars: HashMap<Symbol, QDim>,
79 /// User function name → the dimensional nature of its declared return type, so a call to a
80 /// function returning `Quantity of Area` is statically known to be an area.
81 fn_returns: HashMap<Symbol, QDim>,
82 /// Variables whose currency is statically known in the current scope (money's analogue of `vars`).
83 cur_vars: HashMap<Symbol, CurInfo>,
84 interner: &'a Interner,
85}
86
87impl<'a> DimensionChecker<'a> {
88 pub fn new(interner: &'a Interner) -> Self {
89 Self {
90 vars: HashMap::new(),
91 fn_returns: HashMap::new(),
92 cur_vars: HashMap::new(),
93 interner,
94 }
95 }
96
97 pub fn check_program(&mut self, stmts: &[Stmt<'_>]) -> Result<(), DimensionError> {
98 // Pre-pass: record every function's declared return dimension (forward references included).
99 self.collect_fn_returns(stmts);
100 self.check_block(stmts)
101 }
102
103 fn collect_fn_returns(&mut self, stmts: &[Stmt<'_>]) {
104 for stmt in stmts {
105 if let Stmt::FunctionDef {
106 name, return_type, ..
107 } = stmt
108 {
109 let qd = return_type
110 .map(|t| self.dim_from_type(t))
111 .unwrap_or(QDim::NotQuantity);
112 self.fn_returns.insert(*name, qd);
113 }
114 }
115 }
116
117 /// The dimensional nature declared by a type annotation: `Quantity of Length` → `Known(L)`,
118 /// bare `Quantity` → `Unknown` (dimension-polymorphic), anything else → `NotQuantity`.
119 fn dim_from_type(&self, ty: &TypeExpr<'_>) -> QDim {
120 match ty {
121 TypeExpr::Generic { base, params }
122 if self.interner.resolve(*base) == "Quantity" && params.len() == 1 =>
123 {
124 match ¶ms[0] {
125 TypeExpr::Primitive(s) | TypeExpr::Named(s) => {
126 match Dimension::by_name(self.interner.resolve(*s)) {
127 Some(d) => QDim::Known(d),
128 None => QDim::Unknown,
129 }
130 }
131 _ => QDim::Unknown,
132 }
133 }
134 TypeExpr::Primitive(s) | TypeExpr::Named(s)
135 if self.interner.resolve(*s) == "Quantity" =>
136 {
137 QDim::Unknown
138 }
139 _ => QDim::NotQuantity,
140 }
141 }
142
143 fn check_block(&mut self, stmts: &[Stmt<'_>]) -> Result<(), DimensionError> {
144 for stmt in stmts {
145 self.check_stmt(stmt)?;
146 }
147 Ok(())
148 }
149
150 fn check_stmt(&mut self, stmt: &Stmt<'_>) -> Result<(), DimensionError> {
151 self.check_stmt_kind(stmt).map_err(|mut e| {
152 e.trail.push(StmtId::of(stmt));
153 e
154 })
155 }
156
157 fn check_stmt_kind(&mut self, stmt: &Stmt<'_>) -> Result<(), DimensionError> {
158 match stmt {
159 Stmt::Let { var, value, ty, .. } => {
160 let inferred = self.infer(value)?;
161 // A `Let d: Quantity of Length be …` declares the dimension authoritatively.
162 let declared = ty.map(|t| self.dim_from_type(t));
163 let d = match declared {
164 Some(QDim::Known(k)) => QDim::Known(k),
165 Some(QDim::Unknown) if !inferred.is_quantity() => QDim::Unknown,
166 _ => inferred,
167 };
168 self.vars.insert(*var, d);
169 // Track the binding's currency too, so `Let p be 5 USD. ... p + 1 EUR.` is caught.
170 let c = self.currency_of(value);
171 self.cur_vars.insert(*var, c);
172 }
173 Stmt::Set { value, .. } => {
174 self.infer(value)?;
175 }
176 Stmt::SetField { object, value, .. } => {
177 self.infer(object)?;
178 self.infer(value)?;
179 }
180 Stmt::If {
181 cond,
182 then_block,
183 else_block,
184 } => {
185 self.infer(cond)?;
186 self.check_block(then_block)?;
187 if let Some(e) = else_block {
188 self.check_block(e)?;
189 }
190 }
191 Stmt::While { cond, body, .. } => {
192 self.infer(cond)?;
193 self.check_block(body)?;
194 }
195 Stmt::Repeat { iterable, body, .. } => {
196 self.infer(iterable)?;
197 self.check_block(body)?;
198 }
199 Stmt::Return { value: Some(e) } => {
200 self.infer(e)?;
201 }
202 Stmt::Show { object, .. } => {
203 self.infer(object)?;
204 }
205 Stmt::RuntimeAssert { condition, .. } => {
206 self.infer(condition)?;
207 }
208 Stmt::Call { args, .. } => {
209 for a in args {
210 self.infer(a)?;
211 }
212 }
213 Stmt::FunctionDef { params, body, .. } => {
214 // A function body is a fresh scope: a `Quantity` parameter is dimension-polymorphic
215 // (unknown), every other parameter is a non-quantity for our purposes.
216 let saved = self.vars.clone();
217 let saved_cur = self.cur_vars.clone();
218 for (name, ty) in params {
219 let qd = self.dim_from_type(ty);
220 if qd.is_quantity() {
221 // `Quantity of Length` → Known(L); bare `Quantity` → Unknown (polymorphic).
222 self.vars.insert(*name, qd);
223 }
224 }
225 self.check_block(body)?;
226 self.vars = saved;
227 self.cur_vars = saved_cur;
228 }
229 _ => {}
230 }
231 Ok(())
232 }
233
234 /// The dimension named by a unit-string argument (`Literal::Text`), if it resolves; an
235 /// unresolved unit is left `Unknown` (the construction itself errors at runtime).
236 fn unit_dim(&self, expr: &Expr<'_>) -> QDim {
237 if let Expr::Literal(Literal::Text(sym)) = expr {
238 if let Some(unit) = units::by_name(self.interner.resolve(*sym)) {
239 return QDim::Known(unit.dimension);
240 }
241 }
242 QDim::Unknown
243 }
244
245 /// The currency of an expression, when statically known. Mirrors [`Self::infer`] but for money:
246 /// a `money(_, "USD")` literal is `Known("USD")`, a Let-bound money variable carries its currency,
247 /// `+ −` and scaling keep it, and a `Money ÷ Money` becomes `NotMoney` (a Rational ratio).
248 fn currency_of(&self, expr: &Expr<'_>) -> CurInfo {
249 match expr {
250 Expr::Identifier(s) => self.cur_vars.get(s).cloned().unwrap_or(CurInfo::NotMoney),
251 Expr::Call { function, args } => {
252 if self.interner.resolve(*function) == "money" && args.len() == 2 {
253 if let Expr::Literal(Literal::Text(code)) = args[1] {
254 return CurInfo::Known(self.interner.resolve(*code).to_ascii_uppercase());
255 }
256 return CurInfo::Unknown;
257 }
258 CurInfo::NotMoney
259 }
260 Expr::BinaryOp { op, left, right } => match op {
261 BinaryOpKind::Add | BinaryOpKind::Subtract => {
262 let (l, r) = (self.currency_of(left), self.currency_of(right));
263 if let CurInfo::Known(_) = l {
264 l
265 } else {
266 r
267 }
268 }
269 // Scaling money by a number keeps the currency; `Money ÷ Money` is a ratio (not money).
270 BinaryOpKind::Multiply => {
271 let (l, r) = (self.currency_of(left), self.currency_of(right));
272 if matches!(l, CurInfo::Known(_) | CurInfo::Unknown) {
273 l
274 } else {
275 r
276 }
277 }
278 BinaryOpKind::Divide => {
279 let (l, r) = (self.currency_of(left), self.currency_of(right));
280 // money ÷ money → ratio (not money); money ÷ number → money.
281 if r.is_money() {
282 CurInfo::NotMoney
283 } else {
284 l
285 }
286 }
287 _ => CurInfo::NotMoney,
288 },
289 Expr::Copy { expr } | Expr::Give { value: expr } => self.currency_of(expr),
290 _ => CurInfo::NotMoney,
291 }
292 }
293
294 /// Error if both operands are money of *provably different* currencies (`5 USD + 1 EUR`).
295 fn check_currency_match(
296 &self,
297 left: &Expr<'_>,
298 right: &Expr<'_>,
299 verb: &str,
300 ) -> Result<(), DimensionError> {
301 if let (CurInfo::Known(a), CurInfo::Known(b)) =
302 (self.currency_of(left), self.currency_of(right))
303 {
304 if a != b {
305 return Err(DimensionError {
306 message: format!("cannot {verb} money of different currencies ({a} vs {b})"),
307 trail: Vec::new(),
308 });
309 }
310 }
311 Ok(())
312 }
313
314 /// Infer the dimensional nature of an expression, erroring on a statically-incoherent operation.
315 fn infer(&self, expr: &Expr<'_>) -> Result<QDim, DimensionError> {
316 match expr {
317 Expr::Literal(_) => Ok(QDim::NotQuantity),
318 Expr::Identifier(s) => Ok(self.vars.get(s).copied().unwrap_or(QDim::NotQuantity)),
319
320 Expr::Call { function, args } => {
321 for a in args {
322 self.infer(a)?;
323 }
324 match self.interner.resolve(*function) {
325 "quantity" | "convert" if args.len() == 2 => Ok(self.unit_dim(args[1])),
326 // A user function with a declared `Quantity of <Dim>` return is statically known;
327 // any other call may return a quantity we can't see into — polymorphic (Unknown).
328 _ => Ok(self
329 .fn_returns
330 .get(function)
331 .copied()
332 .unwrap_or(QDim::Unknown)),
333 }
334 }
335
336 Expr::BinaryOp { op, left, right } => {
337 let l = self.infer(left)?;
338 let r = self.infer(right)?;
339 match op {
340 // `+` / `−` require equal dimensions; provably-different dimensions are rejected.
341 BinaryOpKind::Add | BinaryOpKind::Subtract => {
342 self.check_currency_match(
343 left,
344 right,
345 if matches!(op, BinaryOpKind::Add) {
346 "add"
347 } else {
348 "subtract"
349 },
350 )?;
351 if let (QDim::Known(a), QDim::Known(b)) = (l, r) {
352 if a != b {
353 return Err(self.mismatch_err(
354 if matches!(op, BinaryOpKind::Add) {
355 "add"
356 } else {
357 "subtract"
358 },
359 a,
360 b,
361 ));
362 }
363 return Ok(QDim::Known(a));
364 }
365 Ok(self.propagate(l, r))
366 }
367 // Ordering two quantities/monies of provably-different kind is meaningless.
368 BinaryOpKind::Lt
369 | BinaryOpKind::Gt
370 | BinaryOpKind::LtEq
371 | BinaryOpKind::GtEq => {
372 self.check_currency_match(left, right, "compare")?;
373 if let (QDim::Known(a), QDim::Known(b)) = (l, r) {
374 if a != b {
375 return Err(self.mismatch_err("compare", a, b));
376 }
377 }
378 Ok(QDim::NotQuantity)
379 }
380 // `×` combines dimensions (Length × Length = Area); scaling by a number keeps it.
381 BinaryOpKind::Multiply => Ok(match (l, r) {
382 (QDim::Known(a), QDim::Known(b)) => QDim::Known(a.mul(b)),
383 (QDim::Known(a), QDim::NotQuantity)
384 | (QDim::NotQuantity, QDim::Known(a)) => QDim::Known(a),
385 _ if l.is_quantity() || r.is_quantity() => QDim::Unknown,
386 _ => QDim::NotQuantity,
387 }),
388 // `÷` subtracts dimensions (Volume ÷ Area = Length); dividing by a number keeps it.
389 BinaryOpKind::Divide => Ok(match (l, r) {
390 (QDim::Known(a), QDim::Known(b)) => QDim::Known(a.div(b)),
391 (QDim::Known(a), QDim::NotQuantity) => QDim::Known(a),
392 _ if l.is_quantity() || r.is_quantity() => QDim::Unknown,
393 _ => QDim::NotQuantity,
394 }),
395 _ => Ok(QDim::NotQuantity),
396 }
397 }
398
399 // Recurse into expression shapes that nest sub-expressions, so a mismatch buried inside
400 // one is still caught. A collection element may be a quantity of unknown dimension.
401 Expr::Not { operand } => {
402 self.infer(operand)?;
403 Ok(QDim::NotQuantity)
404 }
405 Expr::Index { collection, index } => {
406 self.infer(collection)?;
407 self.infer(index)?;
408 Ok(QDim::Unknown)
409 }
410 Expr::Slice {
411 collection,
412 start,
413 end,
414 } => {
415 self.infer(collection)?;
416 self.infer(start)?;
417 self.infer(end)?;
418 Ok(QDim::Unknown)
419 }
420 Expr::Copy { expr } | Expr::Give { value: expr } => self.infer(expr),
421 Expr::Length { collection } => {
422 self.infer(collection)?;
423 Ok(QDim::NotQuantity)
424 }
425 Expr::Contains { collection, value } => {
426 self.infer(collection)?;
427 self.infer(value)?;
428 Ok(QDim::NotQuantity)
429 }
430 _ => Ok(QDim::NotQuantity),
431 }
432 }
433
434 /// For `+`/`−` where at least one side is dimension-unknown: carry a known dimension forward if
435 /// there is one, otherwise stay quantity-but-unknown when either side is a quantity.
436 fn propagate(&self, l: QDim, r: QDim) -> QDim {
437 match (l, r) {
438 (QDim::Known(d), _) | (_, QDim::Known(d)) => QDim::Known(d),
439 _ if l.is_quantity() || r.is_quantity() => QDim::Unknown,
440 _ => QDim::NotQuantity,
441 }
442 }
443
444 fn mismatch_err(&self, verb: &str, a: Dimension, b: Dimension) -> DimensionError {
445 DimensionError {
446 message: format!("cannot {verb} quantities of different dimensions ({a} vs {b})"),
447 trail: Vec::new(),
448 }
449 }
450}