1use core::fmt;
2
3use num_rational::Ratio;
4
5pub type Fraction = Ratio<i64>;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum Number {
12 Index(i64),
13 Scalar(Fraction),
14}
15
16impl Number {
17 #[must_use]
19 pub fn value(self) -> Fraction {
20 match self {
21 Self::Index(n) => Fraction::from_integer(n),
22 Self::Scalar(f) => f,
23 }
24 }
25}
26
27impl fmt::Display for Number {
29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30 match self {
31 Self::Index(n) => write!(f, "{n}"),
32 Self::Scalar(s) => write!(f, "{}/{}", s.numer(), s.denom()),
33 }
34 }
35}
36
37pub use crate::ast_pair::{PairElement, StructId};
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
46pub enum EntityKind {
47 Account,
48 Commodity,
49 Transaction,
50 Split,
51 Tag,
52 Price,
53 SshKey,
54 Condition,
59}
60
61impl EntityKind {
62 pub const ALL: [EntityKind; 8] = [
66 Self::Account,
67 Self::Commodity,
68 Self::Transaction,
69 Self::Split,
70 Self::Tag,
71 Self::Price,
72 Self::SshKey,
73 Self::Condition,
74 ];
75
76 #[must_use]
78 pub fn wire_code(self) -> i64 {
79 Self::ALL
80 .iter()
81 .position(|kind| *kind == self)
82 .map_or(i64::MAX, |index| index as i64)
83 }
84
85 #[must_use]
87 pub fn from_wire_code(code: i64) -> Option<Self> {
88 usize::try_from(code)
89 .ok()
90 .and_then(|index| Self::ALL.get(index).copied())
91 }
92
93 #[must_use]
97 pub fn type_name(self) -> &'static str {
98 match self {
99 Self::Account => "account",
100 Self::Commodity => "commodity_entity",
101 Self::Transaction => "transaction",
102 Self::Split => "split",
103 Self::Tag => "tag_entity",
104 Self::Price => "price",
105 Self::SshKey => "ssh_key",
106 Self::Condition => "nomi_condition",
107 }
108 }
109}
110
111impl fmt::Display for EntityKind {
112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113 write!(f, "{}", self.type_name())
114 }
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
125pub struct ClosureSigId(pub u32);
126
127impl fmt::Display for ClosureSigId {
128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129 write!(f, "{}", self.0)
130 }
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
134pub enum WasmType {
135 I32,
136 Bool,
145 Ratio,
146 StringRef,
147 SymbolRef,
149 Commodity,
154 PairRef(PairElement),
160 AnyRef,
166 EntityRef(EntityKind),
173 StructRef(StructId),
177 Closure(ClosureSigId),
183}
184
185impl fmt::Display for WasmType {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 match self {
188 Self::I32 => write!(f, "i32"),
189 Self::Bool => write!(f, "bool"),
190 Self::Ratio => write!(f, "ratio"),
191 Self::StringRef => write!(f, "string"),
192 Self::SymbolRef => write!(f, "symbol"),
193 Self::Commodity => write!(f, "commodity"),
194 Self::PairRef(elem) => write!(f, "pair<{elem}>"),
195 Self::EntityRef(kind) => write!(f, "entity<{kind}>"),
196 Self::StructRef(id) => write!(f, "{id}"),
197 Self::Closure(sig) => write!(f, "closure<{sig}>"),
198 Self::AnyRef => write!(f, "any"),
199 }
200 }
201}
202
203#[derive(Debug, Clone, PartialEq)]
204pub struct LambdaParams {
205 pub required: Vec<String>,
206 pub optional: Vec<(String, Option<Expr>)>,
207 pub rest: Option<String>,
208 pub key: Vec<KeyParam>,
209 pub aux: Vec<(String, Option<Expr>)>,
210}
211
212#[derive(Debug, Clone, PartialEq)]
215pub struct KeyParam {
216 pub name: String,
217 pub keyword: String,
218 pub default: Option<Expr>,
219}
220
221impl KeyParam {
222 #[must_use]
224 pub fn new(name: impl Into<String>, default: Option<Expr>) -> Self {
225 let name = name.into();
226 Self {
227 keyword: name.to_uppercase(),
228 name,
229 default,
230 }
231 }
232}
233
234impl LambdaParams {
235 #[must_use]
237 pub fn keyword_of(&self, var: &str) -> String {
238 self.key
239 .iter()
240 .find_map(|param| (param.name == var).then(|| param.keyword.clone()))
241 .unwrap_or_else(|| var.to_uppercase())
242 }
243
244 pub fn defaulted(&self) -> impl Iterator<Item = (&str, Option<&Expr>)> {
246 let optional = self.optional.iter().map(|(name, default)| (name, default));
247 let key = self.key.iter().map(|param| (¶m.name, ¶m.default));
248 let aux = self.aux.iter().map(|(name, default)| (name, default));
249 optional
250 .chain(key)
251 .chain(aux)
252 .map(|(name, default)| (name.as_str(), default.as_ref()))
253 }
254
255 pub fn defaults(&self) -> impl Iterator<Item = &Expr> {
257 self.defaulted().filter_map(|(_, default)| default)
258 }
259
260 pub fn defaults_mut(&mut self) -> impl Iterator<Item = &mut Expr> {
262 let optional = self.optional.iter_mut().map(|(_, default)| default);
263 let key = self.key.iter_mut().map(|param| &mut param.default);
264 let aux = self.aux.iter_mut().map(|(_, default)| default);
265 optional
266 .chain(key)
267 .chain(aux)
268 .filter_map(|default| default.as_mut())
269 }
270}
271
272impl LambdaParams {
273 pub fn simple(params: Vec<String>) -> Self {
274 Self {
275 required: params,
276 optional: Vec::new(),
277 rest: None,
278 key: Vec::new(),
279 aux: Vec::new(),
280 }
281 }
282}
283
284#[derive(Debug, Clone, PartialEq)]
285pub enum Expr {
286 Nil,
287 T,
288 Number(Number),
289 String(String),
290 Symbol(String),
291 Keyword(String),
292 Bytes(Vec<u8>),
293 Cons(Box<Expr>, Box<Expr>),
294 List(Vec<Expr>),
295 Quote(Box<Expr>),
296 Datum(Box<Expr>),
298 Quasiquote(Box<Expr>),
299 Unquote(Box<Expr>),
300 UnquoteSplicing(Box<Expr>),
301 Lambda(LambdaParams, Box<Expr>),
302 RuntimeValue(crate::runtime::Value),
303 WasmRuntime(WasmType),
304 WasmLocal(u32, WasmType),
306 WasmGlobal(u32, WasmType),
308 Instance(u32, StructId),
311}
312
313#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
316pub enum Place {
317 Local(u32),
318 Global(u32),
319}
320
321impl Expr {
322 #[must_use]
323 pub fn cons(car: Expr, cdr: Expr) -> Self {
324 Expr::Cons(Box::new(car), Box::new(cdr))
325 }
326
327 #[must_use]
328 pub fn symbol(name: &str) -> Self {
329 Expr::Symbol(name.to_string())
330 }
331
332 #[must_use]
334 pub fn body(forms: &[Expr]) -> Self {
335 match forms {
336 [form] => form.clone(),
337 _ => Expr::List(
338 std::iter::once(Expr::symbol("PROGN"))
339 .chain(forms.iter().cloned())
340 .collect(),
341 ),
342 }
343 }
344
345 #[must_use]
347 pub fn wasm_type(&self) -> Option<WasmType> {
348 match self {
349 Self::WasmRuntime(ty) | Self::WasmLocal(_, ty) | Self::WasmGlobal(_, ty) => Some(*ty),
350 Self::Instance(_, id) => Some(WasmType::StructRef(*id)),
351 Self::RuntimeValue(crate::runtime::Value::Commodity { .. }) => {
352 Some(WasmType::Commodity)
353 }
354 _ => None,
355 }
356 }
357
358 #[must_use]
360 pub fn is_wasm_runtime(&self) -> bool {
361 matches!(
362 self,
363 Self::WasmRuntime(_)
364 | Self::WasmLocal(_, _)
365 | Self::WasmGlobal(_, _)
366 | Self::Instance(_, _)
367 )
368 }
369
370 #[must_use]
373 pub fn is_runtime_variable(&self) -> bool {
374 matches!(
375 self,
376 Self::WasmRuntime(_) | Self::WasmLocal(_, _) | Self::WasmGlobal(_, _)
377 )
378 }
379
380 pub fn any_form(&self, test: impl Fn(&Expr) -> bool) -> bool {
383 let mut pending = vec![self];
384 while let Some(form) = pending.pop() {
385 if test(form) {
386 return true;
387 }
388 match form {
389 Self::List(items) => pending.extend(items),
390 Self::Cons(car, cdr) => pending.extend([car.as_ref(), cdr.as_ref()]),
391 Self::Quote(inner)
392 | Self::Datum(inner)
393 | Self::Quasiquote(inner)
394 | Self::Unquote(inner)
395 | Self::UnquoteSplicing(inner) => pending.push(inner),
396 Self::Lambda(params, body) => {
397 pending.push(body);
398 pending.extend(params.defaults());
399 }
400 _ => {}
401 }
402 }
403 false
404 }
405
406 #[must_use]
409 pub fn place(&self) -> Option<(Place, WasmType)> {
410 match self {
411 Self::WasmLocal(idx, ty) => Some((Place::Local(*idx), *ty)),
412 Self::WasmGlobal(idx, ty) => Some((Place::Global(*idx), *ty)),
413 _ => None,
414 }
415 }
416
417 #[must_use]
419 pub fn is_function_value(&self) -> bool {
420 matches!(self, Self::Lambda(..)) || matches!(self.place(), Some((_, WasmType::Closure(_))))
421 }
422}
423
424#[derive(Debug, Clone, PartialEq)]
425pub struct Annotation {
426 pub name: String,
427 pub value: Expr,
428}
429
430impl Expr {
431 #[must_use]
433 pub fn is_nil(&self) -> bool {
434 matches!(self, Expr::Nil)
435 }
436
437 #[must_use]
438 pub fn is_atom(&self) -> bool {
439 !matches!(self, Expr::List(_) | Expr::Cons(_, _))
440 }
441
442 #[must_use]
443 pub fn as_symbol(&self) -> Option<&str> {
444 match self {
445 Expr::Symbol(s) => Some(s),
446 _ => None,
447 }
448 }
449
450 #[must_use]
452 pub fn as_list(&self) -> Option<&[Expr]> {
453 match self {
454 Expr::List(l) => Some(l),
455 Expr::Nil => Some(&[]),
456 _ => None,
457 }
458 }
459
460 #[must_use]
466 pub fn symbol_parts(&self) -> Option<(Option<&str>, &str)> {
467 let name = self.as_symbol()?;
468 Some(match name.split_once(':') {
469 Some((ns, base)) => (Some(ns), base),
470 None => (None, name),
471 })
472 }
473}
474
475#[must_use]
479pub fn canonical_symbol(namespace: Option<&str>, name: &str) -> String {
480 match namespace {
481 Some(ns) => format!("{ns}:{name}"),
482 None => name.to_string(),
483 }
484}
485
486#[derive(Debug, Clone, Default)]
487pub struct Program {
488 pub exprs: Vec<Expr>,
489 pub annotations: Vec<Annotation>,
490}
491
492impl Program {
493 #[must_use]
494 pub fn new(exprs: Vec<Expr>) -> Self {
495 Self {
496 exprs,
497 annotations: Vec::new(),
498 }
499 }
500
501 #[must_use]
502 pub fn with_annotations(exprs: Vec<Expr>, annotations: Vec<Annotation>) -> Self {
503 Self { exprs, annotations }
504 }
505}
506
507#[cfg(test)]
508#[path = "ast_tests.rs"]
509mod tests;