forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstdlib.rs
More file actions
589 lines (562 loc) · 25.2 KB
/
Copy pathstdlib.rs
File metadata and controls
589 lines (562 loc) · 25.2 KB
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
//! Standard-library inventory.
//!
//! This module is an inventory/documentation layer only: it does not
//! implement any behavior. It records every built-in effect operation and
//! function that is currently wired into the VM and runtime, so tools
//! (REPL, LSP, docs generators) have a single source of truth for what a
//! `perform Effect.op(...)` call resolves to when no user handler is
//! installed.
//!
//! The wiring itself lives elsewhere:
//! - `IO.print` / `IO.println` / `IO.read`: `VM::perform_builtin_effect`
//! in `vm.rs` (standalone, actor-free scripts).
//! - `Timer.sleep`: the runtime host's `perform_effect` callback in
//! `runtime/mod.rs` (workflow actors only).
//! - `Signal.wait`: lowered to the `SignalWait` opcode in `mir_lower.rs`,
//! served by the host `wait_signal` callback.
//! - `Inference.ask` (canonical) / `LLM.ask` (deprecated alias): lowered to the `PerformAsync` opcode
//! in `mir_lower.rs`, served by the host `perform_async` callback.
//! - `Actor.*` (link/unlink/monitor/demonitor/trap_exit/exit/register/
//! unregister/whereis/set_priority): `Runtime::perform_actor_builtin` in
//! `runtime/mod.rs`, reached through both runtime host callback impls;
//! the standalone VM answers them with a nil no-op.
//! - `Http.get` / `Http.post`: the runtime host's `perform_builtin_effect`
//! callback in `runtime/mod.rs`, dispatched through `HttpProvider` trait
//! (ReqwestHttpProvider behind `ai-runtime` / `http-client` feature).
use crate::types::Span;
use crate::types::{NuError, NuResult};
// ---------------------------------------------------------------------------
// BuiltinOp: one built-in effect operation
// ---------------------------------------------------------------------------
/// Where a built-in operation is implemented.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImplSite {
/// Handled by `VM::perform_builtin_effect` in the standalone VM
/// (actor-free scripts); no runtime required.
StandaloneVm,
/// Handled by a runtime host callback (`ActorVmCallbacks`); requires
/// the actor runtime and, for `Timer.sleep`, a workflow actor.
RuntimeHost,
}
/// A single built-in effect operation wired into the VM/runtime.
#[derive(Debug, Clone, Copy)]
pub struct BuiltinOp {
/// Fully-qualified name as dispatched by the VM, e.g. `"IO.print"`.
pub name: &'static str,
/// Effect the operation belongs to, e.g. `"IO"`.
pub effect: &'static str,
/// Operation name within the effect, e.g. `"print"`.
pub op: &'static str,
/// Human-readable signature, e.g. `"print(msg: String) -> Unit"`.
pub signature: &'static str,
/// Where the operation is implemented.
pub implemented_in: ImplSite,
/// One-line description of the behavior.
pub description: &'static str,
}
// ---------------------------------------------------------------------------
// StdLib: registry of built-in operations
// ---------------------------------------------------------------------------
/// Registry of every built-in effect operation currently wired into the
/// VM and runtime.
///
/// The registry is static: it mirrors the dispatch sites in `vm.rs` and
/// `runtime/mod.rs` and is updated by hand when a new built-in is wired.
pub struct StdLib {
ops: Vec<BuiltinOp>,
}
impl StdLib {
/// Build the registry with all currently wired built-ins.
pub fn new() -> Self {
StdLib {
ops: vec![
BuiltinOp {
name: "IO.print",
effect: "IO",
op: "print",
signature: "print(msg: String) -> Unit",
implemented_in: ImplSite::StandaloneVm,
description: "Write the argument to stdout, followed by a newline.",
},
BuiltinOp {
name: "IO.println",
effect: "IO",
op: "println",
signature: "println(msg: String) -> Unit",
implemented_in: ImplSite::StandaloneVm,
description: "Alias of `IO.print`; writes the argument to stdout with a newline.",
},
BuiltinOp {
name: "IO.read",
effect: "IO",
op: "read",
signature: "read() -> String",
implemented_in: ImplSite::StandaloneVm,
description: "Read one line from stdin; returns the line without the trailing newline.",
},
BuiltinOp { name: "IO.log", effect: "IO", op: "log", signature: "log(level: String, message: String) -> Unit", implemented_in: ImplSite::StandaloneVm, description: "Log a message at the given level to stderr.", },
BuiltinOp { name: "IO.log_error", effect: "IO", op: "log_error", signature: "log_error(message: String) -> Unit", implemented_in: ImplSite::StandaloneVm, description: "Log an error message to stderr.", },
BuiltinOp { name: "Debug.inspect", effect: "Debug", op: "inspect", signature: "inspect(label: String, value: a) -> a", implemented_in: ImplSite::StandaloneVm, description: "Print a labeled value to stderr and return it unchanged.", },
BuiltinOp {
name: "Int.to_string",
effect: "Int",
op: "to_string",
signature: "to_string(value: Int) -> String",
implemented_in: ImplSite::RuntimeHost,
description: "Convert an integer to its string representation.",
},
BuiltinOp {
name: "String.length",
effect: "String",
op: "length",
signature: "length(s: String) -> Int",
implemented_in: ImplSite::StandaloneVm,
description: "Return the length of the string in bytes.",
},
BuiltinOp {
name: "String.charAt",
effect: "String",
op: "charAt",
signature: "charAt(s: String, index: Int) -> Int",
implemented_in: ImplSite::StandaloneVm,
description: "Return the byte at the given index in the string, or -1 if out of bounds.",
},
BuiltinOp { name: "String.concat", effect: "String", op: "concat", signature: "concat(a: String, b: String) -> String", implemented_in: ImplSite::StandaloneVm, description: "Concatenate two strings.", },
BuiltinOp { name: "String.substring", effect: "String", op: "substring", signature: "substring(s: String, start: Int, len: Int) -> String", implemented_in: ImplSite::StandaloneVm, description: "Extract a substring.", },
BuiltinOp {
name: "Timer.sleep",
effect: "Timer",
op: "sleep",
signature: "sleep(name: String, duration_ms: Int) -> Unit",
implemented_in: ImplSite::RuntimeHost,
description: "Schedule a durable workflow timer; only available inside workflow actors.",
},
BuiltinOp {
name: "Signal.wait",
effect: "Signal",
op: "wait",
signature: "wait(name: String) -> Unit",
implemented_in: ImplSite::RuntimeHost,
description: "Suspend the workflow until the named signal arrives, then resume with unit.",
},
BuiltinOp {
name: "Inference.ask",
effect: "Inference",
op: "ask",
signature: "ask(prompt: String) -> String",
implemented_in: ImplSite::RuntimeHost,
description: "Send the prompt to the configured inference provider and return the reply; suspends non-blockingly when the runtime supports it.",
},
BuiltinOp {
name: "LLM.ask",
effect: "LLM",
op: "ask",
signature: "ask(prompt: String) -> String",
implemented_in: ImplSite::RuntimeHost,
description: "Deprecated alias for `Inference.ask`. Prefer `Inference.ask` in new code.",
},
BuiltinOp {
name: "Http.get",
effect: "Http",
op: "get",
signature: "get(url: String) -> String",
implemented_in: ImplSite::RuntimeHost,
description: "Perform an HTTP GET request to `url` and return the response body as a string on success, nil on error. Requires the `http-client` or `ai-runtime` feature for the reqwest provider.",
},
BuiltinOp {
name: "Http.post",
effect: "Http",
op: "post",
signature: "post(url: String, body: String) -> String",
implemented_in: ImplSite::RuntimeHost,
description: "Perform an HTTP POST request to `url` with a JSON body and return the response body as a string on success, nil on error. Requires the `http-client` or `ai-runtime` feature for the reqwest provider.",
},
BuiltinOp {
name: "Http.serve",
effect: "Http",
op: "serve",
signature: "serve(port: Int, handler: fn(String) -> String) -> Int",
implemented_in: ImplSite::RuntimeHost,
description: "Start an HTTP/1.1 server on `port`. For each request, calls `handler(body)` and returns the result as the response body with status 200. Returns the actual bound port.",
},
BuiltinOp {
name: "Actor.link",
effect: "Actor",
op: "link",
signature: "link(target: Actor) -> Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Link the current actor to `target`; abnormal exits propagate to linked peers. Nil no-op outside an actor.",
},
BuiltinOp {
name: "Actor.unlink",
effect: "Actor",
op: "unlink",
signature: "unlink(target: Actor) -> Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Remove the link between the current actor and `target`. Nil no-op outside an actor.",
},
BuiltinOp {
name: "Actor.monitor",
effect: "Actor",
op: "monitor",
signature: "monitor(target: Actor) -> Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Monitor `target` from the current actor; a DOWN system message is delivered when it exits. Nil no-op outside an actor.",
},
BuiltinOp {
name: "Actor.demonitor",
effect: "Actor",
op: "demonitor",
signature: "demonitor(target: Actor) -> Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Stop the current actor's monitor on `target`, so no DOWN message is delivered. Nil no-op outside an actor.",
},
BuiltinOp {
name: "Actor.trap_exit",
effect: "Actor",
op: "trap_exit",
signature: "trap_exit(flag: Bool) -> Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Set the current actor's trap_exits flag; when true, linked-peer exit signals arrive as system messages instead of killing it. Nil no-op outside an actor.",
},
BuiltinOp {
name: "Actor.exit",
effect: "Actor",
op: "exit",
signature: "exit(reason: Int | String) -> Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Self-exit the current actor; 0/\"normal\", 1/\"error\", 2/\"kill\" select the reason, anything else is custom. Nil no-op outside an actor.",
},
BuiltinOp {
name: "Actor.register",
effect: "Actor",
op: "register",
signature: "register(name: String) -> Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Register the current actor under `name` in the local actor registry. Nil no-op outside an actor.",
},
BuiltinOp {
name: "Actor.unregister",
effect: "Actor",
op: "unregister",
signature: "unregister(name: String) -> Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Remove `name` from the local actor registry.",
},
BuiltinOp {
name: "Actor.whereis",
effect: "Actor",
op: "whereis",
signature: "whereis(name: String) -> Actor | Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Look up `name` in the local actor registry; returns the actor ref, or nil when the name is not registered.",
},
BuiltinOp {
name: "Actor.set_priority",
effect: "Actor",
op: "set_priority",
signature: "set_priority(level: Int) -> Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Set the current actor's scheduling priority: 0=High, 1=Normal, 2=Low (any other value selects Normal). Ready High-priority actors are scheduled before Normal, Normal before Low; affects scheduling only, not message order. Nil no-op outside an actor.",
},
BuiltinOp {
name: "Otp.create_supervisor",
effect: "Otp",
op: "create_supervisor",
signature: "create_supervisor(name: String, strategy: Int) -> Int | Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Create an OTP supervisor actor and return its id; strategy is 0=one_for_one, 1=one_for_all, 2=rest_for_one, 3=simple_one_for_one (any other value yields nil). Nil no-op outside a runtime.",
},
BuiltinOp {
name: "Otp.supervise_child",
effect: "Otp",
op: "supervise_child",
signature: "supervise_child(sup: Int, child: Actor, policy: Int) -> Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Place an existing actor under a supervisor; policy is 0=permanent, 1=temporary, 2=transient (any other value is a no-op). Unknown supervisor ids are nil no-ops.",
},
BuiltinOp {
name: "Otp.set_template",
effect: "Otp",
op: "set_template",
signature: "set_template(sup: Int, type_name: String) -> Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Set the child template of a simple_one_for_one supervisor to the named actor type, resolved against the performing module's actor metadata. Unknown types or supervisor ids are nil no-ops.",
},
BuiltinOp {
name: "Otp.start_child",
effect: "Otp",
op: "start_child",
signature: "start_child(sup: Int) -> Actor | Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Spawn a fresh child from a simple_one_for_one supervisor's template and supervise it; returns the child actor ref, or nil when the supervisor is unknown, has no template, or is not simple_one_for_one.",
},
BuiltinOp {
name: "Otp.terminate_child",
effect: "Otp",
op: "terminate_child",
signature: "terminate_child(sup: Int, child: Actor) -> Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Remove a child from supervision WITHOUT restarting it and exit it cleanly (Normal). Unknown supervisors or children are nil no-ops.",
},
BuiltinOp {
name: "Otp.child_count",
effect: "Otp",
op: "child_count",
signature: "child_count(sup: Int) -> Int | Nil",
implemented_in: ImplSite::RuntimeHost,
description: "Return the number of currently supervised children, or nil for an unknown supervisor id.",
},
],
}
}
/// All registered built-in operations, in registration order.
pub fn ops(&self) -> &[BuiltinOp] {
&self.ops
}
/// Look up a built-in by its fully-qualified name (e.g. `"IO.print"`).
pub fn lookup(&self, name: &str) -> Option<&BuiltinOp> {
self.ops.iter().find(|op| op.name == name)
}
/// Look up a built-in by fully-qualified name, or fail with a
/// descriptive error naming the unknown operation.
pub fn require(&self, name: &str) -> NuResult<&BuiltinOp> {
self.lookup(name).ok_or_else(|| NuError::RuntimeError {
msg: format!("unknown built-in operation '{}'", name),
span: Span::default(),
})
}
/// Distinct effect names covered by the registry, in first-seen order.
pub fn effects(&self) -> Vec<&'static str> {
let mut out: Vec<&'static str> = Vec::new();
for op in &self.ops {
if !out.contains(&op.effect) {
out.push(op.effect);
}
}
out
}
}
impl Default for StdLib {
fn default() -> Self {
Self::new()
}
}
// ---------------------------------------------------------------------------
// stdlib_docs: human-readable reference
// ---------------------------------------------------------------------------
/// Print a human-readable reference of every built-in effect operation
/// currently wired into the VM and runtime.
pub fn stdlib_docs() -> String {
let lib = StdLib::new();
let mut out = String::new();
out.push_str("Nulang standard library — built-in effect operations\n");
out.push_str("======================================================\n\n");
for effect in lib.effects() {
out.push_str(&format!("effect {}\n", effect));
for op in lib.ops().iter().filter(|op| op.effect == effect) {
let site = match op.implemented_in {
ImplSite::StandaloneVm => "standalone VM",
ImplSite::RuntimeHost => "runtime host",
};
out.push_str(&format!(
" {} [{}]\n {}\n",
op.signature, site, op.description
));
}
out.push('\n');
}
out
}
// ---------------------------------------------------------------------------
// Behavior contracts
// ---------------------------------------------------------------------------
/// A behavior contract that an actor can declare it implements.
/// The compiler verifies that the actor has all required handler behaviors
/// with compatible signatures.
#[derive(Debug, Clone)]
pub struct BehaviorContract {
/// Contract name (e.g. "StatefulService").
pub name: &'static str,
/// Required handler behaviors. Each entry is `(handler_name, param_count)`.
/// The compiler checks that the actor declares a behavior with matching
/// name and compatible parameter count.
pub required_handlers: &'static [(&'static str, usize)],
/// Human-readable description.
pub description: &'static str,
}
/// Built-in behavior contracts that the compiler knows about.
pub const BUILTIN_CONTRACTS: &[BehaviorContract] = &[BehaviorContract {
name: "StatefulService",
required_handlers: &[
("init", 1),
("handle_call", 2),
("handle_cast", 1),
("handle_info", 1),
("terminate", 1),
],
description:
"Erlang/OTP gen_server-style stateful service with init/call/cast/info/terminate handlers.",
}];
/// Look up a built-in behavior contract by name.
pub fn lookup_contract(name: &str) -> Option<&'static BehaviorContract> {
BUILTIN_CONTRACTS.iter().find(|c| c.name == name)
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn registry_contains_expected_builtins() {
let lib = StdLib::new();
for name in [
"IO.print",
"IO.println",
"IO.read",
"Timer.sleep",
"Signal.wait",
"LLM.ask",
"Actor.link",
"Actor.unlink",
"Actor.monitor",
"Actor.demonitor",
"Actor.trap_exit",
"Actor.exit",
"Actor.register",
"Actor.unregister",
"Actor.whereis",
"Actor.set_priority",
"Otp.create_supervisor",
"Otp.supervise_child",
"Otp.set_template",
"Otp.start_child",
"Otp.terminate_child",
"Otp.child_count",
] {
assert!(
lib.lookup(name).is_some(),
"registry must contain built-in '{}'",
name
);
}
}
#[test]
fn registry_entries_are_consistent() {
let lib = StdLib::new();
for op in lib.ops() {
assert_eq!(
format!("{}.{}", op.effect, op.op),
op.name,
"name must equal effect.op for '{}'",
op.name
);
assert!(!op.signature.is_empty(), "'{}' needs a signature", op.name);
assert!(
op.signature.starts_with(op.op),
"signature of '{}' must start with the op name",
op.name
);
assert!(
!op.description.is_empty(),
"'{}' needs a description",
op.name
);
}
}
#[test]
fn lookup_reports_impl_sites() {
let lib = StdLib::new();
assert_eq!(
lib.lookup("IO.print").unwrap().implemented_in,
ImplSite::StandaloneVm
);
assert_eq!(
lib.lookup("IO.read").unwrap().implemented_in,
ImplSite::StandaloneVm
);
assert_eq!(
lib.lookup("Timer.sleep").unwrap().implemented_in,
ImplSite::RuntimeHost
);
assert_eq!(
lib.lookup("Signal.wait").unwrap().implemented_in,
ImplSite::RuntimeHost
);
assert_eq!(
lib.lookup("LLM.ask").unwrap().implemented_in,
ImplSite::RuntimeHost
);
assert_eq!(
lib.lookup("Actor.link").unwrap().implemented_in,
ImplSite::RuntimeHost
);
assert_eq!(
lib.lookup("Actor.whereis").unwrap().implemented_in,
ImplSite::RuntimeHost
);
assert_eq!(
lib.lookup("Http.get").unwrap().implemented_in,
ImplSite::RuntimeHost
);
assert_eq!(
lib.lookup("Http.post").unwrap().implemented_in,
ImplSite::RuntimeHost
);
}
#[test]
fn effects_lists_distinct_effects_in_order() {
let lib = StdLib::new();
assert_eq!(
lib.effects(),
vec![
"IO",
"Debug",
"Int",
"String",
"Timer",
"Signal",
"Inference",
"LLM",
"Http",
"Actor",
"Otp"
]
);
}
#[test]
fn lookup_unknown_returns_none() {
let lib = StdLib::new();
assert!(lib.lookup("Net.send").is_none());
assert!(lib.lookup("IO.nonexistent").is_none());
}
#[test]
fn require_unknown_is_an_error() {
let lib = StdLib::new();
let err = lib.require("Net.send").unwrap_err();
let msg = format!("{}", err);
assert!(
msg.contains("Net.send"),
"error must name the operation: {}",
msg
);
}
#[test]
fn docs_mention_every_registered_op() {
let docs = stdlib_docs();
let lib = StdLib::new();
for op in lib.ops() {
assert!(
docs.contains(op.signature),
"docs must include the signature of '{}'",
op.name
);
assert!(
docs.contains(op.description),
"docs must include the description of '{}'",
op.name
);
}
}
}