vile / examples / context_host / main.v
34 lines · 31 sloc · 1.05 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module main
2
3import arena
4import context
5import scheme
6import time
7
8// Text borrows the region until main copies it after this function pops it.
9fn run_borrowed(region &arena.Arena, mut ctx context.Context) string {
10 region.push()
11 defer { region.pop() }
12 mut vm := scheme.new_with_options(scheme.Options{ max_steps: 0 }) or { return err.msg() }
13 value := vm.with_context(mut ctx, fn (mut vm scheme.VM) !scheme.Value {
14 return vm.eval('(let loop () (loop))')
15 }) or {
16 if err is scheme.CancellationRequest { return err.msg() }
17 return 'evaluation failed: ${err.msg()}'
18 }
19 return scheme.write(value) or { err.msg() }
20}
21
22fn main() {
23 // Contexts, channels, and timer/cancel machinery belong to the host.
24 // A standard timer goroutine may remain alive after cancel() returns.
25 mut background := context.background()
26 mut ctx, cancel := context.with_timeout(mut background, 20 * time.millisecond)
27 defer { cancel() }
28 mut region := arena.new()
29 borrowed := run_borrowed(&region, mut ctx)
30 text := borrowed.clone()
31 region.free()
32 println(text)
33 unsafe { text.free() }
34}
35