aver-lang 0.8.2

Interpreter and transpiler for Aver, a statically-typed language designed for AI-assisted development
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
use super::*;

impl Interpreter {
    #[allow(dead_code)]
    pub(super) fn call_builtin(
        &mut self,
        name: &str,
        args: &[Value],
    ) -> Result<Value, RuntimeError> {
        let is_effectful = !Self::builtin_effects(name).is_empty();
        if is_effectful {
            return self.execute_effect(name, args);
        }
        self.dispatch_builtin(name, args)
    }

    pub(super) fn execute_effect(
        &mut self,
        effect_type: &str,
        args: &[Value],
    ) -> Result<Value, RuntimeError> {
        match self.execution_mode() {
            ExecutionMode::Normal => self.dispatch_builtin(effect_type, args),
            ExecutionMode::Record => {
                let args_json = values_to_json_lossy(args);
                let result = self.dispatch_builtin(effect_type, args);
                let outcome = match &result {
                    Ok(value) => RecordedOutcome::Value(
                        value_to_json(value).map_err(RuntimeError::ReplaySerialization)?,
                    ),
                    Err(err) => RecordedOutcome::RuntimeError(err.to_string()),
                };
                let caller = self
                    .call_stack
                    .last()
                    .map(|f| f.name.as_str())
                    .unwrap_or("");
                self.replay_state.record_effect(
                    effect_type,
                    args_json,
                    outcome,
                    caller,
                    self.last_call_line,
                );
                // Autosave snapshots on every recorded effect so long-running
                // processes (like HttpServer) still persist replay data.
                self.persist_recording_snapshot(RecordedOutcome::Value(JsonValue::Null))?;
                result
            }
            ExecutionMode::Replay => {
                let record = self
                    .replay_state
                    .replay_effect(effect_type, Some(values_to_json_lossy(args)))
                    .map_err(|err| match err {
                        crate::replay::ReplayFailure::Exhausted {
                            effect_type,
                            position,
                        } => RuntimeError::ReplayExhausted {
                            effect_type,
                            position,
                        },
                        crate::replay::ReplayFailure::Mismatch { seq, expected, got } => {
                            RuntimeError::ReplayMismatch { seq, expected, got }
                        }
                        crate::replay::ReplayFailure::ArgsMismatch {
                            seq,
                            effect_type,
                            expected,
                            got,
                        } => RuntimeError::ReplayArgsMismatch {
                            seq,
                            effect_type,
                            expected,
                            got,
                        },
                        crate::replay::ReplayFailure::Unconsumed { remaining } => {
                            RuntimeError::ReplayUnconsumed { remaining }
                        }
                    })?;
                match record {
                    RecordedOutcome::Value(value_json) => crate::replay::json_to_value(&value_json)
                        .map_err(RuntimeError::ReplaySerialization),
                    RecordedOutcome::RuntimeError(msg) => Err(RuntimeError::Error(msg)),
                }
            }
        }
    }

    pub(super) fn dispatch_builtin(
        &mut self,
        name: &str,
        args: &[Value],
    ) -> Result<Value, RuntimeError> {
        // Runtime policy check for Http/Disk/Env calls
        if matches!(Self::builtin_namespace(name), Some("Http" | "Disk" | "Env")) {
            self.check_runtime_policy(name, args)?;
        }
        match name {
            "__ctor:Result.Ok" => {
                if args.len() != 1 {
                    return Err(RuntimeError::Error(format!(
                        "Result.Ok() takes 1 argument, got {}",
                        args.len()
                    )));
                }
                Ok(Value::Ok(Box::new(args[0].clone())))
            }
            "__ctor:Result.Err" => {
                if args.len() != 1 {
                    return Err(RuntimeError::Error(format!(
                        "Result.Err() takes 1 argument, got {}",
                        args.len()
                    )));
                }
                Ok(Value::Err(Box::new(args[0].clone())))
            }
            "__ctor:Option.Some" => {
                if args.len() != 1 {
                    return Err(RuntimeError::Error(format!(
                        "Option.Some() takes 1 argument, got {}",
                        args.len()
                    )));
                }
                Ok(Value::Some(Box::new(args[0].clone())))
            }
            name if name.starts_with("__ctor:") => {
                // Format: __ctor:TypeName:VariantName
                let parts: Vec<&str> = name.splitn(3, ':').collect();
                let type_name = parts.get(1).copied().unwrap_or("").to_string();
                let variant = parts.get(2).copied().unwrap_or("").to_string();
                Ok(Value::Variant {
                    type_name,
                    variant,
                    fields: args.to_vec().into(),
                })
            }

            "Disk.makeDir" => {
                let [path_val] = args else {
                    return Err(RuntimeError::Error(format!(
                        "Disk.makeDir() takes 1 argument (path), got {}",
                        args.len()
                    )));
                };
                let Value::Str(path) = path_val else {
                    return Err(RuntimeError::Error(
                        "Disk.makeDir: path must be a String".to_string(),
                    ));
                };
                match std::fs::create_dir_all(path) {
                    Ok(_) => Ok(Value::Ok(Box::new(Value::Unit))),
                    Err(e) => Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
                }
            }

            _ => {
                let skip_server = matches!(self.execution_mode(), ExecutionMode::Record);
                match Self::builtin_namespace(name) {
                    Some("HttpServer") => http_server::call_with_runtime(
                        name,
                        args,
                        |handler, callback_args, callback_entry| {
                            let callback_effects = Self::callable_declared_effects(&handler);
                            self.call_value_with_effects_pub(
                                handler,
                                callback_args,
                                &callback_entry,
                                callback_effects,
                            )
                        },
                        skip_server,
                    )
                    .unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Args") => args::call(name, args, &self.cli_args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Console") => console::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Http") => http::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Disk") => disk::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Env") => env::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Random") => random::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Tcp") => tcp::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    #[cfg(feature = "terminal")]
                    Some("Terminal") => terminal::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Time") => time::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Bool") => bool::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Int") => int::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Float") => float::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("String") => string::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("List") => list::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Map") => map::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Vector") => vector::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Char") => char::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Byte") => byte::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Result") => result::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    Some("Option") => option::call(name, args).unwrap_or_else(|| {
                        Err(RuntimeError::Error(format!(
                            "Unknown builtin function: '{}'",
                            name
                        )))
                    }),
                    _ => Err(RuntimeError::Error(format!(
                        "Unknown builtin function: '{}'",
                        name
                    ))),
                }
            }
        }
    }

    // ─── NanValue-native builtin dispatch ───────────────────────────────────

    /// NanValue-native builtin call — avoids Value↔NanValue conversion.
    pub(super) fn call_builtin_nv(
        &mut self,
        name: &str,
        nv_args: &[NanValue],
    ) -> Result<NanValue, RuntimeError> {
        let is_effectful = !Self::builtin_effects(name).is_empty();
        if is_effectful {
            return self.execute_effect_nv(name, nv_args);
        }
        self.dispatch_builtin_nv(name, nv_args)
    }

    fn execute_effect_nv(
        &mut self,
        effect_type: &str,
        nv_args: &[NanValue],
    ) -> Result<NanValue, RuntimeError> {
        match self.execution_mode() {
            ExecutionMode::Normal => self.dispatch_builtin_nv(effect_type, nv_args),
            ExecutionMode::Record | ExecutionMode::Replay => {
                // For record/replay, fall back to Value-based path (JSON serialization needs Value)
                let args: Vec<Value> = nv_args.iter().map(|nv| nv.to_value(&self.arena)).collect();
                let result = self.execute_effect(effect_type, &args)?;
                Ok(NanValue::from_value(&result, &mut self.arena))
            }
        }
    }

    fn dispatch_builtin_nv(
        &mut self,
        name: &str,
        args: &[NanValue],
    ) -> Result<NanValue, RuntimeError> {
        // Runtime policy check — needs Value for Http/Disk/Env
        if matches!(Self::builtin_namespace(name), Some("Http" | "Disk" | "Env")) {
            let old_args: Vec<Value> = args.iter().map(|nv| nv.to_value(&self.arena)).collect();
            self.check_runtime_policy(name, &old_args)?;
        }

        match name {
            "__ctor:Result.Ok" => {
                if args.len() != 1 {
                    return Err(RuntimeError::Error(format!(
                        "Result.Ok() takes 1 argument, got {}",
                        args.len()
                    )));
                }
                Ok(NanValue::new_ok_value(args[0], &mut self.arena))
            }
            "__ctor:Result.Err" => {
                if args.len() != 1 {
                    return Err(RuntimeError::Error(format!(
                        "Result.Err() takes 1 argument, got {}",
                        args.len()
                    )));
                }
                Ok(NanValue::new_err_value(args[0], &mut self.arena))
            }
            "__ctor:Option.Some" => {
                if args.len() != 1 {
                    return Err(RuntimeError::Error(format!(
                        "Option.Some() takes 1 argument, got {}",
                        args.len()
                    )));
                }
                Ok(NanValue::new_some_value(args[0], &mut self.arena))
            }
            name if name.starts_with("__ctor:") => {
                // Variant constructors — need type registry, fall back to bridge
                let old_args: Vec<Value> = args.iter().map(|nv| nv.to_value(&self.arena)).collect();
                let result = self.dispatch_builtin(name, &old_args)?;
                Ok(NanValue::from_value(&result, &mut self.arena))
            }

            _ => {
                let err = || -> Result<NanValue, RuntimeError> {
                    Err(RuntimeError::Error(format!(
                        "Unknown builtin function: '{}'",
                        name
                    )))
                };
                let skip_server = matches!(self.execution_mode(), ExecutionMode::Record);
                match Self::builtin_namespace(name) {
                    Some("HttpServer") => {
                        // HttpServer needs callback support — bridge through Value
                        let old_args: Vec<Value> =
                            args.iter().map(|nv| nv.to_value(&self.arena)).collect();
                        let result = http_server::call_with_runtime(
                            name,
                            &old_args,
                            |handler, callback_args, callback_entry| {
                                let callback_effects = Self::callable_declared_effects(&handler);
                                self.call_value_with_effects_pub(
                                    handler,
                                    callback_args,
                                    &callback_entry,
                                    callback_effects,
                                )
                            },
                            skip_server,
                        )
                        .unwrap_or_else(|| {
                            Err(RuntimeError::Error(format!(
                                "Unknown builtin function: '{}'",
                                name
                            )))
                        })?;
                        Ok(NanValue::from_value(&result, &mut self.arena))
                    }
                    Some("Args") => args::call_nv(name, args, &self.cli_args, &mut self.arena)
                        .unwrap_or_else(err),
                    Some("Console") => {
                        console::call_nv(name, args, &mut self.arena).unwrap_or_else(err)
                    }
                    Some("Http") => http::call_nv(name, args, &mut self.arena).unwrap_or_else(err),
                    Some("Disk") => disk::call_nv(name, args, &mut self.arena).unwrap_or_else(err),
                    Some("Env") => env::call_nv(name, args, &mut self.arena).unwrap_or_else(err),
                    Some("Random") => {
                        random::call_nv(name, args, &mut self.arena).unwrap_or_else(err)
                    }
                    Some("Tcp") => tcp::call_nv(name, args, &mut self.arena).unwrap_or_else(err),
                    #[cfg(feature = "terminal")]
                    Some("Terminal") => {
                        terminal::call_nv(name, args, &mut self.arena).unwrap_or_else(err)
                    }
                    Some("Time") => time::call_nv(name, args, &mut self.arena).unwrap_or_else(err),
                    Some("Bool") => bool::call_nv(name, args, &mut self.arena).unwrap_or_else(err),
                    Some("Int") => int::call_nv(name, args, &mut self.arena).unwrap_or_else(err),
                    Some("Float") => {
                        float::call_nv(name, args, &mut self.arena).unwrap_or_else(err)
                    }
                    Some("String") => {
                        string::call_nv(name, args, &mut self.arena).unwrap_or_else(err)
                    }
                    Some("List") => list::call_nv(name, args, &mut self.arena).unwrap_or_else(err),
                    Some("Map") => map::call_nv(name, args, &mut self.arena).unwrap_or_else(err),
                    Some("Vector") => {
                        vector::call_nv(name, args, &mut self.arena).unwrap_or_else(err)
                    }
                    Some("Char") => char::call_nv(name, args, &mut self.arena).unwrap_or_else(err),
                    Some("Byte") => byte::call_nv(name, args, &mut self.arena).unwrap_or_else(err),
                    Some("Result") => {
                        result::call_nv(name, args, &mut self.arena).unwrap_or_else(err)
                    }
                    Some("Option") => {
                        option::call_nv(name, args, &mut self.arena).unwrap_or_else(err)
                    }
                    _ => err(),
                }
            }
        }
    }
}