specl-syntax 0.1.0

Lexer, parser, and AST for the Specl specification language
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
//! Abstract Syntax Tree for the Specl specification language.

use crate::token::Span;

/// A Specl module (top-level compilation unit).
#[derive(Debug, Clone)]
pub struct Module {
    /// Module name.
    pub name: Ident,
    /// Module declarations.
    pub decls: Vec<Decl>,
    /// Span covering the entire module.
    pub span: Span,
}

/// An identifier with its source span.
#[derive(Debug, Clone)]
pub struct Ident {
    /// The identifier name.
    pub name: String,
    /// Source span.
    pub span: Span,
}

impl Ident {
    pub fn new(name: impl Into<String>, span: Span) -> Self {
        Self {
            name: name.into(),
            span,
        }
    }
}

/// A top-level declaration.
#[derive(Debug, Clone)]
pub enum Decl {
    /// `use ModuleName`
    Use(UseDecl),
    /// `const NAME: Type`
    Const(ConstDecl),
    /// `var NAME: Type`
    Var(VarDecl),
    /// `type NAME = Type`
    Type(TypeDecl),
    /// `func NAME(params) { expr }`
    Func(FuncDecl),
    /// `init { ... }`
    Init(InitDecl),
    /// `action NAME(...) { ... }`
    Action(ActionDecl),
    /// `invariant NAME { ... }`
    Invariant(InvariantDecl),
    /// `property NAME { ... }`
    Property(PropertyDecl),
    /// `fairness { ... }`
    Fairness(FairnessDecl),
}

impl Decl {
    pub fn span(&self) -> Span {
        match self {
            Decl::Use(d) => d.span,
            Decl::Const(d) => d.span,
            Decl::Var(d) => d.span,
            Decl::Type(d) => d.span,
            Decl::Func(d) => d.span,
            Decl::Init(d) => d.span,
            Decl::Action(d) => d.span,
            Decl::Invariant(d) => d.span,
            Decl::Property(d) => d.span,
            Decl::Fairness(d) => d.span,
        }
    }
}

/// `use ModuleName`
#[derive(Debug, Clone)]
pub struct UseDecl {
    pub module: Ident,
    pub span: Span,
}

/// The value of a constant declaration.
#[derive(Debug, Clone)]
pub enum ConstValue {
    /// Type constraint: `const X: 0..10` - value provided at runtime via --constant
    Type(TypeExpr),
    /// Scalar value: `const X: 3` - fixed value
    Scalar(i64),
}

/// `const NAME: Type` or `const NAME: value`
#[derive(Debug, Clone)]
pub struct ConstDecl {
    pub name: Ident,
    pub value: ConstValue,
    pub span: Span,
}

/// `var NAME: Type`
#[derive(Debug, Clone)]
pub struct VarDecl {
    pub name: Ident,
    pub ty: TypeExpr,
    pub span: Span,
}

/// `type NAME = Type`
#[derive(Debug, Clone)]
pub struct TypeDecl {
    pub name: Ident,
    pub ty: TypeExpr,
    pub span: Span,
}

/// `func NAME(params) { body }`
/// User-defined helper function for reuse (like TLA+ operator definitions).
/// Functions are pure and are inlined at call sites during compilation.
#[derive(Debug, Clone)]
pub struct FuncDecl {
    pub name: Ident,
    pub params: Vec<FuncParam>,
    pub body: Expr,
    pub span: Span,
}

/// A function parameter (untyped - types are inferred).
#[derive(Debug, Clone)]
pub struct FuncParam {
    pub name: Ident,
    pub span: Span,
}

/// `init { expr }`
#[derive(Debug, Clone)]
pub struct InitDecl {
    pub body: Expr,
    pub span: Span,
}

/// `action NAME(params) { body }`
#[derive(Debug, Clone)]
pub struct ActionDecl {
    pub name: Ident,
    pub params: Vec<Param>,
    pub body: ActionBody,
    pub span: Span,
}

/// Action body with requires and effects.
#[derive(Debug, Clone)]
pub struct ActionBody {
    /// Guard conditions (`require expr`).
    pub requires: Vec<Expr>,
    /// Effect expression (state transition relation).
    pub effect: Option<Expr>,
    pub span: Span,
}

/// A parameter declaration.
#[derive(Debug, Clone)]
pub struct Param {
    pub name: Ident,
    pub ty: TypeExpr,
    pub span: Span,
}

/// `invariant NAME { expr }`
#[derive(Debug, Clone)]
pub struct InvariantDecl {
    pub name: Ident,
    pub body: Expr,
    pub span: Span,
}

/// `property NAME { expr }`
#[derive(Debug, Clone)]
pub struct PropertyDecl {
    pub name: Ident,
    pub body: Expr,
    pub span: Span,
}

/// `fairness { constraints }`
#[derive(Debug, Clone)]
pub struct FairnessDecl {
    pub constraints: Vec<FairnessConstraint>,
    pub span: Span,
}

/// A fairness constraint.
#[derive(Debug, Clone)]
pub struct FairnessConstraint {
    pub kind: FairnessKind,
    pub action: Ident,
    pub span: Span,
}

/// Kind of fairness constraint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FairnessKind {
    Weak,
    Strong,
}

/// A type expression.
#[derive(Debug, Clone)]
pub enum TypeExpr {
    /// Named type (e.g., `Nat`, `AccountId`).
    Named(Ident),
    /// Set type `Set[T]`.
    Set(Box<TypeExpr>, Span),
    /// Sequence type `Seq[T]`.
    Seq(Box<TypeExpr>, Span),
    /// Dict type `dict[K, V]`.
    Dict(Box<TypeExpr>, Box<TypeExpr>, Span),
    /// Option type `Option[T]`.
    Option(Box<TypeExpr>, Span),
    /// Range type `lo..hi`.
    Range(Box<Expr>, Box<Expr>, Span),
    /// Tuple type `(T1, T2, ...)`.
    Tuple(Vec<TypeExpr>, Span),
}

impl TypeExpr {
    pub fn span(&self) -> Span {
        match self {
            TypeExpr::Named(id) => id.span,
            TypeExpr::Set(_, span) => *span,
            TypeExpr::Seq(_, span) => *span,
            TypeExpr::Dict(_, _, span) => *span,
            TypeExpr::Option(_, span) => *span,
            TypeExpr::Range(_, _, span) => *span,
            TypeExpr::Tuple(_, span) => *span,
        }
    }
}

/// An expression.
#[derive(Debug, Clone)]
pub struct Expr {
    pub kind: ExprKind,
    pub span: Span,
}

impl Expr {
    pub fn new(kind: ExprKind, span: Span) -> Self {
        Self { kind, span }
    }
}

/// The kind of expression.
#[derive(Debug, Clone)]
pub enum ExprKind {
    /// Boolean literal.
    Bool(bool),
    /// Integer literal.
    Int(i64),
    /// String literal.
    String(String),
    /// Identifier.
    Ident(String),
    /// Primed identifier (next-state variable).
    Primed(String),

    /// Binary operation.
    Binary {
        op: BinOp,
        left: Box<Expr>,
        right: Box<Expr>,
    },
    /// Unary operation.
    Unary { op: UnaryOp, operand: Box<Expr> },

    /// Function/set/sequence indexing `e[i]`.
    Index { base: Box<Expr>, index: Box<Expr> },
    /// Sequence slicing `e[lo..hi]`.
    Slice {
        base: Box<Expr>,
        lo: Box<Expr>,
        hi: Box<Expr>,
    },
    /// Field access `e.field`.
    Field { base: Box<Expr>, field: Ident },
    /// Function call `f(args)`.
    Call { func: Box<Expr>, args: Vec<Expr> },

    /// Set literal `{ a, b, c }` or empty `{}`.
    SetLit(Vec<Expr>),
    /// Sequence literal `[a, b, c]` or empty `[]`.
    SeqLit(Vec<Expr>),
    /// Tuple literal `(a, b, c)`.
    TupleLit(Vec<Expr>),
    /// Dict literal `{ key: value, ... }` where keys are expressions.
    DictLit(Vec<(Expr, Expr)>),
    /// Function literal `fn(x in S) => e`.
    FnLit {
        var: Ident,
        domain: Box<Expr>,
        body: Box<Expr>,
    },

    /// Set comprehension `{ e for x in S }` or `{ x in S if P }` or `{ e for x in S if P }`.
    SetComprehension {
        element: Box<Expr>,
        var: Ident,
        domain: Box<Expr>,
        filter: Option<Box<Expr>>,
    },

    /// Record update `e with { field: value, ... }`.
    RecordUpdate {
        base: Box<Expr>,
        updates: Vec<RecordFieldUpdate>,
    },

    /// Quantifier `forall x in S: P` or `exists x in S: P`.
    Quantifier {
        kind: QuantifierKind,
        bindings: Vec<Binding>,
        body: Box<Expr>,
    },
    /// Choose `choose x in S: P`.
    Choose {
        var: Ident,
        domain: Box<Expr>,
        predicate: Box<Expr>,
    },
    /// Fix `fix x: P` - picks an arbitrary value satisfying P (used for CHOOSE without domain).
    Fix { var: Ident, predicate: Box<Expr> },

    /// Let binding `let x = e1 in e2`.
    Let {
        var: Ident,
        value: Box<Expr>,
        body: Box<Expr>,
    },
    /// Conditional `if c then t else f`.
    If {
        cond: Box<Expr>,
        then_branch: Box<Expr>,
        else_branch: Box<Expr>,
    },

    /// Require statement (in action body).
    Require(Box<Expr>),
    /// Changes operator (explicit nondeterminism).
    Changes(Ident),
    /// Enabled predicate `enabled(Action)`.
    Enabled(Ident),

    /// Sequence head `head(seq)` - get first element.
    SeqHead(Box<Expr>),
    /// Sequence tail `tail(seq)` - get all but first element.
    SeqTail(Box<Expr>),
    /// Length `len(x)` - get length of sequence, set, or function.
    Len(Box<Expr>),
    /// Function keys `keys(f)` - get domain of function as set.
    Keys(Box<Expr>),
    /// Function values `values(f)` - get range of function as set.
    Values(Box<Expr>),
    /// Distributed union `union_all(S)` - union of all sets in S.
    BigUnion(Box<Expr>),
    /// Powerset `powerset(S)` - set of all subsets of S.
    Powerset(Box<Expr>),

    /// Temporal: `always P`.
    Always(Box<Expr>),
    /// Temporal: `eventually P`.
    Eventually(Box<Expr>),
    /// Temporal: `P leads_to Q`.
    LeadsTo { left: Box<Expr>, right: Box<Expr> },

    /// Range expression `lo..hi` (as value, not type).
    Range { lo: Box<Expr>, hi: Box<Expr> },

    /// Parenthesized expression (for preserving source).
    Paren(Box<Expr>),
}

/// A record field update.
#[derive(Debug, Clone)]
pub enum RecordFieldUpdate {
    /// Simple field update `field: value`.
    Field { name: Ident, value: Expr },
    /// Dynamic key update `[key]: value`.
    Dynamic { key: Expr, value: Expr },
}

/// Binary operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
    // Logical
    And,
    Or,
    Implies,
    Iff,

    // Comparison
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,

    // Arithmetic
    Add,
    Sub,
    Mul,
    Div,
    Mod,

    // Set
    In,
    NotIn,
    Union,
    Intersect,
    Diff,
    SubsetOf,

    // Sequence
    Concat,
}

impl BinOp {
    /// Get the precedence of this operator (higher = binds tighter).
    pub fn precedence(self) -> u8 {
        match self {
            BinOp::Iff => 1,
            BinOp::Implies => 2,
            BinOp::Or => 3,
            BinOp::And => 4,
            BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => 5,
            BinOp::In | BinOp::NotIn | BinOp::SubsetOf => 5,
            BinOp::Union | BinOp::Diff | BinOp::Concat => 6,
            BinOp::Add | BinOp::Sub => 6,
            BinOp::Intersect => 7,
            BinOp::Mul | BinOp::Div | BinOp::Mod => 7,
        }
    }

    /// Check if this operator is right-associative.
    pub fn is_right_assoc(self) -> bool {
        matches!(self, BinOp::Implies | BinOp::Iff)
    }
}

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

/// Quantifier kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuantifierKind {
    Forall,
    Exists,
}

/// A variable binding `x in S`.
#[derive(Debug, Clone)]
pub struct Binding {
    pub var: Ident,
    pub domain: Expr,
    pub span: Span,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_binop_precedence() {
        // Multiplication binds tighter than addition
        assert!(BinOp::Mul.precedence() > BinOp::Add.precedence());
        // Addition binds tighter than comparison
        assert!(BinOp::Add.precedence() > BinOp::Eq.precedence());
        // Comparison binds tighter than and
        assert!(BinOp::Eq.precedence() > BinOp::And.precedence());
        // And binds tighter than or
        assert!(BinOp::And.precedence() > BinOp::Or.precedence());
        // Or binds tighter than implies
        assert!(BinOp::Or.precedence() > BinOp::Implies.precedence());
    }
}