1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Abstract Syntax Tree definitions for the Lambdust language.
//!
//! This module defines the AST nodes for all language constructs in Lambdust,
//! including the 10 special forms and derived forms implemented as macros.
#![allow(missing_docs)]
pub use crate::diagnostics::Spanned;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
pub mod literal;
pub mod visitor;
pub mod program;
pub mod formals;
pub mod binding;
pub mod parameter_binding;
pub mod cond_clause;
pub mod case_clause;
pub mod guard_clause;
pub mod case_lambda_clause;
pub use literal::*;
pub use visitor::*;
pub use program::*;
pub use formals::*;
pub use binding::*;
pub use parameter_binding::*;
pub use cond_clause::*;
pub use case_clause::*;
pub use guard_clause::*;
pub use case_lambda_clause::*;
/// The main expression type for Lambdust.
///
/// This enum represents all possible expressions in the language,
/// including the 10 special forms and literals.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Expr {
// ============= LITERALS =============
/// Literal values (numbers, strings, booleans, etc.)
Literal(Literal),
/// Identifiers and symbols
Identifier(String),
/// Symbols (for compatibility - alias for Identifier)
Symbol(String),
/// Keywords (#:key)
Keyword(String),
/// Generic list expression (for module syntax)
List(Vec<Spanned<Expr>>),
// ============= SPECIAL FORMS =============
/// Quote expression: (quote <datum>) or '<datum>
Quote(Box<Spanned<Expr>>),
/// Quasiquote expression: (quasiquote <datum>) or `<datum>
Quasiquote(Box<Spanned<Expr>>),
/// Unquote expression: (unquote <datum>) or ,<datum>
Unquote(Box<Spanned<Expr>>),
/// Unquote-splicing expression: (unquote-splicing <datum>) or ,@<datum>
UnquoteSplicing(Box<Spanned<Expr>>),
/// Lambda expression: (lambda <formals> <body>)
Lambda {
formals: Formals,
metadata: HashMap<String, Spanned<Expr>>,
body: Vec<Spanned<Expr>>,
},
/// Conditional: (if <test> <consequent> <alternative>)
If {
test: Box<Spanned<Expr>>,
consequent: Box<Spanned<Expr>>,
alternative: Option<Box<Spanned<Expr>>>,
},
/// Definition: (define <identifier> <expression>) or (define (<identifier> <formals>) <body>)
Define {
name: String,
value: Box<Spanned<Expr>>,
metadata: HashMap<String, Spanned<Expr>>,
},
/// Assignment: (set! <identifier> <expression>)
Set {
name: String,
value: Box<Spanned<Expr>>,
},
/// Macro definition: (define-syntax <identifier> <transformer>)
DefineSyntax {
name: String,
transformer: Box<Spanned<Expr>>,
},
/// Syntax rules: (syntax-rules (literals ...) (pattern template) ...)
SyntaxRules {
literals: Vec<String>,
rules: Vec<(Spanned<Expr>, Spanned<Expr>)>, // (pattern, template) pairs
},
/// Continuation capture: (call-with-current-continuation <procedure>)
CallCC(Box<Spanned<Expr>>),
/// Primitive operation: (primitive <symbol> <arguments>*)
Primitive {
name: String,
args: Vec<Spanned<Expr>>,
},
/// Type annotation: (:: <expression> <type>)
TypeAnnotation {
expr: Box<Spanned<Expr>>,
type_expr: Box<Spanned<Expr>>,
},
/// Parameter binding: (parameterize ((<parameter> <value>) ...) <body>)
Parameterize {
bindings: Vec<ParameterBinding>,
body: Vec<Spanned<Expr>>,
},
/// Module import: (import <import-spec>+)
Import {
import_specs: Vec<Spanned<Expr>>,
},
/// Library definition: (define-library <name> <library-declaration>*)
DefineLibrary {
name: Vec<String>, // Library name as a list, e.g., (srfi 41) becomes ["srfi", "41"]
imports: Vec<Spanned<Expr>>, // import declarations
exports: Vec<Spanned<Expr>>, // export declarations
body: Vec<Spanned<Expr>>, // includes, begin blocks, and other declarations
},
// ============= COMPOUND EXPRESSIONS =============
/// Function application: (<procedure> <arguments>*)
Application {
operator: Box<Spanned<Expr>>,
operands: Vec<Spanned<Expr>>,
},
/// Dotted pair (cons cell): (car . cdr)
Pair {
car: Box<Spanned<Expr>>,
cdr: Box<Spanned<Expr>>,
},
// ============= DERIVED FORMS (implemented as macros) =============
/// Begin expression: (begin <expressions>+)
Begin(Vec<Spanned<Expr>>),
/// Let binding: (let (<bindings>*) <body>)
Let {
bindings: Vec<Binding>,
body: Vec<Spanned<Expr>>,
},
/// Let* binding: (let* (<bindings>*) <body>)
LetStar {
bindings: Vec<Binding>,
body: Vec<Spanned<Expr>>,
},
/// Letrec binding: (letrec (<bindings>*) <body>)
LetRec {
bindings: Vec<Binding>,
body: Vec<Spanned<Expr>>,
},
/// Conditional with multiple clauses: (cond <clauses>+)
Cond(Vec<CondClause>),
/// Case expression: (case <expression> <clauses>+)
Case {
expr: Box<Spanned<Expr>>,
clauses: Vec<CaseClause>,
},
/// Logical AND: (and <expressions>*)
And(Vec<Spanned<Expr>>),
/// Logical OR: (or <expressions>*)
Or(Vec<Spanned<Expr>>),
/// When expression: (when <test> <expressions>+)
When {
test: Box<Spanned<Expr>>,
body: Vec<Spanned<Expr>>,
},
/// Unless expression: (unless <test> <expressions>+)
Unless {
test: Box<Spanned<Expr>>,
body: Vec<Spanned<Expr>>,
},
/// Guard expression: (guard (<variable> <clauses>*) <body>)
Guard {
variable: String,
clauses: Vec<GuardClause>,
body: Vec<Spanned<Expr>>,
},
/// Case-lambda expression: (case-lambda (<formals1> <body1>...) (<formals2> <body2>...) ...)
CaseLambda {
clauses: Vec<CaseLambdaClause>,
metadata: HashMap<String, Spanned<Expr>>,
},
}
impl Expr {
/// Returns true if this expression is a literal.
pub fn is_literal(&self) -> bool {
matches!(self, Expr::Literal(_))
}
/// Returns true if this expression is an identifier.
pub fn is_identifier(&self) -> bool {
matches!(self, Expr::Identifier(_) | Expr::Symbol(_))
}
/// Returns true if this expression is a special form.
pub fn is_special_form(&self) -> bool {
matches!(
self,
Expr::Quote(_)
| Expr::Quasiquote(_)
| Expr::Unquote(_)
| Expr::UnquoteSplicing(_)
| Expr::Lambda { .. }
| Expr::If { .. }
| Expr::Define { .. }
| Expr::Set { .. }
| Expr::DefineSyntax { .. }
| Expr::CallCC(_)
| Expr::Primitive { .. }
| Expr::TypeAnnotation { .. }
| Expr::Parameterize { .. }
| Expr::Import { .. }
| Expr::DefineLibrary { .. }
| Expr::CaseLambda { .. }
)
}
/// Returns true if this expression is self-evaluating.
pub fn is_self_evaluating(&self) -> bool {
matches!(self, Expr::Literal(_) | Expr::Keyword(_))
}
/// Gets the identifier name if this is an identifier expression.
pub fn as_identifier(&self) -> Option<&str> {
match self {
Expr::Identifier(name) | Expr::Symbol(name) => Some(name),
_ => None,
}
}
/// Gets the literal value if this is a literal expression.
pub fn as_literal(&self) -> Option<&Literal> {
match self {
Expr::Literal(lit) => Some(lit),
_ => None,
}
}
}
impl fmt::Display for Expr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Expr::Literal(lit) => write!(f, "{lit}"),
Expr::Identifier(name) => write!(f, "{name}"),
Expr::Symbol(name) => write!(f, "{name}"),
Expr::Keyword(name) => write!(f, "#{name}"),
Expr::List(elements) => {
write!(f, "(")?;
for (i, element) in elements.iter().enumerate() {
if i > 0 { write!(f, " ")?; }
write!(f, "{}", element.inner)?;
}
write!(f, ")")
}
Expr::Quote(expr) => write!(f, "'{}", expr.inner),
Expr::Quasiquote(expr) => write!(f, "`{}", expr.inner),
Expr::Unquote(expr) => write!(f, ",{}", expr.inner),
Expr::UnquoteSplicing(expr) => write!(f, ",@{}", expr.inner),
Expr::Lambda { formals, body, .. } => {
write!(f, "(lambda {formals} ")?;
for (i, expr) in body.iter().enumerate() {
if i > 0 { write!(f, " ")?; }
write!(f, "{}", expr.inner)?;
}
write!(f, ")")
}
Expr::If { test, consequent, alternative } => {
write!(f, "(if {} {}", test.inner, consequent.inner)?;
if let Some(alt) = alternative {
write!(f, " {}", alt.inner)?;
}
write!(f, ")")
}
Expr::Define { name, value, .. } => {
write!(f, "(define {} {})", name, value.inner)
}
Expr::Set { name, value } => {
write!(f, "(set! {} {})", name, value.inner)
}
Expr::Application { operator, operands } => {
write!(f, "({}", operator.inner)?;
for operand in operands {
write!(f, " {}", operand.inner)?;
}
write!(f, ")")
}
Expr::Pair { car, cdr } => {
write!(f, "({} . {})", car.inner, cdr.inner)
}
Expr::CaseLambda { clauses, .. } => {
write!(f, "(case-lambda")?;
for clause in clauses {
write!(f, " ({} ", clause.formals)?;
for (i, expr) in clause.body.iter().enumerate() {
if i > 0 { write!(f, " ")?; }
write!(f, "{}", expr.inner)?;
}
write!(f, ")")?;
}
write!(f, ")")
}
Expr::Import { import_specs } => {
write!(f, "(import")?;
for spec in import_specs {
write!(f, " {}", spec.inner)?;
}
write!(f, ")")
}
Expr::DefineLibrary { name, imports, exports, body } => {
write!(f, "(define-library ({}) ", name.join(" "))?;
for import in imports {
write!(f, " {}", import.inner)?;
}
for export in exports {
write!(f, " {}", export.inner)?;
}
for expr in body {
write!(f, " {}", expr.inner)?;
}
write!(f, ")")
}
// Add more display implementations as needed
_ => write!(f, "<{self:?}>"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::diagnostics::Span;
#[test]
fn test_expr_type_checks() {
let literal = Expr::Literal(Literal::Number(42.0));
let identifier = Expr::Identifier("x".to_string());
let keyword = Expr::Keyword("type".to_string());
assert!(literal.is_literal());
assert!(!literal.is_identifier());
assert!(literal.is_self_evaluating());
assert!(!identifier.is_literal());
assert!(identifier.is_identifier());
assert!(!identifier.is_self_evaluating());
assert!(!keyword.is_literal());
assert!(!keyword.is_identifier());
assert!(keyword.is_self_evaluating());
}
#[test]
fn test_program_creation() {
let mut program = Program::new();
assert!(program.is_empty());
let span = Span::new(0, 1);
let expr = Spanned::new(Expr::Identifier("x".to_string()), span);
program.add_expression(expr);
assert!(!program.is_empty());
assert_eq!(program.expressions.len(), 1);
}
#[test]
fn test_formals_display() {
let fixed = Formals::Fixed(vec!["x".to_string(), "y".to_string()]);
assert_eq!(format!("{fixed}"), "(x y)");
let variable = Formals::Variable("args".to_string());
assert_eq!(format!("{variable}"), "args");
let mixed = Formals::Mixed {
fixed: vec!["x".to_string()],
rest: "rest".to_string(),
};
assert_eq!(format!("{mixed}"), "(x . rest)");
}
}