Skip to main content

fic/rast/
expr.rs

1//! Expressions, resolved: a variable is the declaration it denotes, a call
2//! the foreign function it reaches, `m.vaddr` and `m.paddr` the mapping.
3//!
4//! A struct field stays a name: choosing it needs the base's type.
5//!
6//! `lower` resolves an AST expression against a `Scope`: the system
7//! consts for a const's value, a body's frames for a body.
8
9use std::ops::Range;
10
11use serde::Serialize;
12
13use crate::ast::{self, BinaryOp, Lit, Type, UnaryOp};
14use crate::base::{FfnId, MappingId, TypeRef, VarRef};
15use crate::error::Diagnostic;
16
17/// An expression.
18#[derive(Debug, Clone, Serialize)]
19pub struct Expr {
20    /// What it is.
21    pub kind: ExprKind,
22    /// Byte span in its file.
23    pub span: Range<usize>,
24}
25
26/// The expression forms.
27#[derive(Debug, Clone, Serialize)]
28pub enum ExprKind {
29    /// A literal.
30    Lit(Lit),
31    /// A variable or const.
32    Var(VarRef),
33    /// `m.vaddr`: a mapping's virtual address, which fic's layout chose.
34    Vaddr(MappingId),
35    /// `m.paddr`: the physical address of a mapping's region, which may be
36    /// known only at boot and is patched in at load time.
37    Paddr(MappingId),
38    /// `alias.f(args)`.
39    Call {
40        /// What is called.
41        callee: FfnId,
42        /// Arguments, in order.
43        args: Vec<Expr>,
44    },
45    /// `sizeof(T)`.
46    Sizeof(TypeRef),
47    /// `expr as T`.
48    Cast {
49        /// The value converted.
50        expr: Box<Expr>,
51        /// The type it becomes.
52        ty: TypeRef,
53    },
54    /// `-e`, `!e`, `~e`.
55    Unary {
56        /// The operator.
57        op: UnaryOp,
58        /// Operand.
59        operand: Box<Expr>,
60    },
61    /// `lhs op rhs`.
62    Binary {
63        /// The operator.
64        op: BinaryOp,
65        /// Left-hand side.
66        lhs: Box<Expr>,
67        /// Right-hand side.
68        rhs: Box<Expr>,
69    },
70    /// `base.name` on a struct value.
71    Field {
72        /// The struct value.
73        base: Box<Expr>,
74        /// The field, by name.
75        name: String,
76    },
77}
78
79/// What an expression's names can denote where it is written, and where
80/// to report the ones that denote nothing.
81pub(super) trait Scope {
82    /// The variable or const `name`.
83    fn var(&self, name: &str) -> Option<VarRef>;
84    /// The mapping `name`.
85    fn mapping(&self, name: &str) -> Option<MappingId>;
86    /// A read of mapping `m`'s `.paddr`; a constant cannot read one.
87    fn paddr_read(&self, _m: MappingId) {}
88    /// The function `alias.name`; `Err` says why it does not resolve.
89    fn callee(&self, alias: &str, name: &str) -> Result<FfnId, String>;
90    /// `ty` with its names resolved; `Err` says which does not.
91    fn type_ref(&self, ty: &Type) -> Result<TypeRef, String>;
92    /// Why `name` denotes no variable.
93    fn undeclared(&self, name: &str) -> String {
94        format!("variable '{name}' is not declared")
95    }
96    /// The file diagnostics point into.
97    fn file(&self) -> &str;
98    /// What every diagnostic is prefixed with: `process 'P': `, ...
99    fn context(&self) -> &str;
100}
101
102/// Resolve `e` in `scope`. Each name that does not resolve is reported to
103/// `errors`, and the expression is then `None`.
104pub(super) fn lower(
105    e: &ast::Expr,
106    scope: &impl Scope,
107    errors: &mut Vec<Diagnostic>,
108) -> Option<Expr> {
109    let kind = match &e.kind {
110        ast::ExprKind::Lit(lit) => ExprKind::Lit(lit.clone()),
111        ast::ExprKind::Var(name) => match scope.var(name) {
112            Some(var) => ExprKind::Var(var),
113            None if scope.mapping(name).is_some() => {
114                let message = format!(
115                    "mapping '{name}' is not a value; use '{name}.vaddr' or '{name}.paddr'"
116                );
117                return fail(scope, errors, &message, &e.span);
118            }
119            None => return fail(scope, errors, &scope.undeclared(name), &e.span),
120        },
121        ast::ExprKind::Field { expr, field } => match mapping_base(expr, scope) {
122            Some(m) if field == "vaddr" => ExprKind::Vaddr(m),
123            Some(m) if field == "paddr" => {
124                scope.paddr_read(m);
125                ExprKind::Paddr(m)
126            }
127            Some(_) => {
128                let message =
129                    format!("'{field}' is not a field of a mapping; only 'vaddr' and 'paddr' are");
130                return fail(scope, errors, &message, &e.span);
131            }
132            None => ExprKind::Field {
133                base: Box::new(lower(expr, scope, errors)?),
134                name: field.clone(),
135            },
136        },
137        ast::ExprKind::Call(c) => return call(c, scope, errors),
138        ast::ExprKind::Sizeof(ty) => match scope.type_ref(ty) {
139            Ok(ty) => ExprKind::Sizeof(ty),
140            Err(message) => return fail(scope, errors, &message, &e.span),
141        },
142        ast::ExprKind::Cast { expr, ty } => match scope.type_ref(ty) {
143            Ok(ty) => ExprKind::Cast {
144                expr: Box::new(lower(expr, scope, errors)?),
145                ty,
146            },
147            Err(message) => return fail(scope, errors, &message, &e.span),
148        },
149        // A negated literal is one literal: `-128` is `Lit::Int(-128)`.
150        ast::ExprKind::Unary {
151            op: UnaryOp::Neg,
152            operand,
153        } if matches!(operand.kind, ast::ExprKind::Lit(Lit::Int(_))) => {
154            let ast::ExprKind::Lit(Lit::Int(v)) = &operand.kind else {
155                unreachable!("a decimal literal")
156            };
157            ExprKind::Lit(Lit::Int(
158                v.checked_neg().expect("a parsed numeral is below i64::MAX"),
159            ))
160        }
161        ast::ExprKind::Unary { op, operand } => ExprKind::Unary {
162            op: *op,
163            operand: Box::new(lower(operand, scope, errors)?),
164        },
165        ast::ExprKind::Binary { op, lhs, rhs } => {
166            let lhs = lower(lhs, scope, errors);
167            let rhs = lower(rhs, scope, errors);
168            ExprKind::Binary {
169                op: *op,
170                lhs: Box::new(lhs?),
171                rhs: Box::new(rhs?),
172            }
173        }
174    };
175    Some(Expr {
176        kind,
177        span: e.span.clone(),
178    })
179}
180
181/// Resolve the call `alias.f(args)` in `scope`, as [`lower`].
182pub(super) fn call(
183    c: &ast::CExpr,
184    scope: &impl Scope,
185    errors: &mut Vec<Diagnostic>,
186) -> Option<Expr> {
187    let callee = scope.callee(&c.alias, &c.fn_name);
188    let args: Vec<_> = c.args.iter().map(|a| lower(a, scope, errors)).collect();
189    let callee = match callee {
190        Ok(callee) => callee,
191        Err(message) => return fail(scope, errors, &message, &c.span),
192    };
193    Some(Expr {
194        kind: ExprKind::Call {
195            callee,
196            args: args.into_iter().collect::<Option<_>>()?,
197        },
198        span: c.span.clone(),
199    })
200}
201
202/// The mapping `base` names, when it is a bare name that denotes no
203/// variable but a mapping.
204fn mapping_base(base: &ast::Expr, scope: &impl Scope) -> Option<MappingId> {
205    match &base.kind {
206        ast::ExprKind::Var(name) if scope.var(name).is_none() => scope.mapping(name),
207        _ => None,
208    }
209}
210
211/// Report `message` at `span`, prefixed with the scope's context; the
212/// expression does not resolve.
213pub(super) fn fail<T>(
214    scope: &impl Scope,
215    errors: &mut Vec<Diagnostic>,
216    message: &str,
217    span: &Range<usize>,
218) -> Option<T> {
219    errors.push(Diagnostic::at(
220        format!("{}{message}", scope.context()),
221        span.clone(),
222        scope.file(),
223    ));
224    None
225}