sovereign-intelligence
Front door to Drake Stapleton's sovereign stack.
Brought by drakestapleton
sovereign-intelligence / harness / examples / echo_args.om
| 1 | note echo_args: argcnt includes the program name; argread copies one argument without a terminator |
| 2 | note ---- output helpers: a function works on a global by naming it (a global is never an argument) |
| 3 | global ob uchar 32 |
| 4 | note outb: write ob[off .. off+n) to stdout; a short write continues, 0 or an error exits 90 |
| 5 | note bound: every pass writes at least one byte and n <= 32, so at most 32 passes |
| 6 | fn outb off ulong n ulong to void |
| 7 | e = add off n |
| 8 | p = off |
| 9 | while lt p e bound 32 |
| 10 | k = write 1 ob p sub e p |
| 11 | if le k 0 |
| 12 | exit 90 |
| 13 | end |
| 14 | p = add p ulong k |
| 15 | end |
| 16 | end |
| 17 | note putu: v in decimal, then a newline. A ulong has at most 20 digits, so 20 passes |
| 18 | fn putu v ulong to void |
| 19 | i = ulong 31 |
| 20 | put ob 31 10 |
| 21 | n = v |
| 22 | while true bound 20 |
| 23 | i = sub i 1 |
| 24 | put ob i uchar add rem n 10 48 |
| 25 | n = div n 10 |
| 26 | if eq n 0 |
| 27 | break |
| 28 | end |
| 29 | end |
| 30 | outb i sub 32 i |
| 31 | end |
| 32 | note putl: a signed value; -(v+1)+1 avoids negating the minimum, which would trap 1 |
| 33 | fn putl v long to void |
| 34 | if lt v 0 |
| 35 | put ob 0 45 |
| 36 | outb 0 1 |
| 37 | putu add ulong neg add v 1 1 |
| 38 | ret |
| 39 | end |
| 40 | putu ulong v |
| 41 | end |
| 42 | global ab uchar 32 |
| 43 | text toolong "(longer than 31 bytes)\n" |
| 44 | fn main to int |
| 45 | n = argcnt |
| 46 | putl n |
| 47 | i = ulong 1 |
| 48 | while lt long i n bound 64 |
| 49 | k = argread i ab 0 31 |
| 50 | if eq k -105 |
| 51 | w = write 1 toolong 0 len toolong |
| 52 | else |
| 53 | m = ulong k |
| 54 | put ab m 10 |
| 55 | outbuf m |
| 56 | end |
| 57 | i = add i 1 |
| 58 | end |
| 59 | ret 0 |
| 60 | end |
| 61 | note outbuf: write ab[0 .. m] (the argument and its newline); exit 90 on an error |
| 62 | fn outbuf m ulong to void |
| 63 | e = add m 1 |
| 64 | p = ulong 0 |
| 65 | while lt p e bound 32 |
| 66 | k = write 1 ab p sub e p |
| 67 | if le k 0 |
| 68 | exit 90 |
| 69 | end |
| 70 | p = add p ulong k |
| 71 | end |
| 72 | end |