tl-ast 0.3.2

Abstract Syntax Tree definitions for ThinkingLanguage
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
// ThinkingLanguage — Abstract Syntax Tree
// Licensed under MIT OR Apache-2.0
//
// Defines the tree structure produced by the parser.
// Phase 0 subset: let bindings, functions, if/else, match/case,
// pipe operator, basic types, print.

use tl_errors::Span;

/// A complete TL program is a list of statements
#[derive(Debug, Clone)]
pub struct Program {
    pub statements: Vec<Stmt>,
    /// Module-level documentation from `//!` comments at the top of the file
    pub module_doc: Option<String>,
}

/// A statement with source location information.
#[derive(Debug, Clone)]
pub struct Stmt {
    pub kind: StmtKind,
    pub span: Span,
    /// Documentation comment attached to this statement (from `///` comments)
    pub doc_comment: Option<String>,
}

/// A use-import target
#[derive(Debug, Clone)]
pub enum UseItem {
    /// `use data.transforms.clean_users`
    Single(Vec<String>),
    /// `use data.transforms.{clean_users, CleanedUser}`
    Group(Vec<String>, Vec<String>),
    /// `use data.transforms.*`
    Wildcard(Vec<String>),
    /// `use data.connectors.postgres as pg`
    Aliased(Vec<String>, String),
}

/// A trait bound on a type parameter: `T: Comparable + Hashable`
#[derive(Debug, Clone)]
pub struct TraitBound {
    pub type_param: String,
    pub traits: Vec<String>,
}

/// A method signature within a trait definition
#[derive(Debug, Clone)]
pub struct TraitMethod {
    pub name: String,
    pub params: Vec<Param>,
    pub return_type: Option<TypeExpr>,
}

/// Statement variants
#[derive(Debug, Clone)]
pub enum StmtKind {
    /// `let x = expr` or `let mut x: type = expr`
    Let {
        name: String,
        mutable: bool,
        type_ann: Option<TypeExpr>,
        value: Expr,
        is_public: bool,
    },

    /// `fn name<T, U>(params) -> return_type where T: Bound { body }`
    FnDecl {
        name: String,
        type_params: Vec<String>,
        params: Vec<Param>,
        return_type: Option<TypeExpr>,
        bounds: Vec<TraitBound>,
        body: Vec<Stmt>,
        is_generator: bool,
        is_public: bool,
        is_async: bool,
    },

    /// Expression statement (e.g., a function call on its own line)
    Expr(Expr),

    /// `return expr`
    Return(Option<Expr>),

    /// `if cond { body } else if cond { body } else { body }`
    If {
        condition: Expr,
        then_body: Vec<Stmt>,
        else_ifs: Vec<(Expr, Vec<Stmt>)>,
        else_body: Option<Vec<Stmt>>,
    },

    /// `while cond { body }`
    While { condition: Expr, body: Vec<Stmt> },

    /// `for name in iter { body }`
    For {
        name: String,
        iter: Expr,
        body: Vec<Stmt>,
    },

    /// `parallel for name in iter { body }`
    ParallelFor {
        name: String,
        iter: Expr,
        body: Vec<Stmt>,
    },

    /// `schema Name { field: type, ... }`
    Schema {
        name: String,
        fields: Vec<SchemaField>,
        is_public: bool,
        /// Schema version from `@version N` doc comment annotation
        version: Option<i64>,
        /// Parent version this schema evolves from
        parent_version: Option<i64>,
    },

    /// `migrate SchemaName from V1 to V2 { add_column(...), ... }`
    Migrate {
        schema_name: String,
        from_version: i64,
        to_version: i64,
        operations: Vec<MigrateOp>,
    },

    /// `model name = train algorithm { key: value, ... }`
    Train {
        name: String,
        algorithm: String,
        config: Vec<(String, Expr)>,
    },

    /// `pipeline name { extract { ... } transform { ... } load { ... } }`
    Pipeline {
        name: String,
        extract: Vec<Stmt>,
        transform: Vec<Stmt>,
        load: Vec<Stmt>,
        schedule: Option<String>,
        timeout: Option<String>,
        retries: Option<i64>,
        on_failure: Option<Vec<Stmt>>,
        on_success: Option<Vec<Stmt>>,
    },

    /// `stream name { source: expr, window: spec, transform: { ... }, sink: expr }`
    StreamDecl {
        name: String,
        source: Expr,
        transform: Vec<Stmt>,
        sink: Option<Expr>,
        window: Option<WindowSpec>,
        watermark: Option<String>,
    },

    /// `source name = connector TYPE { key: value, ... }`
    SourceDecl {
        name: String,
        connector_type: String,
        config: Vec<(String, Expr)>,
    },

    /// `sink name = connector TYPE { key: value, ... }`
    SinkDecl {
        name: String,
        connector_type: String,
        config: Vec<(String, Expr)>,
    },

    /// `struct Name<T, U> { field: type, ... }`
    StructDecl {
        name: String,
        type_params: Vec<String>,
        fields: Vec<SchemaField>,
        is_public: bool,
    },

    /// `enum Name<T, E> { Variant, Variant(types), ... }`
    EnumDecl {
        name: String,
        type_params: Vec<String>,
        variants: Vec<EnumVariant>,
        is_public: bool,
    },

    /// `impl<T> Type { fn methods... }`
    ImplBlock {
        type_name: String,
        type_params: Vec<String>,
        methods: Vec<Stmt>,
    },

    /// `try { ... } catch e { ... } finally { ... }`
    TryCatch {
        try_body: Vec<Stmt>,
        catch_var: String,
        catch_body: Vec<Stmt>,
        finally_body: Option<Vec<Stmt>>,
    },

    /// `throw expr`
    Throw(Expr),

    /// `import "path.tl"` or `import "path.tl" as name`
    Import { path: String, alias: Option<String> },

    /// `test "name" { ... }`
    Test { name: String, body: Vec<Stmt> },

    /// `use data.transforms.clean_users` etc.
    Use { item: UseItem, is_public: bool },

    /// `mod transforms` or `pub mod transforms`
    ModDecl { name: String, is_public: bool },

    /// `trait Display<T> { fn show(self) -> string }`
    TraitDef {
        name: String,
        type_params: Vec<String>,
        methods: Vec<TraitMethod>,
        is_public: bool,
    },

    /// `impl Display for Point { fn show(self) -> string { ... } }`
    TraitImpl {
        trait_name: String,
        type_name: String,
        type_params: Vec<String>,
        methods: Vec<Stmt>,
    },

    /// `let { x, y } = expr` or `let [a, b] = expr`
    LetDestructure {
        pattern: Pattern,
        mutable: bool,
        value: Expr,
        is_public: bool,
    },

    /// `type Mapper = fn(int64) -> int64`
    TypeAlias {
        name: String,
        type_params: Vec<String>,
        value: TypeExpr,
        is_public: bool,
    },

    /// `agent name { model: "...", system: "...", tools { ... }, max_turns: N, on_tool_call { ... }, on_complete { ... } }`
    Agent {
        name: String,
        model: String,
        system_prompt: Option<String>,
        tools: Vec<(String, Expr)>,
        max_turns: Option<i64>,
        temperature: Option<f64>,
        max_tokens: Option<i64>,
        base_url: Option<String>,
        api_key: Option<String>,
        output_format: Option<String>,
        on_tool_call: Option<Vec<Stmt>>,
        on_complete: Option<Vec<Stmt>>,
        /// MCP server clients to use as additional tool providers
        mcp_servers: Vec<Expr>,
    },

    /// `break`
    Break,

    /// `continue`
    Continue,
}

/// Enum variant definition
#[derive(Debug, Clone)]
pub struct EnumVariant {
    pub name: String,
    pub fields: Vec<TypeExpr>,
}

/// Window specification for stream processing
#[derive(Debug, Clone)]
pub enum WindowSpec {
    /// `tumbling(duration)` — fixed-size, non-overlapping windows
    Tumbling(String),
    /// `sliding(window_size, slide_interval)` — overlapping windows
    Sliding(String, String),
    /// `session(gap_duration)` — session windows based on activity gap
    Session(String),
}

/// A pattern for match arms and let-destructuring.
/// Identifiers in pattern position are bindings (create new variables),
/// not value references. Use literals, enum variants, or guards for comparison.
#[derive(Debug, Clone)]
pub enum Pattern {
    /// `_` — matches anything, binds nothing
    Wildcard,
    /// Literal value: 1, "hi", true, none
    Literal(Expr),
    /// Binding: `x` — matches anything, binds to name
    Binding(String),
    /// Enum variant: `Color::Red(r, g, b)` or `None`
    Enum {
        type_name: String,
        variant: String,
        args: Vec<Pattern>,
    },
    /// Struct pattern: `Point { x, y }` or `{ x, y }`
    Struct {
        name: Option<String>,
        fields: Vec<StructPatternField>,
    },
    /// List pattern: `[a, b, ...rest]`
    List {
        elements: Vec<Pattern>,
        rest: Option<String>,
    },
    /// OR pattern: `A | B | C`
    Or(Vec<Pattern>),
}

/// A field in a struct destructuring pattern.
#[derive(Debug, Clone)]
pub struct StructPatternField {
    pub name: String,
    /// None = shorthand `{ x }` means `{ x: x }`
    pub pattern: Option<Pattern>,
}

/// A match arm: `pattern [if guard] => body`
#[derive(Debug, Clone)]
pub struct MatchArm {
    pub pattern: Pattern,
    pub guard: Option<Expr>,
    pub body: Expr,
}

/// Schema migration operation
#[derive(Debug, Clone)]
pub enum MigrateOp {
    /// `add_column(name: type, default: expr)`
    AddColumn {
        name: String,
        type_ann: TypeExpr,
        default: Option<Expr>,
    },
    /// `drop_column(name)`
    DropColumn { name: String },
    /// `rename_column(old_name, new_name)`
    RenameColumn { from: String, to: String },
    /// `alter_type(column, new_type)`
    AlterType { column: String, new_type: TypeExpr },
    /// `add_constraint(column, constraint_name)`
    AddConstraint { column: String, constraint: String },
    /// `drop_constraint(column, constraint_name)`
    DropConstraint { column: String, constraint: String },
}

/// Closure body: either a single expression or a block with statements.
#[derive(Debug, Clone)]
pub enum ClosureBody {
    /// `(x) => x * 2`
    Expr(Box<Expr>),
    /// `(x) -> int64 { let y = x * 2; y + 1 }`
    Block {
        stmts: Vec<Stmt>,
        expr: Option<Box<Expr>>,
    },
}

/// Expressions
#[derive(Debug, Clone)]
pub enum Expr {
    // ── Literals ──
    Int(i64),
    Float(f64),
    String(String),
    Bool(bool),
    None,
    /// Decimal literal: `3.14d` — fixed-point decimal
    Decimal(String),

    /// Variable reference
    Ident(String),

    /// Binary operation: left op right
    BinOp {
        left: Box<Expr>,
        op: BinOp,
        right: Box<Expr>,
    },

    /// Unary operation: op expr
    UnaryOp {
        op: UnaryOp,
        expr: Box<Expr>,
    },

    /// Function call: name(args)
    Call {
        function: Box<Expr>,
        args: Vec<Expr>,
    },

    /// Named argument in a call: key: value
    NamedArg {
        name: String,
        value: Box<Expr>,
    },

    /// Pipe: left |> right
    Pipe {
        left: Box<Expr>,
        right: Box<Expr>,
    },

    /// Member access: expr.field
    Member {
        object: Box<Expr>,
        field: String,
    },

    /// Index access: expr[index]
    Index {
        object: Box<Expr>,
        index: Box<Expr>,
    },

    /// List literal: [a, b, c]
    List(Vec<Expr>),

    /// Map literal: { key: value, ... }
    Map(Vec<(Expr, Expr)>),

    /// Block expression: { stmts; expr }
    Block {
        stmts: Vec<Stmt>,
        expr: Option<Box<Expr>>,
    },

    /// case { pattern => expr, ... }
    Case {
        arms: Vec<MatchArm>,
    },

    /// match expr { pattern => expr, ... }
    Match {
        subject: Box<Expr>,
        arms: Vec<MatchArm>,
    },

    /// Closure: (params) => expr  or  (params) -> Type { stmts; expr }
    Closure {
        params: Vec<Param>,
        return_type: Option<TypeExpr>,
        body: ClosureBody,
    },

    /// Range: start..end
    Range {
        start: Box<Expr>,
        end: Box<Expr>,
    },

    /// Null coalesce: expr ?? default
    NullCoalesce {
        expr: Box<Expr>,
        default: Box<Expr>,
    },

    /// Assignment: name = value (for reassigning mut variables)
    Assign {
        target: Box<Expr>,
        value: Box<Expr>,
    },

    /// Struct initialization: Name { field: value, ... }
    StructInit {
        name: String,
        fields: Vec<(String, Expr)>,
    },

    /// Enum variant: Enum::Variant or Enum::Variant(args)
    EnumVariant {
        enum_name: String,
        variant: String,
        args: Vec<Expr>,
    },

    /// Await expression: `await expr`
    Await(Box<Expr>),

    /// Yield expression: `yield expr` or bare `yield`
    Yield(Option<Box<Expr>>),

    /// Try propagation: `expr?` — unwrap Result/Option or early return
    Try(Box<Expr>),
}

/// Binary operators
#[derive(Debug, Clone, PartialEq)]
pub enum BinOp {
    // Arithmetic
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Pow,
    // Comparison
    Eq,
    Neq,
    Lt,
    Gt,
    Lte,
    Gte,
    // Logical
    And,
    Or,
}

impl std::fmt::Display for BinOp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BinOp::Add => write!(f, "+"),
            BinOp::Sub => write!(f, "-"),
            BinOp::Mul => write!(f, "*"),
            BinOp::Div => write!(f, "/"),
            BinOp::Mod => write!(f, "%"),
            BinOp::Pow => write!(f, "**"),
            BinOp::Eq => write!(f, "=="),
            BinOp::Neq => write!(f, "!="),
            BinOp::Lt => write!(f, "<"),
            BinOp::Gt => write!(f, ">"),
            BinOp::Lte => write!(f, "<="),
            BinOp::Gte => write!(f, ">="),
            BinOp::And => write!(f, "and"),
            BinOp::Or => write!(f, "or"),
        }
    }
}

/// Unary operators
#[derive(Debug, Clone, PartialEq)]
pub enum UnaryOp {
    Neg,
    Not,
    /// `&expr` — read-only reference
    Ref,
}

/// Function parameter
#[derive(Debug, Clone)]
pub struct Param {
    pub name: String,
    pub type_ann: Option<TypeExpr>,
}

/// Annotation on schema/struct fields
#[derive(Debug, Clone, PartialEq)]
pub enum Annotation {
    Sensitive,
    Redact,
    Pii,
    Custom(String),
}

/// Schema field definition
#[derive(Debug, Clone)]
pub struct SchemaField {
    pub name: String,
    pub type_ann: TypeExpr,
    /// Field-level doc comment (may contain @since, @deprecated annotations)
    pub doc_comment: Option<String>,
    /// Default value for added fields (used in migrations)
    pub default_value: Option<Expr>,
    /// Security annotations (@sensitive, @redact, @pii)
    pub annotations: Vec<Annotation>,
}

/// Type expressions (Phase 0: basic types only)
#[derive(Debug, Clone)]
pub enum TypeExpr {
    /// Named type: int64, string, bool, float64, User
    Named(String),
    /// Generic type: table<User>, list<int64>
    Generic { name: String, args: Vec<TypeExpr> },
    /// Optional type: T?
    Optional(Box<TypeExpr>),
    /// Function type: fn(int64, int64) -> int64
    Function {
        params: Vec<TypeExpr>,
        return_type: Box<TypeExpr>,
    },
}