omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
omega-mv / si / harness / examples / stdin_count.om
| 1 | note stdin_count: read stdin to its end in 7-byte reads, counting bytes and lines |
| 2 | note read may return fewer bytes than asked, 0 at the end, or minus the errno: handle all three |
| 3 | note ---- output helpers: a function works on a global by naming it (a global is never an argument) |
| 4 | global ob uchar 32 |
| 5 | note outb: write ob[off .. off+n) to stdout; a short write continues, 0 or an error exits 90 |
| 6 | note bound: every pass writes at least one byte and n <= 32, so at most 32 passes |
| 7 | fn outb off ulong n ulong to void |
| 8 | e = add off n |
| 9 | p = off |
| 10 | while lt p e bound 32 |
| 11 | k = write 1 ob p sub e p |
| 12 | if le k 0 |
| 13 | exit 90 |
| 14 | end |
| 15 | p = add p ulong k |
| 16 | end |
| 17 | end |
| 18 | note putu: v in decimal, then a newline. A ulong has at most 20 digits, so 20 passes |
| 19 | fn putu v ulong to void |
| 20 | i = ulong 31 |
| 21 | put ob 31 10 |
| 22 | n = v |
| 23 | while true bound 20 |
| 24 | i = sub i 1 |
| 25 | put ob i uchar add rem n 10 48 |
| 26 | n = div n 10 |
| 27 | if eq n 0 |
| 28 | break |
| 29 | end |
| 30 | end |
| 31 | outb i sub 32 i |
| 32 | end |
| 33 | note putl: a signed value; -(v+1)+1 avoids negating the minimum, which would trap 1 |
| 34 | fn putl v long to void |
| 35 | if lt v 0 |
| 36 | put ob 0 45 |
| 37 | outb 0 1 |
| 38 | putu add ulong neg add v 1 1 |
| 39 | ret |
| 40 | end |
| 41 | putu ulong v |
| 42 | end |
| 43 | global buf uchar 7 |
| 44 | fn main to int |
| 45 | bytes = ulong 0 |
| 46 | lines = ulong 0 |
| 47 | sum = ulong 0 |
| 48 | note bound: every pass but the last reads at least one byte; this program accepts at most 65536 bytes |
| 49 | while true bound 65537 |
| 50 | k = read 0 buf 0 7 |
| 51 | if lt k 0 |
| 52 | exit 91 |
| 53 | end |
| 54 | if eq k 0 |
| 55 | break |
| 56 | end |
| 57 | n = ulong k |
| 58 | for i ulong n |
| 59 | c = get buf i |
| 60 | sum = add sum ulong c |
| 61 | if eq c 10 |
| 62 | lines = add lines 1 |
| 63 | end |
| 64 | end |
| 65 | bytes = add bytes n |
| 66 | end |
| 67 | putu bytes |
| 68 | putu lines |
| 69 | putu sum |
| 70 | ret 0 |
| 71 | end |