1use 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#[derive(Debug, Clone, Serialize)]
19pub struct Expr {
20 pub kind: ExprKind,
22 pub span: Range<usize>,
24}
25
26#[derive(Debug, Clone, Serialize)]
28pub enum ExprKind {
29 Lit(Lit),
31 Var(VarRef),
33 Vaddr(MappingId),
35 Paddr(MappingId),
38 Call {
40 callee: FfnId,
42 args: Vec<Expr>,
44 },
45 Sizeof(TypeRef),
47 Cast {
49 expr: Box<Expr>,
51 ty: TypeRef,
53 },
54 Unary {
56 op: UnaryOp,
58 operand: Box<Expr>,
60 },
61 Binary {
63 op: BinaryOp,
65 lhs: Box<Expr>,
67 rhs: Box<Expr>,
69 },
70 Field {
72 base: Box<Expr>,
74 name: String,
76 },
77}
78
79pub(super) trait Scope {
82 fn var(&self, name: &str) -> Option<VarRef>;
84 fn mapping(&self, name: &str) -> Option<MappingId>;
86 fn paddr_read(&self, _m: MappingId) {}
88 fn callee(&self, alias: &str, name: &str) -> Result<FfnId, String>;
90 fn type_ref(&self, ty: &Type) -> Result<TypeRef, String>;
92 fn undeclared(&self, name: &str) -> String {
94 format!("variable '{name}' is not declared")
95 }
96 fn file(&self) -> &str;
98 fn context(&self) -> &str;
100}
101
102pub(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 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
181pub(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
202fn 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
211pub(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}