keleusma 0.1.1

Total Functional Stream Processor with definitive WCET and WCMU verification, targeting no_std + alloc embedded scripting
Documentation
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
extern crate alloc;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;

use crate::token::Span;

/// A complete Keleusma program.
#[derive(Debug, Clone, PartialEq)]
pub struct Program {
    pub uses: Vec<UseDecl>,
    pub types: Vec<TypeDef>,
    pub data_decls: Vec<DataDecl>,
    pub functions: Vec<FunctionDef>,
    pub traits: Vec<TraitDef>,
    pub impls: Vec<ImplBlock>,
    pub span: Span,
}

/// A trait declaration.
///
/// Traits declare a set of method signatures that an implementing
/// type provides. The body of a trait method declaration is the
/// signature only; concrete implementations are supplied by `impl`
/// blocks. Bounded type parameters in function signatures restrict
/// the parameter to types that implement the named trait.
#[derive(Debug, Clone, PartialEq)]
pub struct TraitDef {
    pub name: String,
    pub type_params: Vec<TypeParam>,
    pub methods: Vec<TraitMethodSig>,
    pub span: Span,
}

/// A method signature inside a trait declaration.
///
/// The signature mirrors a function declaration without a body. The
/// implicit `self` parameter is the first parameter when present and
/// has type `Self` (the implementing type).
#[derive(Debug, Clone, PartialEq)]
pub struct TraitMethodSig {
    pub name: String,
    pub params: Vec<Param>,
    pub return_type: TypeExpr,
    pub span: Span,
}

/// A trait implementation for a concrete type.
///
/// `impl Trait for Type { method definitions }`. The methods supply
/// the concrete bodies for the trait's declared signatures. The
/// implementation registers a method-resolution table entry keyed on
/// the (Trait, Type, method) triple at compile time.
#[derive(Debug, Clone, PartialEq)]
pub struct ImplBlock {
    pub trait_name: String,
    /// Type parameters introduced by the impl block itself, allowing
    /// `impl Trait for Box<T>` style declarations. Empty for
    /// concrete-type impls.
    pub type_params: Vec<TypeParam>,
    /// The implementing type expression. For nominal types this is
    /// typically `TypeExpr::Named(Type, args)`.
    pub for_type: TypeExpr,
    pub methods: Vec<FunctionDef>,
    pub span: Span,
}

/// A `data` block declaration for persistent mutable state.
///
/// Data blocks define named contexts whose fields persist across RESET
/// boundaries. The host initializes the data slots before execution.
/// Script code reads and writes fields via `name.field` syntax.
#[derive(Debug, Clone, PartialEq)]
pub struct DataDecl {
    pub name: String,
    pub fields: Vec<DataFieldDecl>,
    pub span: Span,
}

/// A field in a data block declaration.
#[derive(Debug, Clone, PartialEq)]
pub struct DataFieldDecl {
    pub name: String,
    pub type_expr: TypeExpr,
    pub span: Span,
}

/// A `use` import declaration.
#[derive(Debug, Clone, PartialEq)]
pub struct UseDecl {
    pub path: Vec<String>,
    pub import: ImportItem,
    pub span: Span,
}

/// What is imported by a `use` declaration.
#[derive(Debug, Clone, PartialEq)]
pub enum ImportItem {
    /// A specific name: `use audio::set_frequency`.
    Name(String),
    /// A wildcard: `use audio::*`.
    Wildcard,
}

/// A type definition (struct or enum).
#[derive(Debug, Clone, PartialEq)]
pub enum TypeDef {
    Struct(StructDef),
    Enum(EnumDef),
}

/// A struct definition.
///
/// Generic structs declare type parameters in `<T, U>` form between
/// the struct name and the field block. Field type expressions may
/// reference these parameters. Construction at use sites instantiates
/// the parameters with fresh per-construction type variables in the
/// same way generic functions do.
#[derive(Debug, Clone, PartialEq)]
pub struct StructDef {
    pub name: String,
    pub type_params: Vec<TypeParam>,
    pub fields: Vec<FieldDecl>,
    pub span: Span,
}

/// A field in a struct definition.
#[derive(Debug, Clone, PartialEq)]
pub struct FieldDecl {
    pub name: String,
    pub type_expr: TypeExpr,
    pub span: Span,
}

/// An enum definition.
///
/// Generic enums declare type parameters in `<T, U>` form between the
/// enum name and the variant block. Variant payload type expressions
/// may reference these parameters. Variant construction at use sites
/// instantiates the parameters with fresh per-construction type
/// variables.
#[derive(Debug, Clone, PartialEq)]
pub struct EnumDef {
    pub name: String,
    pub type_params: Vec<TypeParam>,
    pub variants: Vec<VariantDecl>,
    pub span: Span,
}

/// A variant in an enum definition.
#[derive(Debug, Clone, PartialEq)]
pub struct VariantDecl {
    pub name: String,
    pub fields: Vec<TypeExpr>,
    pub span: Span,
}

/// Function category keyword.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FunctionCategory {
    /// Atomic total function (`fn`).
    Fn,
    /// Non-atomic total function (`yield`).
    Yield,
    /// Productive divergent function (`loop`).
    Loop,
}

/// A function definition.
#[derive(Debug, Clone, PartialEq)]
pub struct FunctionDef {
    pub category: FunctionCategory,
    pub name: String,
    /// Generic type parameters declared in `<T, U>` form between the
    /// function name and the parameter list. Empty vector for
    /// non-generic functions. The order is significant for
    /// monomorphization: each call site instantiates these in order.
    pub type_params: Vec<TypeParam>,
    pub params: Vec<Param>,
    pub return_type: TypeExpr,
    pub guard: Option<Box<Expr>>,
    pub body: Block,
    pub span: Span,
}

/// A generic type parameter declared in a signature.
///
/// Carries the parameter's name, optional trait bounds, and source
/// location. A bound restricts the parameter to types implementing
/// the named trait. Multiple bounds can be specified using `+`
/// syntax: `<T: Trait1 + Trait2>`. The empty bounds vector represents
/// an unconstrained parameter.
#[derive(Debug, Clone, PartialEq)]
pub struct TypeParam {
    pub name: String,
    pub bounds: Vec<String>,
    pub span: Span,
}

/// A function parameter.
#[derive(Debug, Clone, PartialEq)]
pub struct Param {
    pub pattern: Pattern,
    pub type_expr: Option<TypeExpr>,
    pub span: Span,
}

/// A block of statements with an optional trailing expression.
#[derive(Debug, Clone, PartialEq)]
pub struct Block {
    pub stmts: Vec<Stmt>,
    pub tail_expr: Option<Box<Expr>>,
    pub span: Span,
}

/// A statement.
#[derive(Debug, Clone, PartialEq)]
pub enum Stmt {
    Let(LetStmt),
    For(ForStmt),
    Break(Span),
    /// Assignment to a data block field: `data_name.field = expr;`.
    DataFieldAssign {
        data_name: String,
        field: String,
        value: Expr,
        span: Span,
    },
    Expr(Expr),
}

/// A `let` binding.
#[derive(Debug, Clone, PartialEq)]
pub struct LetStmt {
    pub pattern: Pattern,
    pub type_expr: Option<TypeExpr>,
    pub value: Expr,
    pub span: Span,
}

/// A `for` loop.
#[derive(Debug, Clone, PartialEq)]
pub struct ForStmt {
    pub var: String,
    pub iterable: Iterable,
    pub body: Block,
    pub span: Span,
}

/// The iterable in a `for` loop.
#[derive(Debug, Clone, PartialEq)]
pub enum Iterable {
    /// A plain expression (e.g., an array).
    Expr(Expr),
    /// A range expression (e.g., `0..8`).
    Range(Box<Expr>, Box<Expr>),
}

/// An expression.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    /// Literal value.
    Literal { value: Literal, span: Span },
    /// Variable or qualified name reference.
    Ident { name: String, span: Span },
    /// Binary operation.
    BinOp {
        op: BinOp,
        left: Box<Expr>,
        right: Box<Expr>,
        span: Span,
    },
    /// Unary operation (`not`, `-`).
    UnaryOp {
        op: UnaryOp,
        operand: Box<Expr>,
        span: Span,
    },
    /// Function call.
    Call {
        name: String,
        args: Vec<Expr>,
        span: Span,
    },
    /// Pipeline expression: `left |> func(args)`.
    Pipeline {
        left: Box<Expr>,
        func: String,
        args: Vec<Expr>,
        span: Span,
    },
    /// Yield expression.
    Yield { value: Box<Expr>, span: Span },
    /// If/else expression.
    If {
        condition: Box<Expr>,
        then_block: Block,
        else_block: Option<Block>,
        span: Span,
    },
    /// Match expression.
    Match {
        scrutinee: Box<Expr>,
        arms: Vec<MatchArm>,
        span: Span,
    },
    /// Loop expression.
    Loop { body: Block, span: Span },
    /// Field access: `expr.field`.
    FieldAccess {
        object: Box<Expr>,
        field: String,
        span: Span,
    },
    /// Method call: `expr.method(args)`. Resolved at compile time to
    /// the impl-defined function for the receiver's type. Generic
    /// receivers are resolved through monomorphization.
    MethodCall {
        receiver: Box<Expr>,
        method: String,
        args: Vec<Expr>,
        span: Span,
    },
    /// Tuple index: `expr.0`.
    TupleIndex {
        object: Box<Expr>,
        index: u64,
        span: Span,
    },
    /// Array index: `expr[index]`.
    ArrayIndex {
        object: Box<Expr>,
        index: Box<Expr>,
        span: Span,
    },
    /// Struct initialization: `Name { field: value }`.
    StructInit {
        name: String,
        fields: Vec<FieldInit>,
        span: Span,
    },
    /// Enum variant: `Enum::Variant(args)`.
    EnumVariant {
        enum_name: String,
        variant: String,
        args: Vec<Expr>,
        span: Span,
    },
    /// Array literal: `[a, b, c]`.
    ArrayLiteral { elements: Vec<Expr>, span: Span },
    /// Tuple literal: `(a, b, c)`.
    TupleLiteral { elements: Vec<Expr>, span: Span },
    /// Type cast: `expr as Type`.
    Cast {
        expr: Box<Expr>,
        target: TypeExpr,
        span: Span,
    },
    /// Pipeline placeholder `_`.
    Placeholder { span: Span },
    /// Closure literal: `|args| body` or `|args| -> ret { body }`.
    /// The return type and body are optional in surface syntax: a
    /// bare expression body is wrapped into a single-tail-expression
    /// block automatically by the parser.
    Closure {
        params: Vec<Param>,
        return_type: Option<TypeExpr>,
        body: Block,
        span: Span,
    },
    /// Hoisted closure reference produced by the closure-hoisting
    /// pass. Carries the synthetic function's name and the names of
    /// outer-scope locals that the closure captures. The compiler
    /// emits `GetLocal` for each captured name followed by
    /// `Op::MakeClosure(chunk_idx, n_captures)`. User-written code
    /// never produces this variant directly.
    ///
    /// When `recursive` is `true`, the closure was produced by a
    /// `let f = |...| ... f(...) ...` form whose let-binding name
    /// appears in the body. The hoist pass synthesizes the chunk
    /// with the binding name as an additional implicit parameter
    /// after the captures, and the compiler emits
    /// `Op::MakeRecursiveClosure` instead of `Op::MakeClosure`. At
    /// invocation, the runtime pushes the closure value itself into
    /// the self parameter slot before the explicit arguments.
    ClosureRef {
        name: String,
        captures: Vec<String>,
        recursive: bool,
        span: Span,
    },
}

impl Expr {
    /// Return the span of this expression.
    pub fn span(&self) -> Span {
        match self {
            Expr::Literal { span, .. }
            | Expr::Ident { span, .. }
            | Expr::BinOp { span, .. }
            | Expr::UnaryOp { span, .. }
            | Expr::Call { span, .. }
            | Expr::Pipeline { span, .. }
            | Expr::Yield { span, .. }
            | Expr::If { span, .. }
            | Expr::Match { span, .. }
            | Expr::Loop { span, .. }
            | Expr::FieldAccess { span, .. }
            | Expr::MethodCall { span, .. }
            | Expr::TupleIndex { span, .. }
            | Expr::ArrayIndex { span, .. }
            | Expr::StructInit { span, .. }
            | Expr::EnumVariant { span, .. }
            | Expr::ArrayLiteral { span, .. }
            | Expr::TupleLiteral { span, .. }
            | Expr::Cast { span, .. }
            | Expr::Placeholder { span }
            | Expr::Closure { span, .. }
            | Expr::ClosureRef { span, .. } => *span,
        }
    }
}

/// A literal value.
#[derive(Debug, Clone, PartialEq)]
pub enum Literal {
    Int(i64),
    Float(f64),
    String(String),
    Bool(bool),
    /// The unit literal `()`.
    Unit,
}

/// Binary operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Eq,
    NotEq,
    Lt,
    Gt,
    LtEq,
    GtEq,
    And,
    Or,
}

/// Unary operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOp {
    Neg,
    Not,
}

/// A match arm: `pattern => expression`.
#[derive(Debug, Clone, PartialEq)]
pub struct MatchArm {
    pub pattern: Pattern,
    pub expr: Expr,
    pub span: Span,
}

/// A field initializer in a struct expression.
#[derive(Debug, Clone, PartialEq)]
pub struct FieldInit {
    pub name: String,
    pub value: Expr,
    pub span: Span,
}

/// A type expression.
#[derive(Debug, Clone, PartialEq)]
pub enum TypeExpr {
    /// Primitive type (`i64`, `f64`, `bool`, `String`).
    Prim(PrimType, Span),
    /// Named type (struct, enum, or opaque) with optional generic
    /// arguments. The `Vec<TypeExpr>` is empty for non-generic
    /// references.
    Named(String, Vec<TypeExpr>, Span),
    /// Tuple type: `(T, U)`.
    Tuple(Vec<TypeExpr>, Span),
    /// Array type: `[T; N]`.
    Array(Box<TypeExpr>, i64, Span),
    /// Option type: `Option<T>`.
    Option(Box<TypeExpr>, Span),
    /// Unit type: `()`.
    Unit(Span),
}

impl TypeExpr {
    pub fn span(&self) -> Span {
        match self {
            TypeExpr::Prim(_, span)
            | TypeExpr::Named(_, _, span)
            | TypeExpr::Tuple(_, span)
            | TypeExpr::Array(_, _, span)
            | TypeExpr::Option(_, span)
            | TypeExpr::Unit(span) => *span,
        }
    }
}

/// Primitive type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrimType {
    I64,
    F64,
    Bool,
    KString,
}

/// A pattern for matching.
#[derive(Debug, Clone, PartialEq)]
pub enum Pattern {
    /// Literal pattern: `42`, `"hello"`, `true`.
    Literal(Literal, Span),
    /// Enum variant pattern: `Enum::Variant(p1, p2)`.
    Enum(String, String, Vec<Pattern>, Span),
    /// Struct destructuring: `Name { field, field2: pat }`.
    Struct(String, Vec<FieldPattern>, Span),
    /// Tuple pattern: `(a, b)`.
    Tuple(Vec<Pattern>, Span),
    /// Wildcard: `_`.
    Wildcard(Span),
    /// Variable binding.
    Variable(String, Span),
}

impl Pattern {
    pub fn span(&self) -> Span {
        match self {
            Pattern::Literal(_, span)
            | Pattern::Enum(_, _, _, span)
            | Pattern::Struct(_, _, span)
            | Pattern::Tuple(_, span)
            | Pattern::Wildcard(span)
            | Pattern::Variable(_, span) => *span,
        }
    }
}

/// A field pattern in struct destructuring.
#[derive(Debug, Clone, PartialEq)]
pub struct FieldPattern {
    pub name: String,
    pub pattern: Option<Pattern>,
    pub span: Span,
}

/// Merge two spans into one covering both.
pub fn merge_spans(start: Span, end: Span) -> Span {
    Span {
        start: start.start,
        end: end.end,
        line: start.line,
        column: start.column,
    }
}