ilo 0.8.2

ilo — a programming language for AI agents
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
use serde::{Deserialize, Serialize};

pub mod source_map;
pub use source_map::SourceMap;

// ---- Span infrastructure ----

/// Byte range within source text.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Span {
    pub start: usize,
    pub end: usize,
}

impl Span {
    pub const UNKNOWN: Span = Span { start: 0, end: 0 };

    pub fn merge(self, other: Span) -> Span {
        Span {
            start: self.start.min(other.start),
            end: self.end.max(other.end),
        }
    }
}

/// Wraps a node with its source span. Transparent to serde (serializes as inner node only).
#[derive(Debug, Clone, PartialEq)]
pub struct Spanned<T> {
    pub node: T,
    pub span: Span,
}

#[allow(dead_code)] // used in tests and as codegen infrastructure
impl<T> Spanned<T> {
    pub fn new(node: T, span: Span) -> Self {
        Spanned { node, span }
    }

    pub fn unknown(node: T) -> Self {
        Spanned { node, span: Span::UNKNOWN }
    }
}

impl<T> std::ops::Deref for Spanned<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.node
    }
}

impl<T: Serialize> Serialize for Spanned<T> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.node.serialize(serializer)
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for Spanned<T> {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        T::deserialize(deserializer).map(|node| Spanned { node, span: Span::UNKNOWN })
    }
}

// ---- Core AST types ----

/// Types in idea9 — single-char base types, composable
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Type {
    Number,  // n
    Text,    // t
    Bool,    // b
    Nil,     // _
    Optional(Box<Type>),          // O type  — nullable (nil or the inner type)
    List(Box<Type>),              // L type
    Map(Box<Type>, Box<Type>),    // M key value  — dynamic key-value collection
    Result(Box<Type>, Box<Type>), // R ok err
    Sum(Vec<String>),             // S a b c  — closed set of named string variants
    Fn(Vec<Type>, Box<Type>),     // F param... return  (last type is return)
    Named(String),                // user-defined type name or type variable
}

/// A parameter: `name:type`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Param {
    pub name: String,
    pub ty: Type,
}

/// Top-level declarations
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Decl {
    /// `name params>return;body`
    Function {
        name: String,
        params: Vec<Param>,
        return_type: Type,
        body: Vec<Spanned<Stmt>>,
        #[serde(skip)]
        span: Span,
    },

    /// `type name{field:type;...}`
    TypeDef {
        name: String,
        fields: Vec<Param>,
        #[serde(skip)]
        span: Span,
    },

    /// `tool name"desc" params>return timeout:n,retry:n`
    Tool {
        name: String,
        description: String,
        params: Vec<Param>,
        return_type: Type,
        timeout: Option<f64>,
        retry: Option<f64>,
        #[serde(skip)]
        span: Span,
    },

    /// `alias name type` — type alias (pure sugar, resolved at verify time)
    Alias {
        name: String,
        target: Type,
        #[serde(skip)]
        span: Span,
    },

    /// `use "path/to/file.ilo"` — import all declarations from another file.
    /// `use "path/to/file.ilo" [name1 name2]` — import only named declarations.
    /// Resolved before verification; replaced by the imported declarations in
    /// the merged program. Stripped by the verifier/codegen as a safety net.
    Use {
        path: String,
        /// `None` = import all; `Some(names)` = import only those names.
        only: Option<Vec<String>>,
        #[serde(skip)]
        span: Span,
    },

    /// Poison node inserted during parser error recovery.
    /// Suppressed by the verifier; omitted from JSON AST output
    /// (filtered by the custom serializer on Program.declarations).
    Error {
        #[serde(skip)]
        span: Span,
    },
}

/// Statements
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Stmt {
    /// `name=expr`
    Let { name: String, value: Expr },

    /// `cond{body}` or `!cond{body}` — guard (early return)
    /// `cond{then}{else}` — ternary (value, no early return)
    Guard {
        condition: Expr,
        negated: bool,
        body: Vec<Spanned<Stmt>>,
        else_body: Option<Vec<Spanned<Stmt>>>,
    },

    /// `?expr{arms}` or `?{arms}`
    Match {
        subject: Option<Expr>,
        arms: Vec<MatchArm>,
    },

    /// `@binding collection{body}`
    ForEach {
        binding: String,
        collection: Expr,
        body: Vec<Spanned<Stmt>>,
    },

    /// `@binding start..end{body}` — range iteration
    ForRange {
        binding: String,
        start: Expr,
        end: Expr,
        body: Vec<Spanned<Stmt>>,
    },

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

    /// `ret expr` — early return from function
    Return(Expr),

    /// `brk` or `brk expr` — exit enclosing loop
    Break(Option<Expr>),

    /// `cnt` — skip to next iteration of enclosing loop
    Continue,

    /// `{a;b;c}=expr` — destructure record fields into local bindings
    Destructure {
        bindings: Vec<String>,
        value: Expr,
    },

    /// Expression as statement (last expr is return value)
    Expr(Expr),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MatchArm {
    pub pattern: Pattern,
    pub body: Vec<Spanned<Stmt>>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Pattern {
    /// `^e:` — binds error value
    Err(String),
    /// `~v:` — binds ok value
    Ok(String),
    /// Literal pattern: `"gold":`, `1000:`
    Literal(Literal),
    /// `_:` — wildcard / catch-all
    Wildcard,
    /// `n v:`, `t v:`, `b v:`, `l v:` — branch on runtime type, bind value
    TypeIs { ty: Type, binding: String },
}

/// Expressions
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Expr {
    Literal(Literal),

    /// Variable reference
    Ref(String),

    /// Field access: `obj.field` or safe `obj.?field`
    Field { object: Box<Expr>, field: String, safe: bool },

    /// Index access: `list.0`, `list.1` or safe `list.?0`
    Index { object: Box<Expr>, index: usize, safe: bool },

    /// Function call with positional args: `func arg1 arg2`
    /// When `unwrap` is true, `func! args` auto-unwraps Result:
    /// Ok(v) → v, Err(e) → propagate Err to enclosing function.
    Call {
        function: String,
        args: Vec<Expr>,
        #[serde(default)]
        unwrap: bool,
    },

    /// Prefix binary op: `+a b`, `*a b`
    BinOp {
        op: BinOp,
        left: Box<Expr>,
        right: Box<Expr>,
    },

    /// Unary negation: `!expr` (logical) or `-expr` (numeric)
    UnaryOp {
        op: UnaryOp,
        operand: Box<Expr>,
    },

    /// Ok constructor: `~expr`
    Ok(Box<Expr>),

    /// Err constructor: `^expr`
    Err(Box<Expr>),

    /// List literal
    List(Vec<Expr>),

    /// Record construction: `typename field:val field:val`
    Record {
        type_name: String,
        fields: Vec<(String, Expr)>,
    },

    /// Match expression: `?expr{arms}` or `?{arms}` used as value
    Match {
        subject: Option<Box<Expr>>,
        arms: Vec<MatchArm>,
    },

    /// Nil-coalesce: `a ?? b` — if a is nil, evaluate b
    NilCoalesce {
        value: Box<Expr>,
        default: Box<Expr>,
    },

    /// With expression: `obj with field:val`
    With {
        object: Box<Expr>,
        updates: Vec<(String, Expr)>,
    },
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Literal {
    Number(f64),
    Text(String),
    Bool(bool),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum BinOp {
    Add,
    Subtract,
    Multiply,
    Divide,
    Equals,
    NotEquals,
    GreaterThan,
    LessThan,
    GreaterOrEqual,
    LessOrEqual,
    And,
    Or,
    Append,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum UnaryOp {
    Not,
    Negate,
}

fn serialize_decls<S: serde::Serializer>(decls: &[Decl], s: S) -> Result<S::Ok, S::Error> {
    use serde::ser::SerializeSeq;
    let mut seq = s.serialize_seq(None)?;
    for d in decls.iter().filter(|d| !matches!(d, Decl::Error { .. } | Decl::Use { .. })) {
        seq.serialize_element(d)?;
    }
    seq.end()
}

/// A complete program is a list of declarations
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Program {
    #[serde(serialize_with = "serialize_decls")]
    pub declarations: Vec<Decl>,
    #[serde(skip)]
    pub source: Option<String>,
}

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

    #[test]
    fn span_unknown_is_zero() {
        assert_eq!(Span::UNKNOWN, Span { start: 0, end: 0 });
    }

    #[test]
    fn span_merge_takes_extremes() {
        let a = Span { start: 5, end: 10 };
        let b = Span { start: 2, end: 15 };
        let merged = a.merge(b);
        assert_eq!(merged, Span { start: 2, end: 15 });
    }

    #[test]
    fn span_merge_same() {
        let a = Span { start: 3, end: 7 };
        assert_eq!(a.merge(a), a);
    }

    #[test]
    fn span_merge_non_overlapping() {
        let a = Span { start: 0, end: 5 };
        let b = Span { start: 10, end: 20 };
        assert_eq!(a.merge(b), Span { start: 0, end: 20 });
    }

    #[test]
    fn span_default_is_zero() {
        let s = Span::default();
        assert_eq!(s, Span { start: 0, end: 0 });
    }

    #[test]
    fn spanned_deref() {
        let s = Spanned::new(42, Span { start: 0, end: 2 });
        assert_eq!(*s, 42);
    }

    #[test]
    fn spanned_unknown() {
        let s = Spanned::unknown("hello");
        assert_eq!(s.span, Span::UNKNOWN);
        assert_eq!(*s, "hello");
    }

    #[test]
    fn spanned_serialize_transparent() {
        let s = Spanned::new(42i32, Span { start: 5, end: 10 });
        let json = serde_json::to_string(&s).unwrap();
        assert_eq!(json, "42");
    }

    #[test]
    fn spanned_deserialize_transparent() {
        let s: Spanned<i32> = serde_json::from_str("42").unwrap();
        assert_eq!(s.node, 42);
        assert_eq!(s.span, Span::UNKNOWN);
    }

    #[test]
    fn spanned_serialize_complex() {
        let expr = Spanned::new(
            Expr::Literal(Literal::Number(3.14)),
            Span { start: 0, end: 4 },
        );
        let json = serde_json::to_string(&expr).unwrap();
        // Should serialize as the inner Expr, not as a wrapper
        assert!(json.contains("Number"));
        assert!(!json.contains("span"));
    }

    #[test]
    fn decl_span_not_serialized() {
        let decl = Decl::Function {
            name: "f".to_string(),
            params: vec![],
            return_type: Type::Number,
            body: vec![Spanned::unknown(Stmt::Expr(Expr::Literal(Literal::Number(1.0))))],
            span: Span { start: 0, end: 10 },
        };
        let json = serde_json::to_string(&decl).unwrap();
        assert!(!json.contains("span"));
    }

    #[test]
    fn program_source_not_serialized() {
        let prog = Program {
            declarations: vec![],
            source: Some("f x:n>n;x".to_string()),
        };
        let json = serde_json::to_string(&prog).unwrap();
        assert!(!json.contains("source"));
        assert!(!json.contains("f x:n>n;x"));
    }

    #[test]
    fn program_json_round_trip() {
        // Ensure existing JSON AST shape is preserved
        let prog = Program {
            declarations: vec![Decl::Function {
                name: "f".to_string(),
                params: vec![Param { name: "x".to_string(), ty: Type::Number }],
                return_type: Type::Number,
                body: vec![Spanned::unknown(Stmt::Expr(Expr::Ref("x".to_string())))],
                span: Span { start: 0, end: 13 },
            }],
            source: Some("f x:n>n;x".to_string()),
        };
        let json = serde_json::to_string_pretty(&prog).unwrap();
        let deserialized: Program = serde_json::from_str(&json).unwrap();
        // Source and spans are lost on deserialization (skipped), but structure matches
        assert_eq!(deserialized.declarations.len(), 1);
        assert!(deserialized.source.is_none());
    }
}