tl-compiler 0.3.5

Bytecode compiler and VM for ThinkingLanguage (Phase 2)
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
// ThinkingLanguage — Async Runtime (tokio-backed)
// Licensed under MIT OR Apache-2.0
//
// Phase 25: Real async I/O implementations for the 9 async builtins.
// Feature-gated behind `async-runtime`.

use std::collections::HashMap;
use std::sync::{Arc, mpsc};

use tl_errors::{RuntimeError, TlError};
use tokio::runtime::Runtime;

use crate::security::SecurityPolicy;
use crate::value::{UpvalueRef, VmClosure, VmTask, VmValue};
use crate::vm::Vm;

fn runtime_err(msg: impl Into<String>) -> TlError {
    TlError::Runtime(RuntimeError {
        message: msg.into(),
        span: None,
        stack_trace: vec![],
    })
}

/// Close all upvalues (Open → Closed) using current stack values.
fn close_upvalues(closure: &VmClosure, stack: &[VmValue]) -> Vec<UpvalueRef> {
    closure
        .upvalues
        .iter()
        .map(|uv| match uv {
            UpvalueRef::Open { stack_index } => {
                let val = stack.get(*stack_index).cloned().unwrap_or(VmValue::None);
                UpvalueRef::Closed(val)
            }
            UpvalueRef::Closed(v) => UpvalueRef::Closed(v.clone()),
        })
        .collect()
}

// ── async_read_file ────────────────────────────────────────────────

pub fn async_read_file_impl(
    rt: &Runtime,
    args: &[VmValue],
    security_policy: &Option<SecurityPolicy>,
) -> Result<VmValue, TlError> {
    let path = match args.first() {
        Some(VmValue::String(s)) => s.clone(),
        _ => return Err(runtime_err("async_read_file() expects a string path")),
    };

    if let Some(policy) = security_policy {
        if !policy.check("file_read") {
            return Err(runtime_err(
                "async_read_file: file_read not allowed by security policy",
            ));
        }
    }

    let (tx, rx) = mpsc::channel();
    rt.spawn(async move {
        let result = tokio::fs::read_to_string(path.as_ref()).await;
        let _ = tx.send(
            result
                .map(|s| VmValue::String(Arc::from(s.as_str())))
                .map_err(|e| format!("async_read_file error: {e}")),
        );
    });
    Ok(VmValue::Task(Arc::new(VmTask::new(rx))))
}

// ── async_write_file ───────────────────────────────────────────────

pub fn async_write_file_impl(
    rt: &Runtime,
    args: &[VmValue],
    security_policy: &Option<SecurityPolicy>,
) -> Result<VmValue, TlError> {
    let path = match args.first() {
        Some(VmValue::String(s)) => s.clone(),
        _ => return Err(runtime_err("async_write_file() expects a string path")),
    };
    let content = match args.get(1) {
        Some(VmValue::String(s)) => s.clone(),
        _ => {
            return Err(runtime_err(
                "async_write_file() expects string content as second argument",
            ));
        }
    };

    if let Some(policy) = security_policy {
        if !policy.check("file_write") {
            return Err(runtime_err(
                "async_write_file: file_write not allowed by security policy",
            ));
        }
    }

    let (tx, rx) = mpsc::channel();
    rt.spawn(async move {
        let result = tokio::fs::write(path.as_ref(), content.as_ref().as_bytes()).await;
        let _ = tx.send(
            result
                .map(|_| VmValue::None)
                .map_err(|e| format!("async_write_file error: {e}")),
        );
    });
    Ok(VmValue::Task(Arc::new(VmTask::new(rx))))
}

// ── async_http_get ─────────────────────────────────────────────────

pub fn async_http_get_impl(
    rt: &Runtime,
    args: &[VmValue],
    security_policy: &Option<SecurityPolicy>,
) -> Result<VmValue, TlError> {
    let url = match args.first() {
        Some(VmValue::String(s)) => s.clone(),
        _ => return Err(runtime_err("async_http_get() expects a string URL")),
    };

    if let Some(policy) = security_policy {
        if !policy.check("network") {
            return Err(runtime_err(
                "async_http_get: network not allowed by security policy",
            ));
        }
    }

    let (tx, rx) = mpsc::channel();
    rt.spawn(async move {
        let result: Result<VmValue, String> = async {
            let body = reqwest::get(url.as_ref())
                .await
                .map_err(|e| format!("async_http_get error: {e}"))?
                .text()
                .await
                .map_err(|e| format!("async_http_get response error: {e}"))?;
            Ok(VmValue::String(Arc::from(body.as_str())))
        }
        .await;
        let _ = tx.send(result);
    });
    Ok(VmValue::Task(Arc::new(VmTask::new(rx))))
}

// ── async_http_post ────────────────────────────────────────────────

pub fn async_http_post_impl(
    rt: &Runtime,
    args: &[VmValue],
    security_policy: &Option<SecurityPolicy>,
) -> Result<VmValue, TlError> {
    let url = match args.first() {
        Some(VmValue::String(s)) => s.clone(),
        _ => return Err(runtime_err("async_http_post() expects a string URL")),
    };
    let body = match args.get(1) {
        Some(VmValue::String(s)) => s.clone(),
        _ => {
            return Err(runtime_err(
                "async_http_post() expects string body as second argument",
            ));
        }
    };

    if let Some(policy) = security_policy {
        if !policy.check("network") {
            return Err(runtime_err(
                "async_http_post: network not allowed by security policy",
            ));
        }
    }

    let (tx, rx) = mpsc::channel();
    rt.spawn(async move {
        let result: Result<VmValue, String> = async {
            let resp = reqwest::Client::new()
                .post(url.as_ref())
                .body(body.to_string())
                .send()
                .await
                .map_err(|e| format!("async_http_post error: {e}"))?
                .text()
                .await
                .map_err(|e| format!("async_http_post response error: {e}"))?;
            Ok(VmValue::String(Arc::from(resp.as_str())))
        }
        .await;
        let _ = tx.send(result);
    });
    Ok(VmValue::Task(Arc::new(VmTask::new(rx))))
}

// ── async_sleep ────────────────────────────────────────────────────

pub fn async_sleep_impl(rt: &Runtime, args: &[VmValue]) -> Result<VmValue, TlError> {
    let ms = match args.first() {
        Some(VmValue::Int(n)) => *n as u64,
        _ => {
            return Err(runtime_err(
                "async_sleep() expects an integer (milliseconds)",
            ));
        }
    };

    let (tx, rx) = mpsc::channel();
    rt.spawn(async move {
        tokio::time::sleep(tokio::time::Duration::from_millis(ms)).await;
        let _ = tx.send(Ok(VmValue::None));
    });
    Ok(VmValue::Task(Arc::new(VmTask::new(rx))))
}

// ── select ─────────────────────────────────────────────────────────
// Takes 2+ task arguments, returns the result of whichever finishes first.
// Uses std::thread racing since tasks are already mpsc receivers.

pub fn select_impl(args: &[VmValue]) -> Result<VmValue, TlError> {
    if args.len() < 2 {
        return Err(runtime_err("select() expects at least 2 task arguments"));
    }

    // Collect receivers from all tasks
    let mut receivers = Vec::new();
    for (i, arg) in args.iter().enumerate() {
        match arg {
            VmValue::Task(task) => {
                let rx = {
                    let mut guard = task.receiver.lock().unwrap();
                    guard.take()
                };
                match rx {
                    Some(r) => receivers.push(r),
                    None => {
                        return Err(runtime_err(format!("select: task {} already consumed", i)));
                    }
                }
            }
            _ => return Err(runtime_err(format!("select: argument {} is not a task", i))),
        }
    }

    // Race: spawn a thread per receiver, first result wins via a shared channel
    let (winner_tx, winner_rx) = mpsc::channel::<Result<VmValue, String>>();
    for rx in receivers {
        let tx = winner_tx.clone();
        std::thread::spawn(move || {
            if let Ok(result) = rx.recv() {
                let _ = tx.send(result);
            }
        });
    }
    drop(winner_tx);

    // Return a task that resolves to the first result
    Ok(VmValue::Task(Arc::new(VmTask::new(winner_rx))))
}

// ── race_all ───────────────────────────────────────────────────────
// Takes a list of tasks, returns the result of whichever finishes first.

pub fn race_all_impl(args: &[VmValue]) -> Result<VmValue, TlError> {
    let tasks = match args.first() {
        Some(VmValue::List(list)) => list.clone(),
        _ => return Err(runtime_err("race_all() expects a list of tasks")),
    };

    if tasks.is_empty() {
        return Err(runtime_err("race_all() expects a non-empty list of tasks"));
    }

    // Collect receivers
    let mut receivers = Vec::new();
    for (i, task_val) in tasks.iter().enumerate() {
        match task_val {
            VmValue::Task(task) => {
                let rx = {
                    let mut guard = task.receiver.lock().unwrap();
                    guard.take()
                };
                match rx {
                    Some(r) => receivers.push(r),
                    None => {
                        return Err(runtime_err(format!(
                            "race_all: task {} already consumed",
                            i
                        )));
                    }
                }
            }
            _ => {
                return Err(runtime_err(format!(
                    "race_all: element {} is not a task",
                    i
                )));
            }
        }
    }

    // Race: spawn a thread per receiver, first result wins
    let (winner_tx, winner_rx) = mpsc::channel::<Result<VmValue, String>>();
    for rx in receivers {
        let tx = winner_tx.clone();
        std::thread::spawn(move || {
            if let Ok(result) = rx.recv() {
                let _ = tx.send(result);
            }
        });
    }
    drop(winner_tx);

    Ok(VmValue::Task(Arc::new(VmTask::new(winner_rx))))
}

// ── async_map ──────────────────────────────────────────────────────
// Maps a closure over a list concurrently using spawn_blocking.

pub fn async_map_impl(
    rt: &Runtime,
    args: &[VmValue],
    globals: &HashMap<String, VmValue>,
    stack: &[VmValue],
) -> Result<VmValue, TlError> {
    let items = match args.first() {
        Some(VmValue::List(list)) => list.clone(),
        _ => return Err(runtime_err("async_map() expects a list as first argument")),
    };
    let closure = match args.get(1) {
        Some(VmValue::Function(c)) => c.clone(),
        _ => {
            return Err(runtime_err(
                "async_map() expects a function as second argument",
            ));
        }
    };

    let closed_upvalues = close_upvalues(&closure, stack);
    let proto = closure.prototype.clone();
    let globals = globals.clone();

    let (tx, rx) = mpsc::channel();
    rt.spawn(async move {
        let mut handles: Vec<tokio::task::JoinHandle<Result<VmValue, String>>> = Vec::new();
        for item in items {
            let proto = proto.clone();
            let upvalues = closed_upvalues.clone();
            let globals = globals.clone();
            let handle = tokio::task::spawn_blocking(move || {
                let mut vm = Vm::new();
                vm.globals = globals;
                vm.execute_closure_with_args(&proto, &upvalues, &[item])
                    .map_err(|e| format!("{e}"))
            });
            handles.push(handle);
        }

        let mut results = Vec::new();
        for handle in handles {
            match handle.await {
                Ok(Ok(val)) => results.push(val),
                Ok(Err(e)) => {
                    let _ = tx.send(Err(format!("async_map error: {e}")));
                    return;
                }
                Err(e) => {
                    let _ = tx.send(Err(format!("async_map join error: {e}")));
                    return;
                }
            }
        }
        let _ = tx.send(Ok(VmValue::List(results)));
    });

    Ok(VmValue::Task(Arc::new(VmTask::new(rx))))
}

// ── async_filter ───────────────────────────────────────────────────
// Filters a list concurrently using spawn_blocking for the predicate.

pub fn async_filter_impl(
    rt: &Runtime,
    args: &[VmValue],
    globals: &HashMap<String, VmValue>,
    stack: &[VmValue],
) -> Result<VmValue, TlError> {
    let items = match args.first() {
        Some(VmValue::List(list)) => list.clone(),
        _ => {
            return Err(runtime_err(
                "async_filter() expects a list as first argument",
            ));
        }
    };
    let closure = match args.get(1) {
        Some(VmValue::Function(c)) => c.clone(),
        _ => {
            return Err(runtime_err(
                "async_filter() expects a function as second argument",
            ));
        }
    };

    let closed_upvalues = close_upvalues(&closure, stack);
    let proto = closure.prototype.clone();
    let globals = globals.clone();

    let (tx, rx) = mpsc::channel();
    rt.spawn(async move {
        let mut handles: Vec<tokio::task::JoinHandle<Result<VmValue, String>>> = Vec::new();
        for item in items.clone() {
            let proto = proto.clone();
            let upvalues = closed_upvalues.clone();
            let globals = globals.clone();
            let handle = tokio::task::spawn_blocking(move || {
                let mut vm = Vm::new();
                vm.globals = globals;
                vm.execute_closure_with_args(&proto, &upvalues, &[item])
                    .map_err(|e| format!("{e}"))
            });
            handles.push(handle);
        }

        let mut results = Vec::new();
        for (i, handle) in handles.into_iter().enumerate() {
            match handle.await {
                Ok(Ok(val)) => {
                    let keep = matches!(&val, VmValue::Bool(true));
                    if keep {
                        results.push(items[i].clone());
                    }
                }
                Ok(Err(e)) => {
                    let _ = tx.send(Err(format!("async_filter error: {e}")));
                    return;
                }
                Err(e) => {
                    let _ = tx.send(Err(format!("async_filter join error: {e}")));
                    return;
                }
            }
        }
        let _ = tx.send(Ok(VmValue::List(results)));
    });

    Ok(VmValue::Task(Arc::new(VmTask::new(rx))))
}