Make fact example a wasi:cli command that prints its result
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
987cdf256b
commit
38f7b934b5
3 files changed
+38
-3
No files matched your search
@@ -6,6 +6,7 @@ runtime: the output is hand-encoded machine code in one or two `PT_LOAD` segment
|
||||
```
|
||||
just run sum # core module -> ELF, runs it, prints the exit code
|
||||
just run-component hello # wasi:cli component -> ELF, prints "Hello from wasi:cli!"
|
||||
just run-component fact # wasi:cli component -> ELF, prints "fact(5) = 120"
|
||||
just examples # everything in examples/
|
||||
```
|
||||
|
||||
|
||||
+33
-3
@@ -1,8 +1,38 @@
|
||||
;; recursive factorial(5) = 120, plus if/else with result
|
||||
;; wasi:cli command: computes factorial(5) recursively and prints "fact(5) = 120".
|
||||
;; Build with: just run-component fact
|
||||
(module
|
||||
(import "wasi:cli/stdout@0.2.0" "get-stdout" (func $get_stdout (result i32)))
|
||||
(import "wasi:io/streams@0.2.0" "[method]output-stream.blocking-write-and-flush"
|
||||
(func $write (param i32 i32 i32 i32)))
|
||||
(memory (export "memory") 1)
|
||||
(data (i32.const 16) "fact(5) = ")
|
||||
|
||||
(func $fact (param $n i32) (result i32)
|
||||
(if (result i32) (i32.le_s (local.get $n) (i32.const 1))
|
||||
(then (i32.const 1))
|
||||
(else (i32.mul (local.get $n) (call $fact (i32.sub (local.get $n) (i32.const 1)))))))
|
||||
(func (export "main") (result i32)
|
||||
(call $fact (i32.const 5))))
|
||||
|
||||
(func (export "wasi:cli/run@0.2.0#run") (result i32)
|
||||
(local $v i32) (local $p i32)
|
||||
(local.set $v (call $fact (i32.const 5)))
|
||||
;; write decimal digits backwards, ending just before a trailing newline at 63
|
||||
(local.set $p (i32.const 63))
|
||||
(i32.store8 (i32.const 63) (i32.const 10))
|
||||
(loop $digits
|
||||
(local.set $p (i32.sub (local.get $p) (i32.const 1)))
|
||||
(i32.store8 (local.get $p)
|
||||
(i32.add (i32.const 48) (i32.rem_u (local.get $v) (i32.const 10))))
|
||||
(local.set $v (i32.div_u (local.get $v) (i32.const 10)))
|
||||
(br_if $digits (local.get $v)))
|
||||
;; prefix "fact(5) = " (10 bytes at 16..26); copy digits right after it
|
||||
(local.set $v (i32.const 26))
|
||||
(block $done
|
||||
(loop $copy
|
||||
(br_if $done (i32.gt_u (local.get $p) (i32.const 63)))
|
||||
(i32.store8 (local.get $v) (i32.load8_u (local.get $p)))
|
||||
(local.set $v (i32.add (local.get $v) (i32.const 1)))
|
||||
(local.set $p (i32.add (local.get $p) (i32.const 1)))
|
||||
(br $copy)))
|
||||
(call $write (call $get_stdout) (i32.const 16)
|
||||
(i32.sub (local.get $v) (i32.const 16)) (i32.const 128))
|
||||
(i32.load8_u (i32.const 128))))
|
||||
@@ -3,3 +3,7 @@ package local:examples;
|
||||
world hello {
|
||||
include wasi:cli/command@0.2.0;
|
||||
}
|
||||
|
||||
world fact {
|
||||
include wasi:cli/command@0.2.0;
|
||||
}
|
||||
Reference in new issue
Block a user