raz / commit ba7f6657

commit
ba7f6657325a8a39efeb71af7b40a2591c4d41b9
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
5d21612d
Rename jed to raz; add an ISC license

raz is Polish for one, as in counting. Every name moves: the compiler
./raz, src/raz.pas, the report doc/raz.md, the extension .raz, the vim
and emacs support (raz-mode). The author address in CLAUDE.md and PLAN.md
is now the GitHub noreply one.

patch · log

230 files changed, +5890 -5869

.gitignore (history) modified +1 -1

@@ -1,2 +1,2 @@
11 build/
2-/jed
2+/raz

CLAUDE.md modified +15 -14

@@ -1,13 +1,13 @@
1-# Working on jed
1+# Working on raz
22
3-Read `PLAN.md` (the plan, ground rules, steps) and `doc/jed.md` (the
3+Read `PLAN.md` (the plan, ground rules, steps) and `doc/raz.md` (the
44 language report) first. The report defines the language; where the
55 plan disagrees, the report wins and the plan is fixed.
66
77 ## Setup and checks
88
99 apt-get install -y fp-compiler # Free Pascal 3.2.2, if fpc is missing
10- make jed # the compiler, ./jed; its library is lib/
10+ make raz # the compiler, ./raz; its library is lib/
1111 make check # every example and test against its expected output
1212 make bench # must report at least 400,000 lines a second
1313 make loc # lines of the compiler; the code column is the budget
@@ -16,16 +16,16 @@
1616 make stress # 40,000 native threads; make check runs a small version
1717 make fmt # lib/, examples/ and tools/ are formatted
1818
19-`make check` also runs `tools/Doc.jed` and `tools/Pretty.jed`, the
19+`make check` also runs `tools/Doc.raz` and `tools/Pretty.raz`, the
2020 report's whole examples, each library module's own `main` (its test),
2121 and the vim and emacs support headless where they are installed
2222 (`apt-get install -y vim emacs-nox`): each example must indent back
2323 exactly as written.
2424
25-`make check` must pass before every commit. Tests: `test/run/X.jed`
25+`make check` must pass before every commit. Tests: `test/run/X.raz`
2626 with `X.expect` (stdout), optional `X.status` and `X.args`; modules they
27-import in `test/run/mods`. `test/err/X.jed` must fail to compile with
28-the text in `X.err`. `test/pretty/X.jed` must format to `X.expect`.
27+import in `test/run/mods`. `test/err/X.raz` must fail to compile with
28+the text in `X.err`. `test/pretty/X.raz` must format to `X.expect`.
2929 Examples in `examples/` work the same way.
3030
3131 ## How we work
@@ -34,21 +34,22 @@
3434 go-ahead; within it, one commit per step, pushed as it is done, then
3535 stop for review. Never start a stage, or change the report's
3636 language, without being asked.
37-- Language changes go into `doc/jed.md` first, for the owner to review,
37+- Language changes go into `doc/raz.md` first, for the owner to review,
3838 before any code.
39-- Commits: author `Luis <42945842+ldiaz94@users.noreply.github.com>`, unsigned
39+- Commits: author
40+ `Luis <42945842+ldiaz94@users.noreply.github.com>`, unsigned
4041 (`--no-gpg-sign`), no attribution trailer. Push to `main`. No pull
4142 requests unless asked.
4243 - Budget: about 5,000 lines of code (blank and comment lines not
43- counted), within 10%; at least 400,000 lines of jed a second.
44+ counted), within 10%; at least 400,000 lines of raz a second.
4445 - Style: clarity over cleverness; each unit opens with what it is, what
4546 it depends on and what it leaves out; comments say why. Match the
4647 report's plain, short prose in documentation.
4748
4849 ## Where things stand
4950
50-Steps 1-18 are done: the language, the tools (`tools/Doc.jed`, and
51-the formatter, `tools/Pretty.jed`, over the shared `tools/Scan.jed`),
51+Steps 1-18 are done: the language, the tools (`tools/Doc.raz`, and
52+the formatter, `tools/Pretty.raz`, over the shared `tools/Scan.raz`),
5253 `README.md` and the guide to the compiler, `doc/compiler.md`. Nothing
5354 further is planned; new work starts only on the owner's word. Keep
5455 `doc/compiler.md`'s table of lines and its routine names true when the
@@ -56,9 +57,9 @@
5657 for later at the owner's word: tagging versions, and a rewrite of var
5758 parameters.
5859
59-`test/libc` runs its programs over `lib/Sys.jed`, the C one, through
60+`test/libc` runs its programs over `lib/Sys.raz`, the C one, through
6061 a link in its `mods`. A test or example without `.expect` is only
61-compiled (`examples/Window.jed` needs a display).
62+compiled (`examples/Window.raz` needs a display).
6263
6364 ## Readings of the report already taken
6465

LICENSE (history) added +15 -0

@@ -0,0 +1,15 @@
1+ISC License
2+
3+Copyright (c) 2026 Luis Díaz
4+
5+Permission to use, copy, modify, and/or distribute this software for any
6+purpose with or without fee is hereby granted, provided that the above
7+copyright notice and this permission notice appear in all copies.
8+
9+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Makefile (history) modified +16 -16

@@ -1,11 +1,11 @@
1-# Builds the compiler, jed, from src/ into the repository's root; the
1+# Builds the compiler, raz, from src/ into the repository's root; the
22 # library it needs is lib/, beside it.
33
44 FPC = fpc
55 FPCFLAGS = -O2 -Mobjfpc -Sh- -vew -FUbuild
66
7-jed: src/*.pas | build
8- $(FPC) $(FPCFLAGS) -FE. -ojed src/jed.pas
7+raz: src/*.pas | build
8+ $(FPC) $(FPCFLAGS) -FE. -oraz src/raz.pas
99
1010 units: src/*.pas | build
1111 for u in scan sym x64 link elf; do $(FPC) $(FPCFLAGS) src/$$u.pas || exit 1; done
@@ -21,23 +21,23 @@
2121 mkdir -p build
2222
2323 clean:
24- rm -rf build jed
24+ rm -rf build raz
2525
2626 # every example and test, against what it should print
27-check: jed
27+check: raz
2828 test/check.sh
2929
3030 # line numbers: gdb stops at a line and names it
31-gdb: jed
31+gdb: raz
3232 test/gdb.sh
3333
3434 # the compiler's speed, on a generated program of about 350,000 lines,
3535 # the best of three runs; fails below 400,000 lines a second
36-bench: jed | build
37- python3 test/genbench.py 12000 > build/Bench.jed
38- @lines=$$(wc -l < build/Bench.jed); best=0; \
36+bench: raz | build
37+ python3 test/genbench.py 12000 > build/Bench.raz
38+ @lines=$$(wc -l < build/Bench.raz); best=0; \
3939 for i in 1 2 3; do \
40- start=$$(date +%s%N); ./jed build/Bench.jed || exit 1; end=$$(date +%s%N); \
40+ start=$$(date +%s%N); ./raz build/Bench.raz || exit 1; end=$$(date +%s%N); \
4141 t=$$((end - start)); if [ $$best = 0 ] || [ $$t -lt $$best ]; then best=$$t; fi; \
4242 done; \
4343 rate=$$((lines * 1000000000 / best)); \
@@ -47,16 +47,16 @@
4747 # native threads under load: 40,000 spawned and joined, 200 alive at a
4848 # time, all waiting on one Mutex; then, with little memory, spawn must
4949 # fail with Thread.Failed. make check runs a small version.
50-stress: jed | build
51- ./jed -o build/Stress lib/Thread.linux-x86_64.jed
50+stress: raz | build
51+ ./raz -o build/Stress lib/Thread.linux-x86_64.raz
5252 build/Stress 40000 200
5353 (ulimit -v 60000; build/Stress fail)
5454
55-# the formatter, tools/Pretty.jed: the library, examples and tools are
55+# the formatter, tools/Pretty.raz: the library, examples and tools are
5656 # formatted already
57-fmt: jed | build
58- ./jed -o build/Pretty tools/Pretty.jed
59- @fail=0; for f in lib/*.jed examples/*.jed tools/*.jed; do \
57+fmt: raz | build
58+ ./raz -o build/Pretty tools/Pretty.raz
59+ @fail=0; for f in lib/*.raz examples/*.raz tools/*.raz; do \
6060 build/Pretty $$f | cmp -s - $$f || { echo "not formatted: $$f"; fail=1; }; \
6161 done; test $$fail = 0
6262

PLAN.md (history) modified +29 -28

@@ -1,12 +1,12 @@
1-# jed: the plan
1+# raz: the plan
22
3-jed (Polish *jeden*, one) is a small systems language in Wirth's
3+raz (Polish for *one*, as in counting) is a small systems language in Wirth's
44 tradition: full control of memory, volatile access, atomics, calls into
55 C, generic modules. Its compiler is meant to be read in a long weekend:
66 under 5,000 lines of Free Pascal, one pass, no IR, no optimizer, writing
77 x86-64 machine code and the ELF file itself.
88
9-The language is defined by `doc/jed.md`. Where this plan and the report
9+The language is defined by `doc/raz.md`. Where this plan and the report
1010 disagree, the report wins and this plan is fixed.
1111
1212 ## Ground rules
@@ -16,14 +16,15 @@
1616 arrays or SysUtils.
1717 - The compiler stays near 5,000 lines of code (not counting blank and
1818 comment lines), within 10%, and compiles at least 400,000 lines of
19- jed a second, from reading the sources to writing the executable.
19+ raz a second, from reading the sources to writing the executable.
2020 `make loc` and `make bench` measure them, and a step that breaks
2121 either limit isn't done.
2222 - Clarity over cleverness. Every unit opens with a header comment: what
2323 it is, what it depends on, what it leaves out. Comments say why, and
2424 what wherever a layout or encoding isn't obvious.
25-- One commit per step, as `Luis <42945842+ldiaz94@users.noreply.github.com>`, unsigned, with
26- no attribution trailer.
25+- One commit per step, as
26+ `Luis <42945842+ldiaz94@users.noreply.github.com>`, unsigned,
27+ with no attribution trailer.
2728 - Work stops after every stage for review. A stage starts only on an
2829 explicit go-ahead; within it, each step is committed and pushed as it
2930 is done.
@@ -32,7 +33,7 @@
3233
3334 ## Decisions
3435
35-1. Source files end in `.jed`, one module per file, named after it.
36+1. Source files end in `.raz`, one module per file, named after it.
3637 2. "Not equal" is `#`.
3738 3. Every statement ends in `;`, including `end;` and `until x;`. Every
3839 match arm starts with `|`, the `else` arm too.
@@ -48,7 +49,7 @@
4849 per distinct list of arguments, its types and its procedures.
4950 8. Tree shaking: the linker keeps only the procedures, variables and
5051 literals reachable from the entry point.
51-9. Variadic arguments exist only to call C. jed code gets the same
52+9. Variadic arguments exist only to call C. raz code gets the same
5253 effect from a slice of a variant (`Fmt.print`).
5354 10. Strings are `[]U8`. The language compares them with `=`; the rest
5455 is a library.
@@ -67,14 +68,14 @@
6768 | `src/parse.pas` | 1,816 | 1,685 | Declarations, statements, expressions, built-ins |
6869 | `src/link.pas` | 131 | 95 | Tree shaking, layout, patching |
6970 | `src/elf.pas` | 424 | 350 | Static and dynamic ELF, symbol table, line numbers |
70-| `src/jed.pas` | 183 | 145 | The command line, the entry points |
71+| `src/raz.pas` | 183 | 145 | The command line, the entry points |
7172 | total | 5,704 | 4,954 | |
7273
7374 ## Steps
7475
7576 Stage 1: the core
7677
77-- [x] 1. Language report, `doc/jed.md`. Reviewed and approved before
78+- [x] 1. Language report, `doc/raz.md`. Reviewed and approved before
7879 any more code.
7980 - [x] 2. Scanner and symbol table, `scan.pas` and `sym.pas`, written
8081 against the report; they compile.
@@ -86,40 +87,40 @@
8687 enumerations and sets, record literals, `defer`, `NEW`, generic
8788 modules and `extern`. Module bodies, per-target modules and their
8889 interface check, and code procedures are in.
89-- [x] 6. `lib/Rt.jed`, `lib/Sys.linux-x86_64.jed`, `lib/Out.jed`;
90+- [x] 6. `lib/Rt.raz`, `lib/Sys.linux-x86_64.raz`, `lib/Out.raz`;
9091 examples (hello, args, variants and slices, volatile, a code
9192 procedure); `make check` runs them against expected output;
92- `make bench` times the compiler on generated jed.
93+ `make bench` times the compiler on generated raz.
9394
9495 Stage 2: the rest of the language
9596
9697 - [x] 7. Multiple results and errors; `INC` and `DEC`.
9798 - [x] 8. Enumerations and sets, record literals, `defer`; examples.
98-- [x] 9. `NEW`; `lib/Mem.jed`, `lib/Arena.jed`, `lib/Heap.jed`.
99+- [x] 9. `NEW`; `lib/Mem.raz`, `lib/Arena.raz`, `lib/Heap.raz`.
99100 - [x] 10. Generic modules, with type and procedure arguments;
100- `lib/Str.jed`, `lib/Buf.jed`, `lib/Fmt.jed`; examples.
101+ `lib/Str.raz`, `lib/Buf.raz`, `lib/Fmt.raz`; examples.
101102
102103 Stage 3: calling C, and what comes with it
103104
104105 - [x] 11. `extern proc`, `extern var` and `link`; dynamic ELF, start
105- through `__libc_start_main`. A plain `lib/Sys.jed` over the C
106+ through `__libc_start_main`. A plain `lib/Sys.raz` over the C
106107 library, the default for targets with no file of their own.
107108 Examples with `printf` to `stdout`, and an X11 window, reading
108109 `XEvent` as an array of words through pointer conversions.
109110 Ending a program: the entry point calls `Rt.exit(status)`, which
110111 runs the procedures registered with `Rt.atExit`, then ends it;
111- `Rt.fail` runs them too. A buffered `lib/Out.jed`: 4 KB, flushed
112+ `Rt.fail` runs them too. A buffered `lib/Out.raz`: 4 KB, flushed
112113 at each newline when standard output is a terminal, when full,
113114 by `Out.flush`, and at exit. The report says how to mix `Out`
114115 with C's `stdio`: flush one before using the other.
115116 - [x] 12. `F32`: arithmetic, conversions, calls; real literals become
116117 untyped constants that take `F32` or `F64`.
117-- [x] 13. A thread-safe `lib/Heap.jed`: its bad sizes refused, and a
118+- [x] 13. A thread-safe `lib/Heap.raz`: its bad sizes refused, and a
118119 marker in each block's header so that freeing a block twice, or
119120 one it never gave out, stops the program; `Out` locks its buffer.
120121 An example with threads from `pthread_create`.
121122 Native threads for programs without C, in
122- `lib/Thread.linux-x86_64.jed`: `spawn` on an `mmap`ed stack with
123+ `lib/Thread.linux-x86_64.raz`: `spawn` on an `mmap`ed stack with
123124 a guard page, through `clone` and a small code procedure; `join`
124125 and a `Mutex` through `futex`. `link static;` marks a module that
125126 needs a program without C; the compiler refuses a program that
@@ -131,22 +132,22 @@
131132
132133 - [x] 15. Versions first: the report says its version, by date
133134 (`2026-10.0`, then `.1` for the next change that month), and
134- ends with what each version changed; `jed --version` prints its
135- own and the report's, `jed 0.3.0, report 2026-10.0`. Each
135+ ends with what each version changed; `raz --version` prints its
136+ own and the report's, `raz 0.3.0, report 2026-10.0`. Each
136137 finished stage is tagged, `v0.3.0` for stage 3. Then
137- `tools/Doc.jed`, a jed program: prints a module's own
138+ `tools/Doc.raz`, a raz program: prints a module's own
138139 comment, the one before `module`, then its exported
139140 declarations, each with the comment just before it; and pulls
140- out the examples of `doc/jed.md` that are whole modules.
141+ out the examples of `doc/raz.md` that are whole modules.
141142 `make check` also compiles those examples, running the ones with
142143 a `main`, and runs each library module's `main` as its test.
143144 The test runner stays in the Makefile: it must work when the
144145 compiler doesn't. (Tagging is left for later, at the owner's
145146 word.)
146147
147-- [x] 16. Editor support: `editor/vim` (`syntax/jed.vim`, `indent/jed.vim`
148- by `shiftwidth()`, and `ftdetect/jed.vim`, which sets 4 spaces)
149- and `editor/emacs/jed-mode.el` (indenting by `jed-indent-offset`,
148+- [x] 16. Editor support: `editor/vim` (`syntax/raz.vim`, `indent/raz.vim`
149+ by `shiftwidth()`, and `ftdetect/raz.vim`, which sets 4 spaces)
150+ and `editor/emacs/raz-mode.el` (indenting by `raz-indent-offset`,
150151 4 unless set). Both colour reserved words, basic types, built-in
151152 procedures, numbers, characters, strings and nested comments.
152153 `make check` loads each, headless, on the examples. And a stress
@@ -163,10 +164,10 @@
163164
164165 Later
165166
166-- [x] 18. `tools/Pretty.jed`, a formatter that keeps every line break
167+- [x] 18. `tools/Pretty.raz`, a formatter that keeps every line break
167168 and comment where it is: it fixes indentation (4 spaces a level)
168169 and the spaces around operators and after `,` and `;`, and
169- leaves formatted code as it is. It shares with `Doc.jed` a
170- scanner that keeps comments, `tools/Scan.jed`. `make fmt` checks
170+ leaves formatted code as it is. It shares with `Doc.raz` a
171+ scanner that keeps comments, `tools/Scan.raz`. `make fmt` checks
171172 that `lib/`, `examples/` and `tools/` come through unchanged, and
172173 `make check` does too, with the cases in `test/pretty`.

README.md (history) modified +32 -28

@@ -1,7 +1,7 @@
1-# jed
1+# raz
22
3-jed (Polish *jeden*, one) is a small systems language in Wirth's
4-tradition, for x86-64 Linux. A jed program can lay a record over a
3+raz (Polish for *one*, as in counting) is a small systems language in Wirth's
4+tradition, for x86-64 Linux. A raz program can lay a record over a
55 device's registers, read and write memory exactly as written, take part
66 in lock-free algorithms, make system calls and call C libraries. It has
77 no garbage collector and no hidden run time: what the program does is
@@ -20,7 +20,7 @@
2020 ```
2121
2222 $ make
23- $ ./jed examples/Hello.jed
23+ $ ./raz examples/Hello.raz
2424 $ examples/Hello
2525 hello, world
2626
@@ -33,13 +33,13 @@
3333
3434 | Path | What |
3535 |---|---|
36-| `doc/jed.md` | The language report: the definition of jed |
36+| `doc/raz.md` | The language report: the definition of raz |
3737 | `doc/compiler.md` | A guide to reading the compiler, file by file |
3838 | `src/` | The compiler, in Free Pascal |
39-| `lib/` | The library, in jed; the compiler finds it beside itself |
39+| `lib/` | The library, in raz; the compiler finds it beside itself |
4040 | `examples/` | Small programs, each with the output it should give |
41-| `tools/Doc.jed` | Prints what a module exports, with its comments |
42-| `tools/Pretty.jed` | The formatter: fixes indentation and spacing |
41+| `tools/Doc.raz` | Prints what a module exports, with its comments |
42+| `tools/Pretty.raz` | The formatter: fixes indentation and spacing |
4343 | `editor/` | Support for vim and emacs |
4444 | `test/` | Tests, and the scripts that run them |
4545 | `PLAN.md` | How the compiler was built, step by step |
@@ -49,7 +49,7 @@
4949 The compiler needs Free Pascal 3.2.2 (`apt-get install fp-compiler`)
5050 and builds into the repository's root:
5151
52- make # ./jed
52+ make # ./raz
5353
5454 The tests need a shell and Python 3; the editor checks run if vim or
5555 emacs is installed.
@@ -57,25 +57,25 @@
5757 make check # every example and test, against what it should give
5858 make bench # the compiler's speed on a program of 350,000 lines
5959 make stress # 40,000 threads, started and joined
60- make gdb # gdb stops at a line of jed and names it
60+ make gdb # gdb stops at a line of raz and names it
6161 make fmt # the library, examples and tools are formatted
6262 make loc # the compiler's lines
6363 make tests # tests of the scanner, encoder and linker on their own
6464
6565 ## Using it
6666
67- jed [-I dir]... [-o file] Main.jed
68- jed run [-I dir]... Main.jed [arg]...
69- jed --version
67+ raz [-I dir]... [-o file] Main.raz
68+ raz run [-I dir]... Main.raz [arg]...
69+ raz --version
7070
71-`jed Main.jed` compiles module `Main` and every module it imports, and
72-writes the executable `Main`. A module `Name` lives in `Name.jed`, found
71+`raz Main.raz` compiles module `Main` and every module it imports, and
72+writes the executable `Main`. A module `Name` lives in `Name.raz`, found
7373 in the main module's directory, then in each `-I` directory, then in
7474 `lib`. A module whose code depends on the system comes in one file per
75-target, `Name.linux-x86_64.jed` before `Name.jed`; the compiler checks
75+target, `Name.linux-x86_64.raz` before `Name.raz`; the compiler checks
7676 that all of them export the same things.
7777
78-`jed run Main.jed a b` compiles the same way, then runs the program
78+`raz run Main.raz a b` compiles the same way, then runs the program
7979 with the arguments `a b`, writing no file: its output and exit status
8080 are the command's.
8181
@@ -102,40 +102,40 @@
102102 - `extern` procedures and variables from C; code procedures written as
103103 bytes of machine code; `SYSCALL`.
104104
105-The report, `doc/jed.md`, says all of it in about 900 lines.
105+The report, `doc/raz.md`, says all of it in about 900 lines.
106106
107107 ## The library
108108
109109 `Rt` (ending the program, checks), `Sys` (system calls), `Out`
110110 (buffered output), `C`, `Lock`, `Thread` (threads without C), `Mem`,
111111 `Heap`, `Arena`, `Str`, `Buf`, `Fmt`, `List(T)` and `Map(K, V; hash,
112-eq)`. `tools/Doc.jed` prints any of them:
112+eq)`. `tools/Doc.raz` prints any of them:
113113
114- $ ./jed -o Doc tools/Doc.jed && ./Doc lib/Str.jed
114+ $ ./raz -o Doc tools/Doc.raz && ./Doc lib/Str.raz
115115
116116 Each library module's `main` is its test, which `make check` runs.
117117
118118 ## Editors
119119
120120 `editor/vim` holds a syntax file, an indent file and file type
121-detection: add it to `runtimepath`. `editor/emacs/jed-mode.el` is a
122-major mode: put it on `load-path` and `(require 'jed-mode)`. Both
121+detection: add it to `runtimepath`. `editor/emacs/raz-mode.el` is a
122+major mode: put it on `load-path` and `(require 'raz-mode)`. Both
123123 colour the language and indent it as the examples are indented.
124124
125-`tools/Pretty.jed` formats a whole file the same way: it fixes the
125+`tools/Pretty.raz` formats a whole file the same way: it fixes the
126126 indentation, 4 spaces a level, and the spaces around operators and
127127 after `,` and `;`, and keeps every line break and comment where it is.
128128
129- $ ./jed -o Pretty tools/Pretty.jed
130- $ ./Pretty Module.jed # prints it, formatted
131- $ ./Pretty -w *.jed # rewrites those that aren't, and names them
129+ $ ./raz -o Pretty tools/Pretty.raz
130+ $ ./Pretty Module.raz # prints it, formatted
131+ $ ./Pretty -w *.raz # rewrites those that aren't, and names them
132132
133133 ## Versions
134134
135135 The compiler says which version of the report it follows:
136136
137- $ ./jed --version
138- jed 0.3.0, report 2026-10.0
137+ $ ./raz --version
138+ raz 0.3.0, report 2026-10.0
139139
140140 A version of the report is named by its month and a count; the report's
141141 last section says what each version changed.
@@ -145,3 +145,7 @@
145145 Other systems and processors (Mach-O, PE, aarch64), an optimizer,
146146 separate compilation, records passed to C by value, thread-local
147147 variables, and type information for debuggers.
148+
149+## License
150+
151+ISC; see `LICENSE`.

doc/compiler.md (history) modified +14 -14

@@ -1,9 +1,9 @@
1-# Reading the jed compiler
1+# Reading the raz compiler
22
33 The compiler is eight files of Free Pascal, under 5,000 lines of code.
44 This guide walks through them in the order they are best read: from the
55 characters of a source file to the bytes of an executable. It assumes
6-you know the language from `doc/jed.md`, and enough x86-64 to read a
6+you know the language from `doc/raz.md`, and enough x86-64 to read a
77 disassembly.
88
99 | File | Lines | Code | What |
@@ -15,7 +15,7 @@
1515 | `src/parse.pas` | 1,816 | 1,685 | Declarations, statements, expressions, built-ins |
1616 | `src/link.pas` | 131 | 95 | Tree shaking, layout, patching |
1717 | `src/elf.pas` | 425 | 351 | Static and dynamic ELF, symbol table, line numbers |
18-| `src/jed.pas` | 214 | 169 | The command line, the entry points |
18+| `src/raz.pas` | 214 | 169 | The command line, the entry points |
1919
2020 Every file opens with a comment that says what it is, what it depends
2121 on and what it leaves out. Read those first; they are the map.
@@ -47,20 +47,20 @@
4747
4848 ## Following one program
4949
50-`jed Hello.jed` does this:
50+`raz Hello.raz` does this:
5151
52-1. `jed.pas` reads the command line and calls `CompileMain`
52+1. `raz.pas` reads the command line and calls `CompileMain`
5353 (`parse.pas`).
5454 2. `CompileMain` imports `Rt` first, since every program needs it, and
55- then compiles `Hello.jed` with `CompileFile`.
55+ then compiles `Hello.raz` with `CompileFile`.
5656 3. `CompileFile` opens the file in the scanner and parses the module.
57- At `import Out;` it calls `ImportModule`, which finds `Out.jed` and
57+ At `import Out;` it calls `ImportModule`, which finds `Out.raz` and
5858 compiles it there and then, saving and restoring the scanner and the
5959 scopes around it. So modules are finished in an order where each
6060 comes after those it imports; that is the order their bodies run.
6161 4. Each procedure becomes a chunk of code; `Out.str("hello, world\n")`
6262 becomes a string chunk, a call, and a fixup to `Out.str`'s chunk.
63-5. Back in `jed.pas`, `Use` marks the modules the program uses; the
63+5. Back in `raz.pas`, `Use` marks the modules the program uses; the
6464 entry point, `_start`, is written as one more chunk: save `argc` and
6565 `argv`, call every used module's body, call `main`, call `Rt.exit`.
6666 6. `WriteElf` (`elf.pas`) has `link.pas` mark what `_start` reaches,
@@ -325,9 +325,9 @@
325325 compile unit gdb needs to find it. There are no types or variables in
326326 it; gdb can stop at a line and show where it is, not print a variable.
327327
328-## jed.pas: the command line
328+## raz.pas: the command line
329329
330-`jed.pas` parses the arguments, calls `CompileMain`, and works out what
330+`raz.pas` parses the arguments, calls `CompileMain`, and works out what
331331 the program uses: `Use` marks the modules imported from the main module
332332 and `Rt`; `UsesC` decides whether the program is dynamic, refusing one
333333 that both uses C and has a module saying `link static`. Then it writes
@@ -336,9 +336,9 @@
336336 start-up does, which sets C up and calls back a `main` that runs the
337337 module bodies and the program's `main`.
338338
339-`jed run` writes the executable to a memfd, a file only in memory, and
340-executes it through `/proc/self/fd` in jed's own place, handing it the
341-rest of jed's `argv`. Nothing is left on disk, and the program's
339+`raz run` writes the executable to a memfd, a file only in memory, and
340+executes it through `/proc/self/fd` in raz's own place, handing it the
341+rest of raz's `argv`. Nothing is left on disk, and the program's
342342 status is the command's.
343343
344344 ## Where to start changing it
@@ -351,6 +351,6 @@
351351 in the same order), a case in `Statement`, and a routine beside the
352352 others.
353353 - **A check that fails:** `Check` in `gen.pas`, and the message in
354- `lib/Rt.jed`'s `fail`.
354+ `lib/Rt.raz`'s `fail`.
355355
356356 After any change: `make check`, `make bench`, `make loc`.

doc/jed.md deleted +0 -907

@@ -1,907 +0,0 @@
1-# The programming language jed
2-
3-jed is a small systems language for x86-64 Linux. A jed program can lay
4-a record over a device's registers, read and write memory exactly as
5-written, take part in lock-free algorithms, make system calls and call
6-C libraries. It has no garbage collector and no hidden run time: what
7-the program does is what its text says.
8-
9-This report defines the language. It is short on purpose. Whatever it
10-doesn't allow, jed doesn't have.
11-
12-This is version 2026-10.0 of the report; section 12 says what each
13-version changed.
14-
15-## 1. A first look
16-
17-```
18-module Hello;
19-import Out;
20-
21-proc main*;
22-begin
23- Out.str("hello, world\n");
24-end;
25-
26-end Hello.
27-```
28-
29-A program is a set of modules. The one named on the command line is
30-the main module, and it exports a procedure `main`; the program starts
31-there, once every module's body has run (section 3). Saved as
32-`Hello.jed`, it is compiled with `jed Hello.jed`, which writes the
33-executable `Hello`.
34-
35-## 2. Words and symbols
36-
37-A program is written in UTF-8. The compiler rejects a file that isn't
38-valid UTF-8: a malformed or overlong sequence, a surrogate, or a code
39-point beyond 10FFFFH. Everything outside strings, characters and
40-comments is ASCII. Spaces, tabs and line breaks separate symbols and
41-are otherwise ignored.
42-
43-**Identifiers** are an ASCII letter or `_` followed by letters, digits
44-and `_`, up to 63 characters. Case matters: `count` and `Count` are different
45-names.
46-
47-**Reserved words** are lowercase, except `VOLATILE`:
48-
49-```
50-and begin break by code const defer div do else elsif end extern for
51-forward if import in link match mod module not of or packed proc record
52-repeat return set shl shr then to type until var variant VOLATILE while
53-xor
54-```
55-
56-**Numbers.** `123` is decimal. `0FFH` is hexadecimal: it starts with a
57-digit and ends in `H`. `1.5` and `2.0E-3` are reals; a real always has
58-a digit on both sides of its point.
59-
60-An integer is an untyped constant, which takes the type it is used as,
61-up to the largest `I64`. A hexadecimal number above that, such as
62-`0FFFFFFFFFFFFFFFFH`, has type `U64`: so `-1` never fits a `U64`, and
63-the big number goes nowhere else without a conversion.
64-
65-A real is an untyped constant too, which takes `F32` or `F64`,
66-whichever it is used as, rounded to the nearest value of that type;
67-where nothing says which, it is an `F64`. A real never becomes an
68-integer, nor an integer a real, without a conversion: `x := 1;` is an
69-error for `x: F64`, and `x := 1.0;` is right.
70-
71-**Characters.** `'a'` is the code point of one character, an integer:
72-`'a'` is 97 and `'é'` is 233.
73-
74-**Strings.** `"héllo\n"` is a sequence of bytes, the UTF-8 of its text:
75-`"é"` is the two bytes 0C3H, 0A9H. Both characters and strings take the
76-escapes `\n` (line feed), `\t` (tab), `\r` (carriage return), `\0`
77-(zero), `\\`, `\'`, `\"`, `\u{H...}` (the code point with hexadecimal
78-value H..., in a string its UTF-8) and, in strings only, `\xHH` (the
79-byte with hexadecimal value HH, which needn't make valid UTF-8).
80-
81-Error messages give the line and the column, counted in characters.
82-
83-**Comments** are `(*` ... `*)` and nest. By convention, the comment
84-just before an exported declaration is its documentation, and the one
85-before `module` is the module's.
86-
87-**Operators and delimiters:**
88-
89-```
90-+ - * / = # < <= > >= := : ; , . .. ... ( ) [ ] { } ^ |
91-```
92-
93-## 3. Modules
94-
95-```
96-Module = "module" ident [ "(" ModParams ")" ] ";"
97- { Import } { Link } { Declaration }
98- [ "begin" Statements ] "end" ident "." .
99-ModParams = ident { "," ident } { ";" ident ":" "proc" Signature } .
100-Import = "import" ImportItem { "," ImportItem } ";" .
101-ImportItem = ident [ ":=" ident [ "(" Type { "," Type } ")" ] ] .
102-Link = "link" ( string | "static" ) ";" .
103-```
104-
105-A module lives in a file of its own name: module `Out` is `Out.jed`.
106-The name after `end` repeats the module's name.
107-
108-**Exports.** A name declared at the top of a module with `*` after it
109-is exported: other modules can use it as `Module.name`. Record fields
110-are exported the same way. Everything else is private to the module.
111-
112-**Imports.** `import Out;` makes `Out`'s exports available as `Out.x`.
113-`import O := Out;` uses the name `O` instead. A module can't import
114-itself, directly or through others.
115-
116-**Generic modules** take types as parameters:
117-
118-```
119-module List(T);
120-type
121- Node* = record next*: ^Node; val*: T; end;
122-...
123-end List.
124-```
125-
126-An import gives the arguments: `import Ints := List(I64);`. Each
127-distinct list of arguments makes one *instance*: the module compiled
128-with `T` standing for `I64`. Two imports of `List(I64)`, in any modules,
129-share one instance. Since every instance is checked on its own, an
130-operation the argument type doesn't support (adding two records, say)
131-is reported as an error in that instance.
132-
133-What a generic module needs to do with its types, beyond moving them
134-about, it is given as procedures, after the types:
135-
136-```
137-module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL);
138-```
139-
140-```
141-import Names := Map([]U8, I64, Str.hash, Str.eq);
142-```
143-
144-A procedure argument names a procedure, not a variable or an
145-expression, and its signature, with the type arguments put in, must be
146-the parameter's. Inside the module, `hash(k)` calls it directly. Two
147-imports make the same instance only if their types and their procedures
148-are the same.
149-
150-**Finding modules.** The compiler looks for module `Name` in the main
151-module's directory, then in each directory given with `-I`, then in the
152-`lib` directory beside the compiler. In each directory it takes the
153-first of `Name.OS-ARCH.jed`, `Name.OS.jed`, `Name.ARCH.jed` and
154-`Name.jed` that exists, where `OS-ARCH` is the target, for now only
155-`linux-x86_64`. So a module whose code depends on the machine or the
156-system comes in one file per target, and the modules that import it
157-don't change. Machine code (section 8) and system calls belong in such
158-files.
159-
160-The compiler holds every file of such a module to the same interface.
161-When it takes one of `Name.*.jed`, it also reads the declarations of
162-the others beside it, and of `Name.jed` if there is one, and reports an
163-error unless they all export the same names, each the same kind of
164-thing:
165-
166-- a constant of the same type (its value may differ: a system call
167- number, say);
168-- a type of the same kind, and for a record or variant the same
169- exported fields and cases, with the same types (unexported fields,
170- and so the size and layout, may differ);
171-- a variable of the same type;
172-- a procedure of the same signature.
173-
174-Two types here are the same if they are built alike, a name in one file
175-standing for the same name in another.
176-
177-**Module bodies.** A module may end with `begin` and statements, its
178-body. Every module's body runs once, before the main module's `main`:
179-a module's body runs after the bodies of the modules it imports, in the
180-order of its `import`s, and once however many modules import it. Each
181-instance of a generic module has its body run once. Module variables
182-are zero before any body runs. `return;` ends a body early.
183-
184-**`link "libX11.so.6";`** names a shared library to load at run time,
185-for the `extern` declarations of section 9. **`link static;`** says the
186-module needs a program without C (section 10): it makes its own system
187-calls, or its own threads, which the C library wouldn't know about.
188-
189-## 4. Declarations
190-
191-```
192-Declaration = "const" { IdentDef [ ":" "ERROR" ] "=" Expr ";" }
193- | "type" { IdentDef "=" Type ";" }
194- | "var" { IdentList ":" Type ";" }
195- | ProcDeclaration ";"
196- | ExternDeclaration ";" .
197-IdentDef = ident [ "*" ] .
198-IdentList = IdentDef { "," IdentDef } .
199-```
200-
201-A name must be declared before it is used, with two exceptions: the
202-base type of a pointer may name a type declared later in the same
203-`type` section (so that two records can point at each other), and a
204-procedure may be declared `forward` and defined later (section 8).
205-
206-**Constants** are evaluated by the compiler. Their expressions use only
207-literals, other constants, operators, `SIZE` and the `LEN` of arrays.
208-
209-**Variables** of a module live as long as the program; variables of a
210-procedure live as long as its call. Both start at zero: every byte of
211-them is zero. So a number starts as `0` (`0.0` for `F32` and `F64`),
212-a `BOOL` as `false`, a pointer, procedure or `ERROR` as `nil`, a slice
213-as the empty slice (`ptr` is `nil`, `len` is 0), a variant as its
214-first case with its fields zero, a set as the empty set, and an
215-enumeration as its first name. No variable is ever read before it has a value.
216-
217-## 5. Types
218-
219-```
220-Type = QualIdent
221- | "[" Expr "]" Type (* array *)
222- | "[" "]" Type (* slice *)
223- | "^" [ "VOLATILE" ] Type (* pointer *)
224- | [ "packed" ] "record" { IdentList ":" Type ";" } "end"
225- | "variant" { Case ";" } "end"
226- | "(" ident { "," ident } ")" (* enumeration *)
227- | "set" "of" QualIdent
228- | "proc" Signature .
229-Case = ident [ "(" FieldList { ";" FieldList } ")" ] .
230-FieldList = ident { "," ident } ":" Type .
231-QualIdent = [ ident "." ] ident .
232-```
233-
234-### 5.1 Basic types
235-
236-| Type | Size | Values |
237-|---|---|---|
238-| `I8` `I16` `I32` `I64` | 1, 2, 4, 8 | signed integers, two's complement |
239-| `U8` `U16` `U32` `U64` | 1, 2, 4, 8 | unsigned integers |
240-| `BOOL` | 1 | `false` (0), `true` (1) |
241-| `F32` | 4 | IEEE 754 single precision |
242-| `F64` | 8 | IEEE 754 double precision |
243-
244-### 5.2 Arrays
245-
246-`[n]T` is `n` elements of type `T`, one after another. `n` is a
247-constant greater than zero. Arrays are values: assigning one copies it.
248-
249-### 5.3 Slices
250-
251-`[]T` is a view of elements that live elsewhere: a pointer to the first
252-and a count, 16 bytes in all.
253-
254-```
255-Slice = record ptr: ^T; len: I64; end; (* its layout *)
256-```
257-
258-A slice is made from an array (`a[2..5]`, or an array used where a
259-slice is wanted), from another slice, or from a pointer (`p[0..n]`). It
260-doesn't own what it points at.
261-
262-### 5.4 Pointers
263-
264-`^T` is the address of a `T`, 8 bytes. `nil` is the pointer to nothing.
265-
266-`^VOLATILE T` is the address of a `T` that something besides the
267-program may read or change: a device register, memory shared with
268-another process. Section 7.6 says what that promises.
269-
270-### 5.5 Records
271-
272-```
273-type Cell = record ch: U8; attr: U8; end;
274-```
275-
276-Fields are laid out in order as C lays them out: each at the next
277-multiple of its own alignment, and the whole record padded to a
278-multiple of its largest alignment. A record declared like a C struct
279-has the same layout as that struct.
280-
281-A `packed record` has no padding: each field starts at the byte after
282-the field before it, and the record's alignment is 1. A field of a
283-packed record may be misaligned. x86-64 reads and writes it anyway, but
284-an atomic operation on it is slow, and a volatile access to it is one
285-instruction that needn't be atomic.
286-
287-### 5.6 Variants
288-
289-A variant holds one of several cases, each with its own fields:
290-
291-```
292-type
293- Shape* = variant
294- circle(r: F64);
295- rect(w, h: F64);
296- dot;
297- end;
298-```
299-
300-The case names are declared in the scope around the type, so `circle`
301-can be used directly, and as `Shapes.circle` from another module if
302-`Shape` is exported. A case with fields is built by calling it like a
303-procedure, `circle(2.0)`; a case without fields is just `dot`. The only
304-way to read the fields is `match` (section 7.4).
305-
306-Layout: an `I64` tag (0 for the first case, 1 for the second, and so
307-on) followed by the fields of the largest case, laid out as a record.
308-A variant that starts at zero therefore holds its first case.
309-
310-### 5.7 Enumerations and sets
311-
312-```
313-type
314- Color* = (red, green, blue);
315- Colors* = set of Color;
316-```
317-
318-An enumeration is a list of names, in order. Like the cases of a
319-variant, the names are declared in the scope around the type. An
320-enumeration has at most 256 names and takes 1 byte; the first name is
321-0, the next 1, and so on.
322-
323-`set of E`, for an enumeration `E` of at most 64 names, holds any
324-choice of `E`'s names: bit `i` stands for the name at position `i`. It
325-takes the smallest of 1, 2, 4 and 8 bytes that has a bit for each name,
326-so a set can stand for a C flags word.
327-
328-### 5.8 Errors
329-
330-```
331-const NotFound*: ERROR = "not found";
332-```
333-
334-`ERROR` is a basic type of 8 bytes. A value of it is made only by a
335-constant declared as above, and each such declaration makes an error
336-different from every other, whatever its message: two modules that
337-both declare `"not found"` have two different errors. A generic module
338-makes its errors once per instance. `nil` is no error.
339-
340-Errors compare with `=` and `#` only, by which declaration made them,
341-never by their message. `MSG(e)` is the message, a `[]U8`; `MSG(nil)`
342-is `""`.
343-
344-```
345-proc find*(key: I64): (^Node, ERROR);
346-...
347-n, err := Table.find(7);
348-if err = Table.NotFound then ... end;
349-```
350-
351-### 5.9 Procedure types
352-
353-```
354-type Compare = proc(a, b: I64): BOOL;
355-```
356-
357-A value of a procedure type is the address of a procedure with that
358-signature, 8 bytes, or `nil`.
359-
360-### 5.10 Same and assignable
361-
362-Two named types are the same only if they are the same declaration.
363-Two anonymous types are the same if they are built alike: `^I64` is
364-`^I64` wherever it is written. A named and an anonymous type are the
365-same if the named one is built like the anonymous one, so that
366-`p := ADR(n)` works for `p: NodePtr` with `type NodePtr = ^Node`.
367-
368-A type declared with only a name on the right, `type Count = I64;`, is
369-another name for that type, not a new one.
370-
371-A value of type `A` can be assigned to a variable of type `B` (and
372-passed to a parameter of type `B`, and returned as a `B`) if they are
373-the same type, or if:
374-
375-- `A` is an integer constant whose value fits in the integer type `B`;
376-- `A` is `nil` and `B` is a pointer, procedure or `ERROR` type;
377-- `A` is `^T` and `B` is `^VOLATILE T`;
378-- `A` is `[n]T` and `B` is `[]T`;
379-- `A` is a string literal and `B` is `[]U8`, `^U8` (a pointer to the
380- bytes followed by a zero byte, as C wants), or `[n]U8` with `n` at
381- least the string's length (the rest is zero);
382-- `A` is a procedure and `B` a procedure type with the same signature.
383-
384-Nothing else converts silently. In particular, there is no conversion
385-between integer types, between integers and reals, or between `F32`
386-and `F64`, without a written conversion (section 6.7).
387-
388-## 6. Expressions
389-
390-```
391-Expr = SimpleExpr [ Relation SimpleExpr ] .
392-Relation = "=" | "#" | "<" | "<=" | ">" | ">=" | "in" .
393-SimpleExpr = [ "-" ] Term { AddOp Term } .
394-AddOp = "+" | "-" | "or" | "xor" .
395-Term = Factor { MulOp Factor } .
396-MulOp = "*" | "/" | "div" | "mod" | "and" | "shl" | "shr" .
397-Factor = number | char | string | Designator | "(" Expr ")"
398- | "not" Factor
399- | "[" [ Expr { "," Expr } ] "]"
400- | "{" [ Element { "," Element } ] "}"
401- | "^" [ "VOLATILE" ] Type "(" Expr ")" .
402-Element = Expr | ident ":" Expr .
403-Designator = QualIdent { Selector } .
404-Selector = "." ident | "^" | "[" Expr [ ".." Expr ] "]"
405- | "(" [ Expr { "," Expr } ] ")" .
406-```
407-
408-The operators bind in the order of the grammar: `not` most tightly,
409-then the multiplying operators, then the adding ones, then the
410-relations. So `a + b * c = d` is `(a + (b * c)) = d`. A unary minus
411-applies to the first term: `-a * b` is `-(a * b)`.
412-
413-### 6.1 Integers
414-
415-Both operands of `+ - * div mod and or xor` have the same integer
416-type, or one is an untyped constant that takes the other's type. The
417-result has that type and wraps around at its width: in `U8`,
418-`200 + 100` is `44`.
419-
420-`div` rounds toward zero and `mod` takes the sign of the dividend, as
421-in C: `-7 div 2` is `-3`, `-7 mod 2` is `-1`. Dividing by zero, and
422-dividing the smallest `I64` by `-1`, stop the program (`SIGFPE`).
423-
424-`and`, `or`, `xor` and `not` work on every bit. `x shl n` and
425-`x shr n` shift by `n and 63`; `shr` brings in copies of the sign bit
426-for signed types and zeros for unsigned ones.
427-
428-Relations compare as signed or unsigned according to the type.
429-
430-### 6.2 Booleans
431-
432-`and` and `or` on `BOOL` evaluate their right operand only when it
433-decides the result. `not` negates, `xor` is "different", and `=` and
434-`#` compare.
435-
436-### 6.3 Reals
437-
438-`+ - * /` and the relations work on `F32` and on `F64`. Both operands
439-have the same type, or one is a real constant, which takes the other's
440-type (section 2). The result has that type: `F32` arithmetic is done in
441-single precision, rounded at each step as C rounds `float`. A
442-constant expression of reals is evaluated in double precision, then
443-rounded once to the type it takes.
444-
445-### 6.4 Pointers
446-
447-- `p^` is the variable `p` points at.
448-- `p + i` and `p - i`, with `i` an integer, move `p` by `i` elements:
449- by `i * SIZE(T)` bytes for `p: ^T`.
450-- `p - q`, with both of the same pointer type, is the number of
451- elements between them, an `I64`.
452-- `p[i]` is `(p + i)^`. `p[lo..hi]` is the slice of the `hi - lo`
453- elements from `p + lo`. Neither is checked. A pointer to an array
454- isn't indexed this way, since a step would be a whole array: its
455- elements are `p^[i]`.
456-- Pointers compare with `= # < <= > >=` as unsigned addresses.
457- Procedure values compare with `=` and `#` only.
458-
459-### 6.5 Arrays and slices
460-
461-`a[i]` is an element of an array or slice, and `a[lo..hi]` is the slice
462-of the elements from `lo` up to but not including `hi`. Both are
463-checked: `i` must be below the length, and `0 <= lo <= hi <= length`.
464-A check that fails prints the file and line to standard error and stops
465-the program with status 2.
466-
467-**Literals.** `[e1, e2, ...]` builds an array, and `{f: e, g: e, ...}`
468-a record, where the type it must have is known: assigned to a variable,
469-passed to a parameter, returned, compared with a value of that type, or
470-an element of a bigger literal. The elements must be assignable to the
471-element type, and an array literal for `[n]T` has exactly `n` of them.
472-A record literal names its fields, in any order, each at most once; the
473-fields it leaves out are zero. An array literal used as a slice is a
474-hidden variable of the procedure, and lives as long as its call.
475-
476-```
477-c := {ch: 'A', attr: 7};
478-Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)]);
479-```
480-
481-**Strings compare.** Two operands that are each a `[]U8`, a `[n]U8` or
482-a string literal are `=` when they have the same length and the same
483-bytes, and `#` otherwise. Other arrays and slices, records and variants
484-can't be compared; write a loop. Ordering strings is the library's
485-`Str.cmp`.
486-
487-### 6.6 Enumerations and sets
488-
489-Enumerations compare with all six relations, by position, and an
490-enumeration can be the variable of a `for` loop and the expression of a
491-`match` (section 7.4).
492-
493-`{red, blue}` is a set, of the set type of its names' enumeration;
494-`{}` is the empty set, where the type it must have is known. On two sets
495-of the same type, `+` is union, `*` intersection and `-` difference;
496-`=` and `#` compare, and `<=` and `>=` are "is a subset of" and "is a
497-superset of". `x in s` is `true` if the name `x` is in the set `s`.
498-
499-### 6.7 Conversions
500-
501-A type name applied like a procedure converts: `I32(x)`, `F64(n)`,
502-`^Cell(addr)`. A pointer type written out uses the `^` form of the
503-grammar: `^VOLATILE U32(0FEE00000H)`.
504-
505-| From | To | Result |
506-|---|---|---|
507-| integer | integer | the value cut to the new width, or extended by its sign (signed) or zeros (unsigned) |
508-| integer | `F32`, `F64` | the nearest real |
509-| `F32`, `F64` | integer | rounded toward zero; a NaN, or a real out of the range of `I64`, gives the smallest `I64`, then cut |
510-| `F32` | `F64` | the same value |
511-| `F64` | `F32` | the nearest `F32`; too big a value gives an infinity |
512-| enumeration | integer | its position |
513-| integer | enumeration | the name at that position; a position out of range is a failed check (6.5) |
514-| set | integer | its bits |
515-| integer | set | the low bits, as many as the set has |
516-| integer | pointer, procedure | the address |
517-| pointer, procedure | integer | the address |
518-| pointer, procedure | pointer, procedure | the same address, seen as the new type |
519-
520-### 6.8 Built-in procedures
521-
522-| Call | Result |
523-|---|---|
524-| `SIZE(T)` | the size of type `T` in bytes, a constant |
525-| `ADR(x)` | the address of variable `x`, a `^T` |
526-| `LEN(a)` | the number of elements of an array (a constant) or a slice, an `I64` |
527-| `NEW(p, a)` | sets `p: ^T` to a fresh, zeroed `T` from the allocator `a: ^Mem.Allocator`, or to `nil` if `a` has no room |
528-| `MSG(e)` | the message of the error `e`, a `[]U8` |
529-| `SYSCALL(n, x1, ..., x6)` | Linux system call `n` with up to six integer or pointer arguments; the raw result, an `I64` (a negative number is `-errno`) |
530-| `INC(v)`, `INC(v, k)` | adds 1, or `k`, to the integer variable `v`; it wraps, like `+` |
531-| `DEC(v)`, `DEC(v, k)` | subtracts 1, or `k`, from `v` |
532-| `FENCE` | a full memory barrier |
533-| `CAS(p, old, new)` | if `p^ = old`, sets `p^ := new` and returns `true`; atomically |
534-| `XCHG(p, x)` | sets `p^ := x` and returns the value before, atomically |
535-| `XADD(p, x)` | adds `x` to `p^` and returns the value before, atomically |
536-| `ARGC()` | the number of command line arguments, an `I64` |
537-| `ARGV()` | the arguments, a `^^U8` (C strings) |
538-
539-`SYSCALL` exists only on Linux targets. Other systems have no stable
540-system call interface, and their modules call the C library instead
541-(section 9).
542-
543-`INC` and `DEC` evaluate `v` once, so `INC(a[f(i)])` calls `f` once. They
544-read `v` and then write it: two accesses, even through a `^VOLATILE`
545-pointer, and not atomic; `XADD` is the atomic one.
546-
547-For `CAS`, `XCHG` and `XADD`, `p` is a `^T` or `^VOLATILE T` where `T`
548-is an 8-byte integer or pointer type (an integer type for `XADD`). They
549-are sequentially consistent.
550-
551-## 7. Statements
552-
553-```
554-Statements = { Statement ";" } .
555-Statement = Designator [ ":=" Expr ]
556- | Designator "," Designator { "," Designator } ":=" Expr
557- | "if" Expr "then" Statements
558- { "elsif" Expr "then" Statements } [ "else" Statements ] "end"
559- | "while" Expr "do" Statements "end"
560- | "repeat" Statements "until" Expr
561- | "for" ident ":=" Expr "to" Expr [ "by" Expr ] "do" Statements "end"
562- | "match" Expr "of" { "|" Arm } "end"
563- | "return" [ Expr { "," Expr } ]
564- | "break"
565- | "defer" Statement .
566-Arm = ( ident [ "(" ident { "," ident } ")" ] | "else" ) ":" Statements .
567-```
568-
569-Every statement ends in `;`, including the ones that end in `end` or
570-`until`.
571-
572-### 7.1 Assignment and calls
573-
574-`x := e` evaluates `e` and stores it in `x`; arrays, records, slices and
575-variants are copied. A designator on its own is a call, and any result
576-it returns is dropped: `Out.ln;`, `write(fd, buf);`.
577-
578-`a, b := f(x);` assigns the results of a procedure that returns several
579-(section 8), in order.
580-
581-### 7.2 Conditions and loops
582-
583-`if`, `while` and `repeat` take `BOOL` expressions. `repeat` runs its
584-body at least once and stops when the condition is true.
585-
586-`for i := a to b by s do ... end;` sets the integer variable `i` to `a`,
587-`a + s`, ... while `i <= b` (or `i >= b` if the constant `s` is
588-negative). `s` is 1 if left out. `b` is evaluated once, before the
589-first round.
590-
591-`break` ends the innermost `while`, `repeat` or `for` it stands in,
592-and the program goes on after it. There is no `goto`.
593-
594-### 7.3 Return
595-
596-`return e;` ends the procedure with the result `e`; `return a, b;` with
597-several results; `return;` from a procedure without results. A
598-procedure with results that runs off its end returns zeros, each result
599-as a variable of its type starts (section 4).
600-
601-### 7.4 Match
602-
603-```
604-match s of
605-| circle(r): area := 3.14159 * r * r;
606-| rect(w, h): area := w * h;
607-| dot: area := 0.0;
608-end;
609-```
610-
611-`match` runs the arm of the case `s` holds. An arm may name the case's
612-fields, in order, all of them; the names stand for those fields of `s`
613-itself, so assigning to one changes `s`. An arm may also leave the
614-fields unnamed. Every case must have an arm, unless there is an
615-`| else:` arm, which must come last.
616-
617-`match` on an enumeration works the same way: each arm names one of the
618-enumeration's names.
619-
620-### 7.5 Order of evaluation
621-
622-Operands, arguments and the designators of an assignment are evaluated
623-from left to right.
624-
625-### 7.6 Volatile
626-
627-A variable reached through a `^VOLATILE T` is volatile, and so is any
628-field or element of it. Each read or write of a volatile variable of a
629-basic, enumeration, set or pointer type is exactly one memory access,
630-of exactly its size, and volatile accesses happen in the order the
631-program writes them. Copying a whole record or array through a
632-volatile pointer is not allowed, since it can't be one access.
633-
634-A `^VOLATILE T` doesn't convert to `^T` without a written conversion.
635-
636-`FENCE` also orders the program's ordinary accesses against those of
637-other processors and devices.
638-
639-### 7.7 Defer
640-
641-`defer s;` runs the statement `s` when the program leaves the statement
642-list the `defer` stands in: at its end, or by a `return`, or by a
643-`break` out of it. Statements deferred in the same list run in the
644-opposite order to their `defer`s, and only those whose `defer` has been
645-reached run.
646-
647-```
648-module Head;
649-import Sys, Out;
650-
651-(* Prints the first line of the file at path. *)
652-proc head(path: []U8): BOOL;
653-var fd, n, i: I64; buf: [256]U8;
654-begin
655- fd := Sys.openRead(path);
656- if fd < 0 then return false; end;
657- defer Sys.close(fd);
658- n := Sys.read(fd, buf);
659- if n < 0 then return false; end;
660- for i := 0 to n - 1 do
661- if buf[i] = 10 then n := i; break; end;
662- end;
663- Out.str(buf[0..n]);
664- Out.ln;
665- return true;
666-end;
667-
668-proc main*;
669-begin
670- if not head("/etc/hostname") then Out.str("no hostname\n"); end;
671-end;
672-
673-end Head.
674-```
675-
676-`return e;` evaluates `e` before the deferred statements run. A
677-deferred statement can't contain `return`, `break` or `defer` that
678-would leave it.
679-
680-## 8. Procedures
681-
682-```
683-ProcDeclaration = "proc" IdentDef Signature ";"
684- ( "forward" | { LocalDeclaration } "begin" Statements "end" [ ident ]
685- | "code" Expr { "," Expr } ) .
686-LocalDeclaration = "const" { ident [ ":" "ERROR" ] "=" Expr ";" }
687- | "type" { ident "=" Type ";" }
688- | "var" { ident { "," ident } ":" Type ";" } .
689-Signature = "(" [ Params { ";" Params } [ ";" "..." ] ] ")" [ ":" Results ]
690- | [ ":" Results ] .
691-Params = [ "var" ] ident { "," ident } ":" Type .
692-Results = Type | "(" Type { "," Type } ")" .
693-```
694-
695-A procedure without parameters may leave out the parentheses, both
696-where it is declared (`proc main*;`) and where it is called (`Out.ln`).
697-Used without parentheses in an expression, a procedure is a procedure
698-value, not a call.
699-
700-**Parameters.** A value parameter is a copy: the procedure may change
701-it, and the caller's variable stays as it was. A `var` parameter is the
702-caller's variable itself; its argument must be a variable of exactly
703-the parameter's type.
704-
705-**Results.** A procedure returns nothing, one value, or several. A call
706-that returns several values can only stand on the right of a multiple
707-assignment, or alone as a statement.
708-
709-```
710-module Divide;
711-import Out;
712-
713-proc divmod(a, b: I64): (I64, I64);
714-begin
715- return a div b, a mod b;
716-end;
717-
718-proc main*;
719-var q, r: I64;
720-begin
721- q, r := divmod(17, 5);
722- Out.int(q); Out.str(" rest "); Out.int(r); Out.ln;
723-end;
724-
725-end Divide.
726-```
727-
728-**forward.** `proc f(x: I64): I64; forward;` declares `f` so that it
729-can be called before its body appears; the body comes later with the
730-same signature.
731-
732-Procedures don't nest.
733-
734-**Code procedures.** A procedure whose body is `code` and a list of
735-constant bytes is machine code, written by hand:
736-
737-```
738-proc rdtsc*: U64;
739-code 0FH, 31H, (* rdtsc *)
740- 48H, 0C1H, 0E2H, 20H, (* shl rdx, 32 *)
741- 48H, 09H, 0D0H, (* or rax, rdx *)
742- 0C3H; (* ret *)
743-```
744-
745-It is called like any procedure, with the System V convention: integer
746-and pointer arguments arrive in `rdi`, `rsi`, `rdx`, `rcx`, `r8` and
747-`r9`, `F32` and `F64` ones in `xmm0` to `xmm7`, and the result goes in
748-`rax` (and `rdx` for a second) or `xmm0`. Its parameters and results
749-are therefore of the types C can take (section 9), at most six integer
750-and eight real parameters, and at most two results. The bytes are the whole
751-procedure, `ret` included; they must keep `rbx`, `rbp`, `rsp` and `r12`
752-to `r15` as they found them. The compiler doesn't look inside them.
753-
754-## 9. Calling C
755-
756-```
757-ExternDeclaration = "extern" ( "proc" IdentDef Signature
758- | "var" IdentDef ":" Type ) .
759-```
760-
761-```
762-link "libX11.so.6";
763-extern proc XOpenDisplay(name: ^U8): ^U8;
764-extern proc printf(format: ^U8; ...): I32;
765-extern var environ: ^^U8;
766-```
767-
768-An `extern` procedure or variable is found by its name in the C
769-libraries the program links: the C library always, and each library
770-named by `link`.
771-
772-An `extern` procedure's parameters and result are integers, `BOOL`,
773-`F32`, `F64`, pointers or procedures; a record goes to C by pointer,
774-never by value. `...` accepts any number of further arguments of those
775-types, and is allowed only in an `extern`. C takes no `float` there,
776-so an `F32` given to `...` is an error: the program writes `F64(x)`.
777-A real constant there is an `F64`.
778-
779-An `extern` variable is C's variable itself: reading it reads C's,
780-assigning it writes C's. It can be of any type, declared as C declares
781-it, a record laid out as C lays it out (section 5.5); the compiler
782-can't check that it is. A C variable that is local to each thread,
783-such as `errno`, can't be reached this way; the C library has a
784-procedure for it (`__errno_location`).
785-
786-A C union has no jed type. A program reads one as an array of words,
787-and the member it wants through a pointer conversion:
788-
789-```
790-var ev: [24]I64; (* XEvent: 192 bytes *)
791-...
792-XNextEvent(dpy, ADR(ev));
793-if I32(ev[0]) = KeyPress then
794- key := ^XKeyEvent(ADR(ev));
795- ...
796-end;
797-```
798-
799-Every jed procedure uses the System V calling convention, so a jed
800-procedure whose parameters and result are of those types can be given
801-to C as a callback.
802-
803-## 10. Programs
804-
805-Any module may export a procedure `main`, declared `proc main*;` or
806-`proc main*: I64;`. The program runs the bodies of all its modules
807-(section 3), then the main module's `main`, if it has one, and ends
808-with status 0, or with the status `main` returns, by calling
809-`Rt.exit`. The `main` of an imported module is an ordinary procedure,
810-which runs only if something calls it; so a library module can carry a
811-`main` that tests it.
812-A program uses C if any of its modules has an `extern` declaration or
813-a `link` of a library. A program that doesn't is a static executable
814-with no run time besides the code it uses. One that does is linked
815-dynamically and starts through the C library, so that C's own set-up
816-and clean-up run. A program with a module that says `link static;`
817-must not use C, and the compiler reports an error if it does.
818-
819-**Ending.** `Rt.exit(status)` ends the program. First it runs the
820-procedures registered with `Rt.atExit`, the last registered first,
821-each at most once; then it ends the program with `status`, through
822-C's `exit` in a program that uses C, so that C flushes its own
823-buffers. A failed check (section 6.5) runs them too, after its
824-message, so that `Out`'s buffer is written out. `Sys.exit` ends the
825-program at once, and a program stopped by a signal runs none of them.
826-
827-```
828-proc atExit*(p: proc): ERROR; (* Rt.Full if 32 are registered *)
829-proc exit*(status: I64);
830-```
831-
832-Only what can be reached from `main` and the module bodies goes into
833-the executable: unused procedures, variables and strings are left out.
834-The executable names its procedures and carries line numbers, so that
835-gdb can stop at a line of the source and show where it is.
836-
837-**Defined behaviour.** Every variable starts at zero, integers wrap,
838-and indexing arrays and slices is checked, so a program's behaviour is
839-defined by this report, with one exception: memory reached through a
840-pointer. Dereferencing a stale or made-up pointer, indexing through a
841-pointer, a code procedure that breaks its rules, and C code can read or
842-write any memory, and what follows isn't defined. Dereferencing `nil`, dividing
843-by zero and calling a `nil` procedure stop the program with a signal.
844-
845-## 11. The library
846-
847-Modules written in jed, in the compiler's `lib` directory:
848-
849-| Module | What |
850-|---|---|
851-| `Rt` | ending the program, `exit` and `atExit`; `stop`, which ends it with a message; what the compiler's checks call when they fail; string comparison |
852-| `Sys` | system calls: `openRead`, `create`, `read`, `write`, `close`, `mmap`, `munmap`, `isTerminal`, `yield`, `exit`; one file per target, and `Sys.jed` over the C library for the others |
853-| `Out` | writing text and numbers to standard output, buffered; safe to call from several threads |
854-| `C` | the parts of the C library the others use, and `printf`, `fflush`, `stdout`, `pthread_create`; a program that imports it uses C |
855-| `Lock` | a lock for short sections, for C's threads and `Thread`'s alike |
856-| `Thread` | threads for a program without C: `spawn`, `join`, and `Mutex`; it says `link static` |
857-| `Mem` | `Allocator`, the interface of every allocator, and pages from the system |
858-| `Heap` | a general allocator, `Heap.heap`, safe to call from several threads; freeing a block twice, or one it never gave out, stops the program |
859-| `Arena` | an allocator that frees everything at once; `ADR(arena.base)` is its allocator |
860-| `Str` | operations on `[]U8` strings |
861-| `Buf` | a growable byte buffer |
862-| `Fmt` | formatted output: `Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)])`, or into a `Buf` with `Fmt.write` |
863-| `List` | a generic singly linked list, `List(T)` |
864-| `Map` | a generic hash map, `Map(K, V; hash, eq)` |
865-
866-```
867-module Mem;
868-type
869- Allocator* = record
870- alloc*: proc(a: ^Allocator; size, align: I64): ^U8;
871- free*: proc(a: ^Allocator; p: ^U8);
872- end;
873-...
874-end Mem.
875-```
876-
877-**Out and C's stdio.** `Out` keeps a buffer of 4 KB. It writes it out
878-when it is full, at each line feed when standard output is a terminal,
879-at `Out.flush`, and when the program ends by `Rt.exit`. C's `stdio`
880-keeps a buffer of its own for the same standard output. A program that
881-writes with both flushes one before writing with the other, or the
882-text comes out of order:
883-
884-```
885-module Both;
886-import Out, C; (* C: printf, fflush and C's FILE *stdout *)
887-
888-proc main*;
889-begin
890- Out.str("from jed\n");
891- Out.flush;
892- C.printf("from C\n");
893- C.fflush(C.stdout);
894- Out.str("from jed again\n");
895-end;
896-
897-end Both.
898-```
899-
900-## 12. Versions
901-
902-A version of this report is named by the month it was made in and a
903-count: `2026-10.0`, then `2026-10.1` for the next change that month.
904-`jed --version` says which version the compiler follows.
905-
906-- **2026-10.0.** The first numbered version: the language of compiler
907- 0.3.0.

doc/raz.md (history) added +907 -0

@@ -0,0 +1,907 @@
1+# The programming language raz
2+
3+raz is a small systems language for x86-64 Linux. A raz program can lay
4+a record over a device's registers, read and write memory exactly as
5+written, take part in lock-free algorithms, make system calls and call
6+C libraries. It has no garbage collector and no hidden run time: what
7+the program does is what its text says.
8+
9+This report defines the language. It is short on purpose. Whatever it
10+doesn't allow, raz doesn't have.
11+
12+This is version 2026-10.0 of the report; section 12 says what each
13+version changed.
14+
15+## 1. A first look
16+
17+```
18+module Hello;
19+import Out;
20+
21+proc main*;
22+begin
23+ Out.str("hello, world\n");
24+end;
25+
26+end Hello.
27+```
28+
29+A program is a set of modules. The one named on the command line is
30+the main module, and it exports a procedure `main`; the program starts
31+there, once every module's body has run (section 3). Saved as
32+`Hello.raz`, it is compiled with `raz Hello.raz`, which writes the
33+executable `Hello`.
34+
35+## 2. Words and symbols
36+
37+A program is written in UTF-8. The compiler rejects a file that isn't
38+valid UTF-8: a malformed or overlong sequence, a surrogate, or a code
39+point beyond 10FFFFH. Everything outside strings, characters and
40+comments is ASCII. Spaces, tabs and line breaks separate symbols and
41+are otherwise ignored.
42+
43+**Identifiers** are an ASCII letter or `_` followed by letters, digits
44+and `_`, up to 63 characters. Case matters: `count` and `Count` are different
45+names.
46+
47+**Reserved words** are lowercase, except `VOLATILE`:
48+
49+```
50+and begin break by code const defer div do else elsif end extern for
51+forward if import in link match mod module not of or packed proc record
52+repeat return set shl shr then to type until var variant VOLATILE while
53+xor
54+```
55+
56+**Numbers.** `123` is decimal. `0FFH` is hexadecimal: it starts with a
57+digit and ends in `H`. `1.5` and `2.0E-3` are reals; a real always has
58+a digit on both sides of its point.
59+
60+An integer is an untyped constant, which takes the type it is used as,
61+up to the largest `I64`. A hexadecimal number above that, such as
62+`0FFFFFFFFFFFFFFFFH`, has type `U64`: so `-1` never fits a `U64`, and
63+the big number goes nowhere else without a conversion.
64+
65+A real is an untyped constant too, which takes `F32` or `F64`,
66+whichever it is used as, rounded to the nearest value of that type;
67+where nothing says which, it is an `F64`. A real never becomes an
68+integer, nor an integer a real, without a conversion: `x := 1;` is an
69+error for `x: F64`, and `x := 1.0;` is right.
70+
71+**Characters.** `'a'` is the code point of one character, an integer:
72+`'a'` is 97 and `'é'` is 233.
73+
74+**Strings.** `"héllo\n"` is a sequence of bytes, the UTF-8 of its text:
75+`"é"` is the two bytes 0C3H, 0A9H. Both characters and strings take the
76+escapes `\n` (line feed), `\t` (tab), `\r` (carriage return), `\0`
77+(zero), `\\`, `\'`, `\"`, `\u{H...}` (the code point with hexadecimal
78+value H..., in a string its UTF-8) and, in strings only, `\xHH` (the
79+byte with hexadecimal value HH, which needn't make valid UTF-8).
80+
81+Error messages give the line and the column, counted in characters.
82+
83+**Comments** are `(*` ... `*)` and nest. By convention, the comment
84+just before an exported declaration is its documentation, and the one
85+before `module` is the module's.
86+
87+**Operators and delimiters:**
88+
89+```
90++ - * / = # < <= > >= := : ; , . .. ... ( ) [ ] { } ^ |
91+```
92+
93+## 3. Modules
94+
95+```
96+Module = "module" ident [ "(" ModParams ")" ] ";"
97+ { Import } { Link } { Declaration }
98+ [ "begin" Statements ] "end" ident "." .
99+ModParams = ident { "," ident } { ";" ident ":" "proc" Signature } .
100+Import = "import" ImportItem { "," ImportItem } ";" .
101+ImportItem = ident [ ":=" ident [ "(" Type { "," Type } ")" ] ] .
102+Link = "link" ( string | "static" ) ";" .
103+```
104+
105+A module lives in a file of its own name: module `Out` is `Out.raz`.
106+The name after `end` repeats the module's name.
107+
108+**Exports.** A name declared at the top of a module with `*` after it
109+is exported: other modules can use it as `Module.name`. Record fields
110+are exported the same way. Everything else is private to the module.
111+
112+**Imports.** `import Out;` makes `Out`'s exports available as `Out.x`.
113+`import O := Out;` uses the name `O` instead. A module can't import
114+itself, directly or through others.
115+
116+**Generic modules** take types as parameters:
117+
118+```
119+module List(T);
120+type
121+ Node* = record next*: ^Node; val*: T; end;
122+...
123+end List.
124+```
125+
126+An import gives the arguments: `import Ints := List(I64);`. Each
127+distinct list of arguments makes one *instance*: the module compiled
128+with `T` standing for `I64`. Two imports of `List(I64)`, in any modules,
129+share one instance. Since every instance is checked on its own, an
130+operation the argument type doesn't support (adding two records, say)
131+is reported as an error in that instance.
132+
133+What a generic module needs to do with its types, beyond moving them
134+about, it is given as procedures, after the types:
135+
136+```
137+module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL);
138+```
139+
140+```
141+import Names := Map([]U8, I64, Str.hash, Str.eq);
142+```
143+
144+A procedure argument names a procedure, not a variable or an
145+expression, and its signature, with the type arguments put in, must be
146+the parameter's. Inside the module, `hash(k)` calls it directly. Two
147+imports make the same instance only if their types and their procedures
148+are the same.
149+
150+**Finding modules.** The compiler looks for module `Name` in the main
151+module's directory, then in each directory given with `-I`, then in the
152+`lib` directory beside the compiler. In each directory it takes the
153+first of `Name.OS-ARCH.raz`, `Name.OS.raz`, `Name.ARCH.raz` and
154+`Name.raz` that exists, where `OS-ARCH` is the target, for now only
155+`linux-x86_64`. So a module whose code depends on the machine or the
156+system comes in one file per target, and the modules that import it
157+don't change. Machine code (section 8) and system calls belong in such
158+files.
159+
160+The compiler holds every file of such a module to the same interface.
161+When it takes one of `Name.*.raz`, it also reads the declarations of
162+the others beside it, and of `Name.raz` if there is one, and reports an
163+error unless they all export the same names, each the same kind of
164+thing:
165+
166+- a constant of the same type (its value may differ: a system call
167+ number, say);
168+- a type of the same kind, and for a record or variant the same
169+ exported fields and cases, with the same types (unexported fields,
170+ and so the size and layout, may differ);
171+- a variable of the same type;
172+- a procedure of the same signature.
173+
174+Two types here are the same if they are built alike, a name in one file
175+standing for the same name in another.
176+
177+**Module bodies.** A module may end with `begin` and statements, its
178+body. Every module's body runs once, before the main module's `main`:
179+a module's body runs after the bodies of the modules it imports, in the
180+order of its `import`s, and once however many modules import it. Each
181+instance of a generic module has its body run once. Module variables
182+are zero before any body runs. `return;` ends a body early.
183+
184+**`link "libX11.so.6";`** names a shared library to load at run time,
185+for the `extern` declarations of section 9. **`link static;`** says the
186+module needs a program without C (section 10): it makes its own system
187+calls, or its own threads, which the C library wouldn't know about.
188+
189+## 4. Declarations
190+
191+```
192+Declaration = "const" { IdentDef [ ":" "ERROR" ] "=" Expr ";" }
193+ | "type" { IdentDef "=" Type ";" }
194+ | "var" { IdentList ":" Type ";" }
195+ | ProcDeclaration ";"
196+ | ExternDeclaration ";" .
197+IdentDef = ident [ "*" ] .
198+IdentList = IdentDef { "," IdentDef } .
199+```
200+
201+A name must be declared before it is used, with two exceptions: the
202+base type of a pointer may name a type declared later in the same
203+`type` section (so that two records can point at each other), and a
204+procedure may be declared `forward` and defined later (section 8).
205+
206+**Constants** are evaluated by the compiler. Their expressions use only
207+literals, other constants, operators, `SIZE` and the `LEN` of arrays.
208+
209+**Variables** of a module live as long as the program; variables of a
210+procedure live as long as its call. Both start at zero: every byte of
211+them is zero. So a number starts as `0` (`0.0` for `F32` and `F64`),
212+a `BOOL` as `false`, a pointer, procedure or `ERROR` as `nil`, a slice
213+as the empty slice (`ptr` is `nil`, `len` is 0), a variant as its
214+first case with its fields zero, a set as the empty set, and an
215+enumeration as its first name. No variable is ever read before it has a value.
216+
217+## 5. Types
218+
219+```
220+Type = QualIdent
221+ | "[" Expr "]" Type (* array *)
222+ | "[" "]" Type (* slice *)
223+ | "^" [ "VOLATILE" ] Type (* pointer *)
224+ | [ "packed" ] "record" { IdentList ":" Type ";" } "end"
225+ | "variant" { Case ";" } "end"
226+ | "(" ident { "," ident } ")" (* enumeration *)
227+ | "set" "of" QualIdent
228+ | "proc" Signature .
229+Case = ident [ "(" FieldList { ";" FieldList } ")" ] .
230+FieldList = ident { "," ident } ":" Type .
231+QualIdent = [ ident "." ] ident .
232+```
233+
234+### 5.1 Basic types
235+
236+| Type | Size | Values |
237+|---|---|---|
238+| `I8` `I16` `I32` `I64` | 1, 2, 4, 8 | signed integers, two's complement |
239+| `U8` `U16` `U32` `U64` | 1, 2, 4, 8 | unsigned integers |
240+| `BOOL` | 1 | `false` (0), `true` (1) |
241+| `F32` | 4 | IEEE 754 single precision |
242+| `F64` | 8 | IEEE 754 double precision |
243+
244+### 5.2 Arrays
245+
246+`[n]T` is `n` elements of type `T`, one after another. `n` is a
247+constant greater than zero. Arrays are values: assigning one copies it.
248+
249+### 5.3 Slices
250+
251+`[]T` is a view of elements that live elsewhere: a pointer to the first
252+and a count, 16 bytes in all.
253+
254+```
255+Slice = record ptr: ^T; len: I64; end; (* its layout *)
256+```
257+
258+A slice is made from an array (`a[2..5]`, or an array used where a
259+slice is wanted), from another slice, or from a pointer (`p[0..n]`). It
260+doesn't own what it points at.
261+
262+### 5.4 Pointers
263+
264+`^T` is the address of a `T`, 8 bytes. `nil` is the pointer to nothing.
265+
266+`^VOLATILE T` is the address of a `T` that something besides the
267+program may read or change: a device register, memory shared with
268+another process. Section 7.6 says what that promises.
269+
270+### 5.5 Records
271+
272+```
273+type Cell = record ch: U8; attr: U8; end;
274+```
275+
276+Fields are laid out in order as C lays them out: each at the next
277+multiple of its own alignment, and the whole record padded to a
278+multiple of its largest alignment. A record declared like a C struct
279+has the same layout as that struct.
280+
281+A `packed record` has no padding: each field starts at the byte after
282+the field before it, and the record's alignment is 1. A field of a
283+packed record may be misaligned. x86-64 reads and writes it anyway, but
284+an atomic operation on it is slow, and a volatile access to it is one
285+instruction that needn't be atomic.
286+
287+### 5.6 Variants
288+
289+A variant holds one of several cases, each with its own fields:
290+
291+```
292+type
293+ Shape* = variant
294+ circle(r: F64);
295+ rect(w, h: F64);
296+ dot;
297+ end;
298+```
299+
300+The case names are declared in the scope around the type, so `circle`
301+can be used directly, and as `Shapes.circle` from another module if
302+`Shape` is exported. A case with fields is built by calling it like a
303+procedure, `circle(2.0)`; a case without fields is just `dot`. The only
304+way to read the fields is `match` (section 7.4).
305+
306+Layout: an `I64` tag (0 for the first case, 1 for the second, and so
307+on) followed by the fields of the largest case, laid out as a record.
308+A variant that starts at zero therefore holds its first case.
309+
310+### 5.7 Enumerations and sets
311+
312+```
313+type
314+ Color* = (red, green, blue);
315+ Colors* = set of Color;
316+```
317+
318+An enumeration is a list of names, in order. Like the cases of a
319+variant, the names are declared in the scope around the type. An
320+enumeration has at most 256 names and takes 1 byte; the first name is
321+0, the next 1, and so on.
322+
323+`set of E`, for an enumeration `E` of at most 64 names, holds any
324+choice of `E`'s names: bit `i` stands for the name at position `i`. It
325+takes the smallest of 1, 2, 4 and 8 bytes that has a bit for each name,
326+so a set can stand for a C flags word.
327+
328+### 5.8 Errors
329+
330+```
331+const NotFound*: ERROR = "not found";
332+```
333+
334+`ERROR` is a basic type of 8 bytes. A value of it is made only by a
335+constant declared as above, and each such declaration makes an error
336+different from every other, whatever its message: two modules that
337+both declare `"not found"` have two different errors. A generic module
338+makes its errors once per instance. `nil` is no error.
339+
340+Errors compare with `=` and `#` only, by which declaration made them,
341+never by their message. `MSG(e)` is the message, a `[]U8`; `MSG(nil)`
342+is `""`.
343+
344+```
345+proc find*(key: I64): (^Node, ERROR);
346+...
347+n, err := Table.find(7);
348+if err = Table.NotFound then ... end;
349+```
350+
351+### 5.9 Procedure types
352+
353+```
354+type Compare = proc(a, b: I64): BOOL;
355+```
356+
357+A value of a procedure type is the address of a procedure with that
358+signature, 8 bytes, or `nil`.
359+
360+### 5.10 Same and assignable
361+
362+Two named types are the same only if they are the same declaration.
363+Two anonymous types are the same if they are built alike: `^I64` is
364+`^I64` wherever it is written. A named and an anonymous type are the
365+same if the named one is built like the anonymous one, so that
366+`p := ADR(n)` works for `p: NodePtr` with `type NodePtr = ^Node`.
367+
368+A type declared with only a name on the right, `type Count = I64;`, is
369+another name for that type, not a new one.
370+
371+A value of type `A` can be assigned to a variable of type `B` (and
372+passed to a parameter of type `B`, and returned as a `B`) if they are
373+the same type, or if:
374+
375+- `A` is an integer constant whose value fits in the integer type `B`;
376+- `A` is `nil` and `B` is a pointer, procedure or `ERROR` type;
377+- `A` is `^T` and `B` is `^VOLATILE T`;
378+- `A` is `[n]T` and `B` is `[]T`;
379+- `A` is a string literal and `B` is `[]U8`, `^U8` (a pointer to the
380+ bytes followed by a zero byte, as C wants), or `[n]U8` with `n` at
381+ least the string's length (the rest is zero);
382+- `A` is a procedure and `B` a procedure type with the same signature.
383+
384+Nothing else converts silently. In particular, there is no conversion
385+between integer types, between integers and reals, or between `F32`
386+and `F64`, without a written conversion (section 6.7).
387+
388+## 6. Expressions
389+
390+```
391+Expr = SimpleExpr [ Relation SimpleExpr ] .
392+Relation = "=" | "#" | "<" | "<=" | ">" | ">=" | "in" .
393+SimpleExpr = [ "-" ] Term { AddOp Term } .
394+AddOp = "+" | "-" | "or" | "xor" .
395+Term = Factor { MulOp Factor } .
396+MulOp = "*" | "/" | "div" | "mod" | "and" | "shl" | "shr" .
397+Factor = number | char | string | Designator | "(" Expr ")"
398+ | "not" Factor
399+ | "[" [ Expr { "," Expr } ] "]"
400+ | "{" [ Element { "," Element } ] "}"
401+ | "^" [ "VOLATILE" ] Type "(" Expr ")" .
402+Element = Expr | ident ":" Expr .
403+Designator = QualIdent { Selector } .
404+Selector = "." ident | "^" | "[" Expr [ ".." Expr ] "]"
405+ | "(" [ Expr { "," Expr } ] ")" .
406+```
407+
408+The operators bind in the order of the grammar: `not` most tightly,
409+then the multiplying operators, then the adding ones, then the
410+relations. So `a + b * c = d` is `(a + (b * c)) = d`. A unary minus
411+applies to the first term: `-a * b` is `-(a * b)`.
412+
413+### 6.1 Integers
414+
415+Both operands of `+ - * div mod and or xor` have the same integer
416+type, or one is an untyped constant that takes the other's type. The
417+result has that type and wraps around at its width: in `U8`,
418+`200 + 100` is `44`.
419+
420+`div` rounds toward zero and `mod` takes the sign of the dividend, as
421+in C: `-7 div 2` is `-3`, `-7 mod 2` is `-1`. Dividing by zero, and
422+dividing the smallest `I64` by `-1`, stop the program (`SIGFPE`).
423+
424+`and`, `or`, `xor` and `not` work on every bit. `x shl n` and
425+`x shr n` shift by `n and 63`; `shr` brings in copies of the sign bit
426+for signed types and zeros for unsigned ones.
427+
428+Relations compare as signed or unsigned according to the type.
429+
430+### 6.2 Booleans
431+
432+`and` and `or` on `BOOL` evaluate their right operand only when it
433+decides the result. `not` negates, `xor` is "different", and `=` and
434+`#` compare.
435+
436+### 6.3 Reals
437+
438+`+ - * /` and the relations work on `F32` and on `F64`. Both operands
439+have the same type, or one is a real constant, which takes the other's
440+type (section 2). The result has that type: `F32` arithmetic is done in
441+single precision, rounded at each step as C rounds `float`. A
442+constant expression of reals is evaluated in double precision, then
443+rounded once to the type it takes.
444+
445+### 6.4 Pointers
446+
447+- `p^` is the variable `p` points at.
448+- `p + i` and `p - i`, with `i` an integer, move `p` by `i` elements:
449+ by `i * SIZE(T)` bytes for `p: ^T`.
450+- `p - q`, with both of the same pointer type, is the number of
451+ elements between them, an `I64`.
452+- `p[i]` is `(p + i)^`. `p[lo..hi]` is the slice of the `hi - lo`
453+ elements from `p + lo`. Neither is checked. A pointer to an array
454+ isn't indexed this way, since a step would be a whole array: its
455+ elements are `p^[i]`.
456+- Pointers compare with `= # < <= > >=` as unsigned addresses.
457+ Procedure values compare with `=` and `#` only.
458+
459+### 6.5 Arrays and slices
460+
461+`a[i]` is an element of an array or slice, and `a[lo..hi]` is the slice
462+of the elements from `lo` up to but not including `hi`. Both are
463+checked: `i` must be below the length, and `0 <= lo <= hi <= length`.
464+A check that fails prints the file and line to standard error and stops
465+the program with status 2.
466+
467+**Literals.** `[e1, e2, ...]` builds an array, and `{f: e, g: e, ...}`
468+a record, where the type it must have is known: assigned to a variable,
469+passed to a parameter, returned, compared with a value of that type, or
470+an element of a bigger literal. The elements must be assignable to the
471+element type, and an array literal for `[n]T` has exactly `n` of them.
472+A record literal names its fields, in any order, each at most once; the
473+fields it leaves out are zero. An array literal used as a slice is a
474+hidden variable of the procedure, and lives as long as its call.
475+
476+```
477+c := {ch: 'A', attr: 7};
478+Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)]);
479+```
480+
481+**Strings compare.** Two operands that are each a `[]U8`, a `[n]U8` or
482+a string literal are `=` when they have the same length and the same
483+bytes, and `#` otherwise. Other arrays and slices, records and variants
484+can't be compared; write a loop. Ordering strings is the library's
485+`Str.cmp`.
486+
487+### 6.6 Enumerations and sets
488+
489+Enumerations compare with all six relations, by position, and an
490+enumeration can be the variable of a `for` loop and the expression of a
491+`match` (section 7.4).
492+
493+`{red, blue}` is a set, of the set type of its names' enumeration;
494+`{}` is the empty set, where the type it must have is known. On two sets
495+of the same type, `+` is union, `*` intersection and `-` difference;
496+`=` and `#` compare, and `<=` and `>=` are "is a subset of" and "is a
497+superset of". `x in s` is `true` if the name `x` is in the set `s`.
498+
499+### 6.7 Conversions
500+
501+A type name applied like a procedure converts: `I32(x)`, `F64(n)`,
502+`^Cell(addr)`. A pointer type written out uses the `^` form of the
503+grammar: `^VOLATILE U32(0FEE00000H)`.
504+
505+| From | To | Result |
506+|---|---|---|
507+| integer | integer | the value cut to the new width, or extended by its sign (signed) or zeros (unsigned) |
508+| integer | `F32`, `F64` | the nearest real |
509+| `F32`, `F64` | integer | rounded toward zero; a NaN, or a real out of the range of `I64`, gives the smallest `I64`, then cut |
510+| `F32` | `F64` | the same value |
511+| `F64` | `F32` | the nearest `F32`; too big a value gives an infinity |
512+| enumeration | integer | its position |
513+| integer | enumeration | the name at that position; a position out of range is a failed check (6.5) |
514+| set | integer | its bits |
515+| integer | set | the low bits, as many as the set has |
516+| integer | pointer, procedure | the address |
517+| pointer, procedure | integer | the address |
518+| pointer, procedure | pointer, procedure | the same address, seen as the new type |
519+
520+### 6.8 Built-in procedures
521+
522+| Call | Result |
523+|---|---|
524+| `SIZE(T)` | the size of type `T` in bytes, a constant |
525+| `ADR(x)` | the address of variable `x`, a `^T` |
526+| `LEN(a)` | the number of elements of an array (a constant) or a slice, an `I64` |
527+| `NEW(p, a)` | sets `p: ^T` to a fresh, zeroed `T` from the allocator `a: ^Mem.Allocator`, or to `nil` if `a` has no room |
528+| `MSG(e)` | the message of the error `e`, a `[]U8` |
529+| `SYSCALL(n, x1, ..., x6)` | Linux system call `n` with up to six integer or pointer arguments; the raw result, an `I64` (a negative number is `-errno`) |
530+| `INC(v)`, `INC(v, k)` | adds 1, or `k`, to the integer variable `v`; it wraps, like `+` |
531+| `DEC(v)`, `DEC(v, k)` | subtracts 1, or `k`, from `v` |
532+| `FENCE` | a full memory barrier |
533+| `CAS(p, old, new)` | if `p^ = old`, sets `p^ := new` and returns `true`; atomically |
534+| `XCHG(p, x)` | sets `p^ := x` and returns the value before, atomically |
535+| `XADD(p, x)` | adds `x` to `p^` and returns the value before, atomically |
536+| `ARGC()` | the number of command line arguments, an `I64` |
537+| `ARGV()` | the arguments, a `^^U8` (C strings) |
538+
539+`SYSCALL` exists only on Linux targets. Other systems have no stable
540+system call interface, and their modules call the C library instead
541+(section 9).
542+
543+`INC` and `DEC` evaluate `v` once, so `INC(a[f(i)])` calls `f` once. They
544+read `v` and then write it: two accesses, even through a `^VOLATILE`
545+pointer, and not atomic; `XADD` is the atomic one.
546+
547+For `CAS`, `XCHG` and `XADD`, `p` is a `^T` or `^VOLATILE T` where `T`
548+is an 8-byte integer or pointer type (an integer type for `XADD`). They
549+are sequentially consistent.
550+
551+## 7. Statements
552+
553+```
554+Statements = { Statement ";" } .
555+Statement = Designator [ ":=" Expr ]
556+ | Designator "," Designator { "," Designator } ":=" Expr
557+ | "if" Expr "then" Statements
558+ { "elsif" Expr "then" Statements } [ "else" Statements ] "end"
559+ | "while" Expr "do" Statements "end"
560+ | "repeat" Statements "until" Expr
561+ | "for" ident ":=" Expr "to" Expr [ "by" Expr ] "do" Statements "end"
562+ | "match" Expr "of" { "|" Arm } "end"
563+ | "return" [ Expr { "," Expr } ]
564+ | "break"
565+ | "defer" Statement .
566+Arm = ( ident [ "(" ident { "," ident } ")" ] | "else" ) ":" Statements .
567+```
568+
569+Every statement ends in `;`, including the ones that end in `end` or
570+`until`.
571+
572+### 7.1 Assignment and calls
573+
574+`x := e` evaluates `e` and stores it in `x`; arrays, records, slices and
575+variants are copied. A designator on its own is a call, and any result
576+it returns is dropped: `Out.ln;`, `write(fd, buf);`.
577+
578+`a, b := f(x);` assigns the results of a procedure that returns several
579+(section 8), in order.
580+
581+### 7.2 Conditions and loops
582+
583+`if`, `while` and `repeat` take `BOOL` expressions. `repeat` runs its
584+body at least once and stops when the condition is true.
585+
586+`for i := a to b by s do ... end;` sets the integer variable `i` to `a`,
587+`a + s`, ... while `i <= b` (or `i >= b` if the constant `s` is
588+negative). `s` is 1 if left out. `b` is evaluated once, before the
589+first round.
590+
591+`break` ends the innermost `while`, `repeat` or `for` it stands in,
592+and the program goes on after it. There is no `goto`.
593+
594+### 7.3 Return
595+
596+`return e;` ends the procedure with the result `e`; `return a, b;` with
597+several results; `return;` from a procedure without results. A
598+procedure with results that runs off its end returns zeros, each result
599+as a variable of its type starts (section 4).
600+
601+### 7.4 Match
602+
603+```
604+match s of
605+| circle(r): area := 3.14159 * r * r;
606+| rect(w, h): area := w * h;
607+| dot: area := 0.0;
608+end;
609+```
610+
611+`match` runs the arm of the case `s` holds. An arm may name the case's
612+fields, in order, all of them; the names stand for those fields of `s`
613+itself, so assigning to one changes `s`. An arm may also leave the
614+fields unnamed. Every case must have an arm, unless there is an
615+`| else:` arm, which must come last.
616+
617+`match` on an enumeration works the same way: each arm names one of the
618+enumeration's names.
619+
620+### 7.5 Order of evaluation
621+
622+Operands, arguments and the designators of an assignment are evaluated
623+from left to right.
624+
625+### 7.6 Volatile
626+
627+A variable reached through a `^VOLATILE T` is volatile, and so is any
628+field or element of it. Each read or write of a volatile variable of a
629+basic, enumeration, set or pointer type is exactly one memory access,
630+of exactly its size, and volatile accesses happen in the order the
631+program writes them. Copying a whole record or array through a
632+volatile pointer is not allowed, since it can't be one access.
633+
634+A `^VOLATILE T` doesn't convert to `^T` without a written conversion.
635+
636+`FENCE` also orders the program's ordinary accesses against those of
637+other processors and devices.
638+
639+### 7.7 Defer
640+
641+`defer s;` runs the statement `s` when the program leaves the statement
642+list the `defer` stands in: at its end, or by a `return`, or by a
643+`break` out of it. Statements deferred in the same list run in the
644+opposite order to their `defer`s, and only those whose `defer` has been
645+reached run.
646+
647+```
648+module Head;
649+import Sys, Out;
650+
651+(* Prints the first line of the file at path. *)
652+proc head(path: []U8): BOOL;
653+var fd, n, i: I64; buf: [256]U8;
654+begin
655+ fd := Sys.openRead(path);
656+ if fd < 0 then return false; end;
657+ defer Sys.close(fd);
658+ n := Sys.read(fd, buf);
659+ if n < 0 then return false; end;
660+ for i := 0 to n - 1 do
661+ if buf[i] = 10 then n := i; break; end;
662+ end;
663+ Out.str(buf[0..n]);
664+ Out.ln;
665+ return true;
666+end;
667+
668+proc main*;
669+begin
670+ if not head("/etc/hostname") then Out.str("no hostname\n"); end;
671+end;
672+
673+end Head.
674+```
675+
676+`return e;` evaluates `e` before the deferred statements run. A
677+deferred statement can't contain `return`, `break` or `defer` that
678+would leave it.
679+
680+## 8. Procedures
681+
682+```
683+ProcDeclaration = "proc" IdentDef Signature ";"
684+ ( "forward" | { LocalDeclaration } "begin" Statements "end" [ ident ]
685+ | "code" Expr { "," Expr } ) .
686+LocalDeclaration = "const" { ident [ ":" "ERROR" ] "=" Expr ";" }
687+ | "type" { ident "=" Type ";" }
688+ | "var" { ident { "," ident } ":" Type ";" } .
689+Signature = "(" [ Params { ";" Params } [ ";" "..." ] ] ")" [ ":" Results ]
690+ | [ ":" Results ] .
691+Params = [ "var" ] ident { "," ident } ":" Type .
692+Results = Type | "(" Type { "," Type } ")" .
693+```
694+
695+A procedure without parameters may leave out the parentheses, both
696+where it is declared (`proc main*;`) and where it is called (`Out.ln`).
697+Used without parentheses in an expression, a procedure is a procedure
698+value, not a call.
699+
700+**Parameters.** A value parameter is a copy: the procedure may change
701+it, and the caller's variable stays as it was. A `var` parameter is the
702+caller's variable itself; its argument must be a variable of exactly
703+the parameter's type.
704+
705+**Results.** A procedure returns nothing, one value, or several. A call
706+that returns several values can only stand on the right of a multiple
707+assignment, or alone as a statement.
708+
709+```
710+module Divide;
711+import Out;
712+
713+proc divmod(a, b: I64): (I64, I64);
714+begin
715+ return a div b, a mod b;
716+end;
717+
718+proc main*;
719+var q, r: I64;
720+begin
721+ q, r := divmod(17, 5);
722+ Out.int(q); Out.str(" rest "); Out.int(r); Out.ln;
723+end;
724+
725+end Divide.
726+```
727+
728+**forward.** `proc f(x: I64): I64; forward;` declares `f` so that it
729+can be called before its body appears; the body comes later with the
730+same signature.
731+
732+Procedures don't nest.
733+
734+**Code procedures.** A procedure whose body is `code` and a list of
735+constant bytes is machine code, written by hand:
736+
737+```
738+proc rdtsc*: U64;
739+code 0FH, 31H, (* rdtsc *)
740+ 48H, 0C1H, 0E2H, 20H, (* shl rdx, 32 *)
741+ 48H, 09H, 0D0H, (* or rax, rdx *)
742+ 0C3H; (* ret *)
743+```
744+
745+It is called like any procedure, with the System V convention: integer
746+and pointer arguments arrive in `rdi`, `rsi`, `rdx`, `rcx`, `r8` and
747+`r9`, `F32` and `F64` ones in `xmm0` to `xmm7`, and the result goes in
748+`rax` (and `rdx` for a second) or `xmm0`. Its parameters and results
749+are therefore of the types C can take (section 9), at most six integer
750+and eight real parameters, and at most two results. The bytes are the whole
751+procedure, `ret` included; they must keep `rbx`, `rbp`, `rsp` and `r12`
752+to `r15` as they found them. The compiler doesn't look inside them.
753+
754+## 9. Calling C
755+
756+```
757+ExternDeclaration = "extern" ( "proc" IdentDef Signature
758+ | "var" IdentDef ":" Type ) .
759+```
760+
761+```
762+link "libX11.so.6";
763+extern proc XOpenDisplay(name: ^U8): ^U8;
764+extern proc printf(format: ^U8; ...): I32;
765+extern var environ: ^^U8;
766+```
767+
768+An `extern` procedure or variable is found by its name in the C
769+libraries the program links: the C library always, and each library
770+named by `link`.
771+
772+An `extern` procedure's parameters and result are integers, `BOOL`,
773+`F32`, `F64`, pointers or procedures; a record goes to C by pointer,
774+never by value. `...` accepts any number of further arguments of those
775+types, and is allowed only in an `extern`. C takes no `float` there,
776+so an `F32` given to `...` is an error: the program writes `F64(x)`.
777+A real constant there is an `F64`.
778+
779+An `extern` variable is C's variable itself: reading it reads C's,
780+assigning it writes C's. It can be of any type, declared as C declares
781+it, a record laid out as C lays it out (section 5.5); the compiler
782+can't check that it is. A C variable that is local to each thread,
783+such as `errno`, can't be reached this way; the C library has a
784+procedure for it (`__errno_location`).
785+
786+A C union has no raz type. A program reads one as an array of words,
787+and the member it wants through a pointer conversion:
788+
789+```
790+var ev: [24]I64; (* XEvent: 192 bytes *)
791+...
792+XNextEvent(dpy, ADR(ev));
793+if I32(ev[0]) = KeyPress then
794+ key := ^XKeyEvent(ADR(ev));
795+ ...
796+end;
797+```
798+
799+Every raz procedure uses the System V calling convention, so a raz
800+procedure whose parameters and result are of those types can be given
801+to C as a callback.
802+
803+## 10. Programs
804+
805+Any module may export a procedure `main`, declared `proc main*;` or
806+`proc main*: I64;`. The program runs the bodies of all its modules
807+(section 3), then the main module's `main`, if it has one, and ends
808+with status 0, or with the status `main` returns, by calling
809+`Rt.exit`. The `main` of an imported module is an ordinary procedure,
810+which runs only if something calls it; so a library module can carry a
811+`main` that tests it.
812+A program uses C if any of its modules has an `extern` declaration or
813+a `link` of a library. A program that doesn't is a static executable
814+with no run time besides the code it uses. One that does is linked
815+dynamically and starts through the C library, so that C's own set-up
816+and clean-up run. A program with a module that says `link static;`
817+must not use C, and the compiler reports an error if it does.
818+
819+**Ending.** `Rt.exit(status)` ends the program. First it runs the
820+procedures registered with `Rt.atExit`, the last registered first,
821+each at most once; then it ends the program with `status`, through
822+C's `exit` in a program that uses C, so that C flushes its own
823+buffers. A failed check (section 6.5) runs them too, after its
824+message, so that `Out`'s buffer is written out. `Sys.exit` ends the
825+program at once, and a program stopped by a signal runs none of them.
826+
827+```
828+proc atExit*(p: proc): ERROR; (* Rt.Full if 32 are registered *)
829+proc exit*(status: I64);
830+```
831+
832+Only what can be reached from `main` and the module bodies goes into
833+the executable: unused procedures, variables and strings are left out.
834+The executable names its procedures and carries line numbers, so that
835+gdb can stop at a line of the source and show where it is.
836+
837+**Defined behaviour.** Every variable starts at zero, integers wrap,
838+and indexing arrays and slices is checked, so a program's behaviour is
839+defined by this report, with one exception: memory reached through a
840+pointer. Dereferencing a stale or made-up pointer, indexing through a
841+pointer, a code procedure that breaks its rules, and C code can read or
842+write any memory, and what follows isn't defined. Dereferencing `nil`, dividing
843+by zero and calling a `nil` procedure stop the program with a signal.
844+
845+## 11. The library
846+
847+Modules written in raz, in the compiler's `lib` directory:
848+
849+| Module | What |
850+|---|---|
851+| `Rt` | ending the program, `exit` and `atExit`; `stop`, which ends it with a message; what the compiler's checks call when they fail; string comparison |
852+| `Sys` | system calls: `openRead`, `create`, `read`, `write`, `close`, `mmap`, `munmap`, `isTerminal`, `yield`, `exit`; one file per target, and `Sys.raz` over the C library for the others |
853+| `Out` | writing text and numbers to standard output, buffered; safe to call from several threads |
854+| `C` | the parts of the C library the others use, and `printf`, `fflush`, `stdout`, `pthread_create`; a program that imports it uses C |
855+| `Lock` | a lock for short sections, for C's threads and `Thread`'s alike |
856+| `Thread` | threads for a program without C: `spawn`, `join`, and `Mutex`; it says `link static` |
857+| `Mem` | `Allocator`, the interface of every allocator, and pages from the system |
858+| `Heap` | a general allocator, `Heap.heap`, safe to call from several threads; freeing a block twice, or one it never gave out, stops the program |
859+| `Arena` | an allocator that frees everything at once; `ADR(arena.base)` is its allocator |
860+| `Str` | operations on `[]U8` strings |
861+| `Buf` | a growable byte buffer |
862+| `Fmt` | formatted output: `Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)])`, or into a `Buf` with `Fmt.write` |
863+| `List` | a generic singly linked list, `List(T)` |
864+| `Map` | a generic hash map, `Map(K, V; hash, eq)` |
865+
866+```
867+module Mem;
868+type
869+ Allocator* = record
870+ alloc*: proc(a: ^Allocator; size, align: I64): ^U8;
871+ free*: proc(a: ^Allocator; p: ^U8);
872+ end;
873+...
874+end Mem.
875+```
876+
877+**Out and C's stdio.** `Out` keeps a buffer of 4 KB. It writes it out
878+when it is full, at each line feed when standard output is a terminal,
879+at `Out.flush`, and when the program ends by `Rt.exit`. C's `stdio`
880+keeps a buffer of its own for the same standard output. A program that
881+writes with both flushes one before writing with the other, or the
882+text comes out of order:
883+
884+```
885+module Both;
886+import Out, C; (* C: printf, fflush and C's FILE *stdout *)
887+
888+proc main*;
889+begin
890+ Out.str("from raz\n");
891+ Out.flush;
892+ C.printf("from C\n");
893+ C.fflush(C.stdout);
894+ Out.str("from raz again\n");
895+end;
896+
897+end Both.
898+```
899+
900+## 12. Versions
901+
902+A version of this report is named by the month it was made in and a
903+count: `2026-10.0`, then `2026-10.1` for the next change that month.
904+`raz --version` says which version the compiler follows.
905+
906+- **2026-10.0.** The first numbered version: the language of compiler
907+ 0.3.0.

editor/emacs/jed-mode.el deleted +0 -230

@@ -1,230 +0,0 @@
1-;;; jed-mode.el --- a major mode for jed -*- lexical-binding: t -*-
2-
3-;; Colours jed's reserved words, basic types, built-in procedures,
4-;; numbers, characters, strings and nested comments, and indents by
5-;; `jed-indent-offset': a block's statements one level in from the
6-;; word that opens it; end, until, else and elsif at that word's
7-;; level; match arms at the level of match; procedures, sections
8-;; (const, type, var) and module bodies at the left margin. The text
9-;; of a comment, and a line that goes on with the expression of the
10-;; line before, keep the indent they have.
11-;;
12-;; (add-to-list 'load-path "/path/to/jed/editor/emacs")
13-;; (require 'jed-mode)
14-
15-;;; Code:
16-
17-(defgroup jed nil "The jed programming language." :group 'languages)
18-
19-(defcustom jed-indent-offset 4
20- "Columns that a block's statements are indented by."
21- :type 'integer :group 'jed)
22-
23-(defconst jed-keywords
24- '("and" "begin" "break" "by" "code" "const" "defer" "div" "do" "else"
25- "elsif" "end" "extern" "for" "forward" "if" "import" "in" "link"
26- "match" "mod" "module" "not" "of" "or" "packed" "proc" "record"
27- "repeat" "return" "set" "shl" "shr" "then" "to" "type" "until" "var"
28- "variant" "VOLATILE" "while" "xor"))
29-
30-(defconst jed-types
31- '("I8" "I16" "I32" "I64" "U8" "U16" "U32" "U64" "BOOL" "F32" "F64" "ERROR"))
32-
33-(defconst jed-builtins
34- '("SIZE" "ADR" "LEN" "NEW" "MSG" "SYSCALL" "FENCE" "CAS" "XCHG" "XADD"
35- "ARGC" "ARGV" "INC" "DEC"))
36-
37-(defvar jed-mode-syntax-table
38- (let ((st (make-syntax-table)))
39- ;; (* ... *), nested
40- (modify-syntax-entry ?\( "()1n" st)
41- (modify-syntax-entry ?\) ")(4n" st)
42- (modify-syntax-entry ?* ". 23n" st)
43- (modify-syntax-entry ?\" "\"" st)
44- (modify-syntax-entry ?\' "\"" st)
45- (modify-syntax-entry ?\\ "\\" st)
46- (modify-syntax-entry ?_ "_" st)
47- (dolist (c '(?+ ?- ?/ ?= ?# ?< ?> ?: ?\; ?, ?. ?^ ?|))
48- (modify-syntax-entry c "." st))
49- st)
50- "Syntax table for `jed-mode'.")
51-
52-(defvar jed-font-lock-keywords
53- `((,(regexp-opt jed-keywords 'symbols) . font-lock-keyword-face)
54- (,(regexp-opt jed-types 'symbols) . font-lock-type-face)
55- (,(regexp-opt jed-builtins 'symbols) . font-lock-builtin-face)
56- (,(regexp-opt '("true" "false" "nil") 'symbols) . font-lock-constant-face)
57- ;; 123, 0FFH, 1.5, 2.0E-3
58- ("\\_<[0-9][0-9A-F]*H\\_>\\|\\_<[0-9]+\\(?:\\.[0-9]+\\(?:E[-+]?[0-9]+\\)?\\)?\\_>"
59- . font-lock-constant-face))
60- "What `jed-mode' colours, besides strings and comments.")
61-
62-;;; Indenting
63-
64-(defconst jed--decl
65- "^[ \t]*\\(?:module\\|import\\|link\\|extern\\|proc\\|const\\|type\\|var\\|begin\\)\\_>")
66-(defconst jed--leading "^[ \t]*\\(?:or\\|and\\)\\_>")
67-(defconst jed--block-word
68- "\\_<\\(if\\|while\\|for\\|match\\|record\\|variant\\|begin\\|repeat\\|end\\|until\\)\\_>")
69-
70-(defun jed--line (n)
71- "The text of line N."
72- (save-excursion
73- (goto-char (point-min))
74- (forward-line (1- n))
75- (buffer-substring-no-properties (line-beginning-position) (line-end-position))))
76-
77-(defun jed--indent-of (n)
78- (save-excursion (goto-char (point-min)) (forward-line (1- n)) (current-indentation)))
79-
80-(defun jed--in-comment (n)
81- "Whether line N starts inside a comment that began before it."
82- (save-excursion
83- (goto-char (point-min))
84- (forward-line (1- n))
85- (back-to-indentation)
86- (and (nth 4 (syntax-ppss))
87- (not (looking-at "(\\*")))))
88-
89-(defun jed--prev (n)
90- "The last line before N that isn't blank, or 0."
91- (let ((l (1- n)))
92- (while (and (> l 0) (string-match-p "\\`[ \t]*\\'" (jed--line l)))
93- (setq l (1- l)))
94- l))
95-
96-(defun jed--code (n)
97- "Line N's code, without strings, characters and comments."
98- (let ((line (jed--line n)))
99- (when (jed--in-comment n)
100- (setq line (if (string-match "\\*)" line) (substring line (match-end 0)) "")))
101- ;; one pattern, so that whichever comes first is taken
102- (setq line (replace-regexp-in-string
103- "\"\\(?:[^\"\\\\]\\|\\\\.\\)*\"\\|'\\(?:[^'\\\\]\\|\\\\.\\)*'\\|(\\*.*?\\*)"
104- (lambda (m) (if (string-prefix-p "(" m) "" "0")) line t t))
105- (setq line (replace-regexp-in-string "(\\*.*\\'" "" line t t))
106- (string-trim line)))
107-
108-(defun jed--count (re s)
109- (let ((n 0) (i 0))
110- (while (string-match re s i)
111- (setq n (1+ n) i (match-end 0)))
112- n))
113-
114-(defun jed--continues (n)
115- "Whether the expression on line N goes on to the next line."
116- (let ((code (jed--code n)))
117- (or (> (jed--count "[([{]" code) (jed--count "[])}]" code))
118- (string-match-p "\\(?:,\\|:=\\|[-+*/=#<>]\\|\\_<and\\|\\_<or\\)\\'" code))))
119-
120-(defun jed--start (n)
121- "The first line of the statement that ends on line N."
122- (let ((l n) (done nil))
123- (while (not done)
124- (let ((p (jed--prev l)))
125- (if (or (= p 0)
126- (and (not (jed--continues p))
127- (not (string-match-p jed--leading (jed--line l)))))
128- (setq done t)
129- (setq l p))))
130- l))
131-
132-(defun jed--opens (code)
133- "How many blocks CODE opens, less those it closes."
134- (let ((n 0) (i 0) (case-fold-search nil))
135- (while (string-match jed--block-word code i)
136- (setq n (if (member (match-string 1 code) '("end" "until")) (1- n) (1+ n))
137- i (match-end 0)))
138- n))
139-
140-(defun jed--opener (n)
141- "The indent of the word that opens the block line N is in, or nil."
142- (save-excursion
143- (goto-char (point-min))
144- (forward-line (1- n))
145- (let ((depth 0) (found nil) (case-fold-search nil))
146- (while (and (not found) (re-search-backward jed--block-word nil t))
147- (unless (nth 8 (syntax-ppss))
148- (if (member (match-string 1) '("end" "until"))
149- (setq depth (1+ depth))
150- (if (= depth 0)
151- (setq found (current-indentation))
152- (setq depth (1- depth))))))
153- found)))
154-
155-(defun jed--comment-start (n)
156- "Where the comment that line N, holding only comment, began."
157- (let ((l n))
158- (while (and (> l 1) (not (string-match-p "(\\*" (jed--line l))))
159- (setq l (1- l)))
160- l))
161-
162-(defun jed-calculate-indent ()
163- "The column line at point should start at, or nil to leave it."
164- (let* ((case-fold-search nil)
165- (n (line-number-at-pos))
166- (cur (jed--line n))
167- (prev (jed--prev n)))
168- (catch 'done
169- (when (jed--in-comment n) (throw 'done nil))
170- (when (and (string-match-p jed--decl cur) (not (string-match-p "^[ \t]*proc[ \t]*(" cur)))
171- (throw 'done 0))
172- ;; a comment before a declaration goes with it, at the margin
173- (when (string-match-p "^[ \t]*(\\*" cur)
174- (let ((l n) (last (line-number-at-pos (point-max))))
175- (while (and (< l last) (not (string-match-p "\\*)" (jed--line l))))
176- (setq l (1+ l)))
177- (setq l (1+ l))
178- (while (and (<= l last) (string-match-p "\\`[ \t]*\\'" (jed--line l)))
179- (setq l (1+ l)))
180- (when (and (<= l last) (string-match-p jed--decl (jed--line l)))
181- (throw 'done 0))))
182- (when (string-match-p "^[ \t]*\\(?:end\\|until\\)\\_>" cur)
183- (throw 'done (or (jed--opener n) 0)))
184- (when (= prev 0) (throw 'done 0))
185- (when (string-match-p "^[ \t]*\\(?:\\(?:else\\|elsif\\)\\_>\\||\\)" cur)
186- (throw 'done (or (jed--opener n) (jed--indent-of prev))))
187- (when (or (jed--continues prev) (string-match-p jed--leading cur))
188- (throw 'done nil))
189- (when (string= (jed--code prev) "")
190- (throw 'done (jed--indent-of (jed--comment-start prev))))
191- (let* ((start (jed--start prev))
192- (ind (jed--indent-of start))
193- (code (mapconcat #'jed--code (number-sequence start prev) " ")))
194- (cond
195- ((or (string-match-p "\\`\\(?:const\\|type\\|var\\)\\'" code)
196- (and (string-match-p "\\`else\\_>" code) (>= (jed--opens code) 0))
197- (string-match-p "\\`|.*:\\'" code)
198- (string-match-p "\\`elsif\\_>.*\\_<then\\'" code))
199- (+ ind jed-indent-offset))
200- ((or (string-match-p "\\`|" code) (string-match-p "\\_<match\\_>.*\\_<of\\'" code))
201- ind)
202- ((> (jed--opens code) 0) (+ ind jed-indent-offset))
203- (t ind))))))
204-
205-(defun jed-indent-line ()
206- "Indent the current line as jed's blocks say."
207- (interactive)
208- (let ((col (save-excursion (jed-calculate-indent)))
209- (offset (- (current-column) (current-indentation))))
210- (when col
211- (indent-line-to col)
212- (when (> offset 0) (move-to-column (+ col offset))))))
213-
214-;;;###autoload
215-(define-derived-mode jed-mode prog-mode "jed"
216- "Major mode for editing jed."
217- :syntax-table jed-mode-syntax-table
218- (setq-local font-lock-defaults '(jed-font-lock-keywords nil nil))
219- (setq-local comment-start "(* ")
220- (setq-local comment-end " *)")
221- (setq-local comment-start-skip "(\\*+[ \t]*")
222- (setq-local indent-tabs-mode nil)
223- (setq-local indent-line-function #'jed-indent-line))
224-
225-;;;###autoload
226-(add-to-list 'auto-mode-alist '("\\.jed\\'" . jed-mode))
227-
228-(provide 'jed-mode)
229-
230-;;; jed-mode.el ends here

editor/emacs/raz-mode.el (history) added +230 -0

@@ -0,0 +1,230 @@
1+;;; raz-mode.el --- a major mode for raz -*- lexical-binding: t -*-
2+
3+;; Colours raz's reserved words, basic types, built-in procedures,
4+;; numbers, characters, strings and nested comments, and indents by
5+;; `raz-indent-offset': a block's statements one level in from the
6+;; word that opens it; end, until, else and elsif at that word's
7+;; level; match arms at the level of match; procedures, sections
8+;; (const, type, var) and module bodies at the left margin. The text
9+;; of a comment, and a line that goes on with the expression of the
10+;; line before, keep the indent they have.
11+;;
12+;; (add-to-list 'load-path "/path/to/raz/editor/emacs")
13+;; (require 'raz-mode)
14+
15+;;; Code:
16+
17+(defgroup raz nil "The raz programming language." :group 'languages)
18+
19+(defcustom raz-indent-offset 4
20+ "Columns that a block's statements are indented by."
21+ :type 'integer :group 'raz)
22+
23+(defconst raz-keywords
24+ '("and" "begin" "break" "by" "code" "const" "defer" "div" "do" "else"
25+ "elsif" "end" "extern" "for" "forward" "if" "import" "in" "link"
26+ "match" "mod" "module" "not" "of" "or" "packed" "proc" "record"
27+ "repeat" "return" "set" "shl" "shr" "then" "to" "type" "until" "var"
28+ "variant" "VOLATILE" "while" "xor"))
29+
30+(defconst raz-types
31+ '("I8" "I16" "I32" "I64" "U8" "U16" "U32" "U64" "BOOL" "F32" "F64" "ERROR"))
32+
33+(defconst raz-builtins
34+ '("SIZE" "ADR" "LEN" "NEW" "MSG" "SYSCALL" "FENCE" "CAS" "XCHG" "XADD"
35+ "ARGC" "ARGV" "INC" "DEC"))
36+
37+(defvar raz-mode-syntax-table
38+ (let ((st (make-syntax-table)))
39+ ;; (* ... *), nested
40+ (modify-syntax-entry ?\( "()1n" st)
41+ (modify-syntax-entry ?\) ")(4n" st)
42+ (modify-syntax-entry ?* ". 23n" st)
43+ (modify-syntax-entry ?\" "\"" st)
44+ (modify-syntax-entry ?\' "\"" st)
45+ (modify-syntax-entry ?\\ "\\" st)
46+ (modify-syntax-entry ?_ "_" st)
47+ (dolist (c '(?+ ?- ?/ ?= ?# ?< ?> ?: ?\; ?, ?. ?^ ?|))
48+ (modify-syntax-entry c "." st))
49+ st)
50+ "Syntax table for `raz-mode'.")
51+
52+(defvar raz-font-lock-keywords
53+ `((,(regexp-opt raz-keywords 'symbols) . font-lock-keyword-face)
54+ (,(regexp-opt raz-types 'symbols) . font-lock-type-face)
55+ (,(regexp-opt raz-builtins 'symbols) . font-lock-builtin-face)
56+ (,(regexp-opt '("true" "false" "nil") 'symbols) . font-lock-constant-face)
57+ ;; 123, 0FFH, 1.5, 2.0E-3
58+ ("\\_<[0-9][0-9A-F]*H\\_>\\|\\_<[0-9]+\\(?:\\.[0-9]+\\(?:E[-+]?[0-9]+\\)?\\)?\\_>"
59+ . font-lock-constant-face))
60+ "What `raz-mode' colours, besides strings and comments.")
61+
62+;;; Indenting
63+
64+(defconst raz--decl
65+ "^[ \t]*\\(?:module\\|import\\|link\\|extern\\|proc\\|const\\|type\\|var\\|begin\\)\\_>")
66+(defconst raz--leading "^[ \t]*\\(?:or\\|and\\)\\_>")
67+(defconst raz--block-word
68+ "\\_<\\(if\\|while\\|for\\|match\\|record\\|variant\\|begin\\|repeat\\|end\\|until\\)\\_>")
69+
70+(defun raz--line (n)
71+ "The text of line N."
72+ (save-excursion
73+ (goto-char (point-min))
74+ (forward-line (1- n))
75+ (buffer-substring-no-properties (line-beginning-position) (line-end-position))))
76+
77+(defun raz--indent-of (n)
78+ (save-excursion (goto-char (point-min)) (forward-line (1- n)) (current-indentation)))
79+
80+(defun raz--in-comment (n)
81+ "Whether line N starts inside a comment that began before it."
82+ (save-excursion
83+ (goto-char (point-min))
84+ (forward-line (1- n))
85+ (back-to-indentation)
86+ (and (nth 4 (syntax-ppss))
87+ (not (looking-at "(\\*")))))
88+
89+(defun raz--prev (n)
90+ "The last line before N that isn't blank, or 0."
91+ (let ((l (1- n)))
92+ (while (and (> l 0) (string-match-p "\\`[ \t]*\\'" (raz--line l)))
93+ (setq l (1- l)))
94+ l))
95+
96+(defun raz--code (n)
97+ "Line N's code, without strings, characters and comments."
98+ (let ((line (raz--line n)))
99+ (when (raz--in-comment n)
100+ (setq line (if (string-match "\\*)" line) (substring line (match-end 0)) "")))
101+ ;; one pattern, so that whichever comes first is taken
102+ (setq line (replace-regexp-in-string
103+ "\"\\(?:[^\"\\\\]\\|\\\\.\\)*\"\\|'\\(?:[^'\\\\]\\|\\\\.\\)*'\\|(\\*.*?\\*)"
104+ (lambda (m) (if (string-prefix-p "(" m) "" "0")) line t t))
105+ (setq line (replace-regexp-in-string "(\\*.*\\'" "" line t t))
106+ (string-trim line)))
107+
108+(defun raz--count (re s)
109+ (let ((n 0) (i 0))
110+ (while (string-match re s i)
111+ (setq n (1+ n) i (match-end 0)))
112+ n))
113+
114+(defun raz--continues (n)
115+ "Whether the expression on line N goes on to the next line."
116+ (let ((code (raz--code n)))
117+ (or (> (raz--count "[([{]" code) (raz--count "[])}]" code))
118+ (string-match-p "\\(?:,\\|:=\\|[-+*/=#<>]\\|\\_<and\\|\\_<or\\)\\'" code))))
119+
120+(defun raz--start (n)
121+ "The first line of the statement that ends on line N."
122+ (let ((l n) (done nil))
123+ (while (not done)
124+ (let ((p (raz--prev l)))
125+ (if (or (= p 0)
126+ (and (not (raz--continues p))
127+ (not (string-match-p raz--leading (raz--line l)))))
128+ (setq done t)
129+ (setq l p))))
130+ l))
131+
132+(defun raz--opens (code)
133+ "How many blocks CODE opens, less those it closes."
134+ (let ((n 0) (i 0) (case-fold-search nil))
135+ (while (string-match raz--block-word code i)
136+ (setq n (if (member (match-string 1 code) '("end" "until")) (1- n) (1+ n))
137+ i (match-end 0)))
138+ n))
139+
140+(defun raz--opener (n)
141+ "The indent of the word that opens the block line N is in, or nil."
142+ (save-excursion
143+ (goto-char (point-min))
144+ (forward-line (1- n))
145+ (let ((depth 0) (found nil) (case-fold-search nil))
146+ (while (and (not found) (re-search-backward raz--block-word nil t))
147+ (unless (nth 8 (syntax-ppss))
148+ (if (member (match-string 1) '("end" "until"))
149+ (setq depth (1+ depth))
150+ (if (= depth 0)
151+ (setq found (current-indentation))
152+ (setq depth (1- depth))))))
153+ found)))
154+
155+(defun raz--comment-start (n)
156+ "Where the comment that line N, holding only comment, began."
157+ (let ((l n))
158+ (while (and (> l 1) (not (string-match-p "(\\*" (raz--line l))))
159+ (setq l (1- l)))
160+ l))
161+
162+(defun raz-calculate-indent ()
163+ "The column line at point should start at, or nil to leave it."
164+ (let* ((case-fold-search nil)
165+ (n (line-number-at-pos))
166+ (cur (raz--line n))
167+ (prev (raz--prev n)))
168+ (catch 'done
169+ (when (raz--in-comment n) (throw 'done nil))
170+ (when (and (string-match-p raz--decl cur) (not (string-match-p "^[ \t]*proc[ \t]*(" cur)))
171+ (throw 'done 0))
172+ ;; a comment before a declaration goes with it, at the margin
173+ (when (string-match-p "^[ \t]*(\\*" cur)
174+ (let ((l n) (last (line-number-at-pos (point-max))))
175+ (while (and (< l last) (not (string-match-p "\\*)" (raz--line l))))
176+ (setq l (1+ l)))
177+ (setq l (1+ l))
178+ (while (and (<= l last) (string-match-p "\\`[ \t]*\\'" (raz--line l)))
179+ (setq l (1+ l)))
180+ (when (and (<= l last) (string-match-p raz--decl (raz--line l)))
181+ (throw 'done 0))))
182+ (when (string-match-p "^[ \t]*\\(?:end\\|until\\)\\_>" cur)
183+ (throw 'done (or (raz--opener n) 0)))
184+ (when (= prev 0) (throw 'done 0))
185+ (when (string-match-p "^[ \t]*\\(?:\\(?:else\\|elsif\\)\\_>\\||\\)" cur)
186+ (throw 'done (or (raz--opener n) (raz--indent-of prev))))
187+ (when (or (raz--continues prev) (string-match-p raz--leading cur))
188+ (throw 'done nil))
189+ (when (string= (raz--code prev) "")
190+ (throw 'done (raz--indent-of (raz--comment-start prev))))
191+ (let* ((start (raz--start prev))
192+ (ind (raz--indent-of start))
193+ (code (mapconcat #'raz--code (number-sequence start prev) " ")))
194+ (cond
195+ ((or (string-match-p "\\`\\(?:const\\|type\\|var\\)\\'" code)
196+ (and (string-match-p "\\`else\\_>" code) (>= (raz--opens code) 0))
197+ (string-match-p "\\`|.*:\\'" code)
198+ (string-match-p "\\`elsif\\_>.*\\_<then\\'" code))
199+ (+ ind raz-indent-offset))
200+ ((or (string-match-p "\\`|" code) (string-match-p "\\_<match\\_>.*\\_<of\\'" code))
201+ ind)
202+ ((> (raz--opens code) 0) (+ ind raz-indent-offset))
203+ (t ind))))))
204+
205+(defun raz-indent-line ()
206+ "Indent the current line as raz's blocks say."
207+ (interactive)
208+ (let ((col (save-excursion (raz-calculate-indent)))
209+ (offset (- (current-column) (current-indentation))))
210+ (when col
211+ (indent-line-to col)
212+ (when (> offset 0) (move-to-column (+ col offset))))))
213+
214+;;;###autoload
215+(define-derived-mode raz-mode prog-mode "raz"
216+ "Major mode for editing raz."
217+ :syntax-table raz-mode-syntax-table
218+ (setq-local font-lock-defaults '(raz-font-lock-keywords nil nil))
219+ (setq-local comment-start "(* ")
220+ (setq-local comment-end " *)")
221+ (setq-local comment-start-skip "(\\*+[ \t]*")
222+ (setq-local indent-tabs-mode nil)
223+ (setq-local indent-line-function #'raz-indent-line))
224+
225+;;;###autoload
226+(add-to-list 'auto-mode-alist '("\\.raz\\'" . raz-mode))
227+
228+(provide 'raz-mode)
229+
230+;;; raz-mode.el ends here

editor/vim/ftdetect/jed.vim deleted +0 -3

@@ -1,3 +0,0 @@
1-" jed: *.jed files, indented by 4 spaces.
2-autocmd BufRead,BufNewFile *.jed setfiletype jed
3-autocmd FileType jed setlocal shiftwidth=4 softtabstop=4 expandtab

editor/vim/ftdetect/raz.vim (history) added +3 -0

@@ -0,0 +1,3 @@
1+" raz: *.raz files, indented by 4 spaces.
2+autocmd BufRead,BufNewFile *.raz setfiletype raz
3+autocmd FileType raz setlocal shiftwidth=4 softtabstop=4 expandtab

editor/vim/indent/jed.vim deleted +0 -157

@@ -1,157 +0,0 @@
1-" Vim indent file for jed, by shiftwidth(): a block's statements one
2-" level in from the word that opens it; end, until, else and elsif at
3-" that word's level; match arms at the level of match; procedures,
4-" sections (const, type, var) and module bodies at the left margin.
5-" The text of a comment, and a line that goes on with the expression
6-" of the line before, keep the indent they have.
7-
8-if exists("b:did_indent")
9- finish
10-endif
11-let b:did_indent = 1
12-
13-setlocal indentexpr=GetJedIndent(v:lnum)
14-setlocal indentkeys=o,O,0=end,0=else,0=elsif,0=until,0=\|,!^F
15-setlocal nolisp nosmartindent
16-
17-if exists("*GetJedIndent")
18- finish
19-endif
20-
21-" searchpair() needs groups that don't capture
22-let s:opener = '\C\<\%(if\|while\|for\|match\|record\|variant\|begin\|repeat\)\>'
23-let s:closer = '\C\<\%(end\|until\)\>'
24-let s:skip = 'synIDattr(synID(line("."), col("."), 1), "name") =~? "string\\|char\\|comment"'
25-let s:decl = '^\s*\%(module\|import\|link\|extern\|proc\|const\|type\|var\|begin\)\>'
26-
27-" The line's code, without strings, characters and comments.
28-function! s:Code(lnum)
29- let line = getline(a:lnum)
30- " a line that starts inside a comment: its code is after the comment
31- if s:InComment(a:lnum)
32- let line = line =~ '\*)' ? substitute(line, '^.\{-}\*)', '', '') : ''
33- endif
34- " one pattern, so that whichever comes first is taken: a " in a
35- " character, a ' in a string; strings become 0, comments go
36- let line = substitute(line,
37- \ '"\%([^"\\]\|\\.\)*"\|''\%([^''\\]\|\\.\)*''\|(\*.\{-}\*)',
38- \ '\=submatch(0)[0] == "(" ? "" : "0"', 'g')
39- let line = substitute(line, '(\*.*$', '', '')
40- return substitute(line, '^\s*\(.\{-}\)\s*$', '\1', '')
41-endfunction
42-
43-" Whether the expression on lnum goes on to the next line.
44-function! s:Continues(lnum)
45- let code = s:Code(a:lnum)
46- if len(substitute(code, '[^([{]', '', 'g')) > len(substitute(code, '[^)\]}]', '', 'g'))
47- return 1
48- endif
49- return code =~# '\%(,\|:=\|[-+*/=#<>]\|\<and\|\<or\)$'
50-endfunction
51-
52-let s:leading = '^\s*\%(or\|and\)\>'
53-
54-" The first line of the statement that ends on lnum.
55-function! s:Start(lnum)
56- let l = a:lnum
57- while 1
58- let p = prevnonblank(l - 1)
59- if p == 0 || !s:Continues(p) && getline(l) !~# s:leading
60- return l
61- endif
62- let l = p
63- endwhile
64-endfunction
65-
66-" The line itself, or where the comment it ends began, if it holds
67-" nothing but comment.
68-function! s:Reference(lnum)
69- let l = a:lnum
70- if s:Code(l) != ''
71- return l
72- endif
73- while l > 1 && getline(l) !~ '(\*'
74- let l -= 1
75- endwhile
76- return l
77-endfunction
78-
79-" How many blocks the code opens, less those it closes.
80-function! s:Opens(code)
81- let n = 0
82- let i = 0
83- while 1
84- let m = matchstrpos(a:code, '\C\<\%(if\|while\|for\|record\|variant\|begin\|repeat\|end\|until\)\>', i)
85- if m[1] < 0
86- return n
87- endif
88- let n += (m[0] ==# 'end' || m[0] ==# 'until') ? -1 : 1
89- let i = m[2]
90- endwhile
91-endfunction
92-
93-function! s:InComment(lnum)
94- let col = match(getline(a:lnum), '\S') + 1
95- return col > 0 && synIDattr(synID(a:lnum, col, 1), "name") =~? 'comment'
96- \ && getline(a:lnum) !~ '^\s*(\*'
97-endfunction
98-
99-function! GetJedIndent(lnum)
100- let cur = getline(a:lnum)
101- if s:InComment(a:lnum)
102- return -1
103- endif
104- if cur =~# s:decl && cur !~# '^\s*proc\s*('
105- return 0
106- endif
107- " a comment before a declaration goes with it, at the margin
108- if cur =~ '^\s*(\*'
109- let l = a:lnum
110- while l < line('$') && getline(l) !~ '\*)'
111- let l += 1
112- endwhile
113- if getline(nextnonblank(l + 1)) =~# s:decl
114- return 0
115- endif
116- endif
117- if cur =~# '^\s*\%(end\|until\)\>'
118- call cursor(a:lnum, 1)
119- let l = searchpair(s:opener, '', s:closer, 'bW', s:skip)
120- return l > 0 ? indent(l) : 0
121- endif
122- let prev = prevnonblank(a:lnum - 1)
123- if prev == 0
124- return 0
125- endif
126- if cur =~# '^\s*\%(else\|elsif\)\>'
127- call cursor(a:lnum, 1)
128- let l = searchpair(s:opener, '', s:closer, 'bW', s:skip)
129- return l > 0 ? indent(l) : indent(prev)
130- endif
131- if cur =~# '^\s*|'
132- call cursor(a:lnum, 1)
133- let l = searchpair(s:opener, '', s:closer, 'bW', s:skip)
134- return l > 0 ? indent(l) : indent(prev)
135- endif
136- if s:Continues(prev) || cur =~# s:leading
137- return -1
138- endif
139- if s:Code(prev) == ''
140- return indent(s:Reference(prev))
141- endif
142-
143- let start = s:Start(prev)
144- let ind = indent(start)
145- let code = join(map(range(start, prev), 's:Code(v:val)'), ' ')
146- if code =~# '^\%(const\|type\|var\)$' || code =~# '^else\>' && s:Opens(code) >= 0
147- \ || code =~# '^|.*:$' || code =~# '^elsif\>.*\<then$'
148- return ind + shiftwidth()
149- endif
150- if code =~# '^|' || code =~# '\<match\>.*\<of$'
151- return ind
152- endif
153- if s:Opens(code) > 0
154- return ind + shiftwidth()
155- endif
156- return ind
157-endfunction

editor/vim/indent/raz.vim (history) added +157 -0

@@ -0,0 +1,157 @@
1+" Vim indent file for raz, by shiftwidth(): a block's statements one
2+" level in from the word that opens it; end, until, else and elsif at
3+" that word's level; match arms at the level of match; procedures,
4+" sections (const, type, var) and module bodies at the left margin.
5+" The text of a comment, and a line that goes on with the expression
6+" of the line before, keep the indent they have.
7+
8+if exists("b:did_indent")
9+ finish
10+endif
11+let b:did_indent = 1
12+
13+setlocal indentexpr=GetRazIndent(v:lnum)
14+setlocal indentkeys=o,O,0=end,0=else,0=elsif,0=until,0=\|,!^F
15+setlocal nolisp nosmartindent
16+
17+if exists("*GetRazIndent")
18+ finish
19+endif
20+
21+" searchpair() needs groups that don't capture
22+let s:opener = '\C\<\%(if\|while\|for\|match\|record\|variant\|begin\|repeat\)\>'
23+let s:closer = '\C\<\%(end\|until\)\>'
24+let s:skip = 'synIDattr(synID(line("."), col("."), 1), "name") =~? "string\\|char\\|comment"'
25+let s:decl = '^\s*\%(module\|import\|link\|extern\|proc\|const\|type\|var\|begin\)\>'
26+
27+" The line's code, without strings, characters and comments.
28+function! s:Code(lnum)
29+ let line = getline(a:lnum)
30+ " a line that starts inside a comment: its code is after the comment
31+ if s:InComment(a:lnum)
32+ let line = line =~ '\*)' ? substitute(line, '^.\{-}\*)', '', '') : ''
33+ endif
34+ " one pattern, so that whichever comes first is taken: a " in a
35+ " character, a ' in a string; strings become 0, comments go
36+ let line = substitute(line,
37+ \ '"\%([^"\\]\|\\.\)*"\|''\%([^''\\]\|\\.\)*''\|(\*.\{-}\*)',
38+ \ '\=submatch(0)[0] == "(" ? "" : "0"', 'g')
39+ let line = substitute(line, '(\*.*$', '', '')
40+ return substitute(line, '^\s*\(.\{-}\)\s*$', '\1', '')
41+endfunction
42+
43+" Whether the expression on lnum goes on to the next line.
44+function! s:Continues(lnum)
45+ let code = s:Code(a:lnum)
46+ if len(substitute(code, '[^([{]', '', 'g')) > len(substitute(code, '[^)\]}]', '', 'g'))
47+ return 1
48+ endif
49+ return code =~# '\%(,\|:=\|[-+*/=#<>]\|\<and\|\<or\)$'
50+endfunction
51+
52+let s:leading = '^\s*\%(or\|and\)\>'
53+
54+" The first line of the statement that ends on lnum.
55+function! s:Start(lnum)
56+ let l = a:lnum
57+ while 1
58+ let p = prevnonblank(l - 1)
59+ if p == 0 || !s:Continues(p) && getline(l) !~# s:leading
60+ return l
61+ endif
62+ let l = p
63+ endwhile
64+endfunction
65+
66+" The line itself, or where the comment it ends began, if it holds
67+" nothing but comment.
68+function! s:Reference(lnum)
69+ let l = a:lnum
70+ if s:Code(l) != ''
71+ return l
72+ endif
73+ while l > 1 && getline(l) !~ '(\*'
74+ let l -= 1
75+ endwhile
76+ return l
77+endfunction
78+
79+" How many blocks the code opens, less those it closes.
80+function! s:Opens(code)
81+ let n = 0
82+ let i = 0
83+ while 1
84+ let m = matchstrpos(a:code, '\C\<\%(if\|while\|for\|record\|variant\|begin\|repeat\|end\|until\)\>', i)
85+ if m[1] < 0
86+ return n
87+ endif
88+ let n += (m[0] ==# 'end' || m[0] ==# 'until') ? -1 : 1
89+ let i = m[2]
90+ endwhile
91+endfunction
92+
93+function! s:InComment(lnum)
94+ let col = match(getline(a:lnum), '\S') + 1
95+ return col > 0 && synIDattr(synID(a:lnum, col, 1), "name") =~? 'comment'
96+ \ && getline(a:lnum) !~ '^\s*(\*'
97+endfunction
98+
99+function! GetRazIndent(lnum)
100+ let cur = getline(a:lnum)
101+ if s:InComment(a:lnum)
102+ return -1
103+ endif
104+ if cur =~# s:decl && cur !~# '^\s*proc\s*('
105+ return 0
106+ endif
107+ " a comment before a declaration goes with it, at the margin
108+ if cur =~ '^\s*(\*'
109+ let l = a:lnum
110+ while l < line('$') && getline(l) !~ '\*)'
111+ let l += 1
112+ endwhile
113+ if getline(nextnonblank(l + 1)) =~# s:decl
114+ return 0
115+ endif
116+ endif
117+ if cur =~# '^\s*\%(end\|until\)\>'
118+ call cursor(a:lnum, 1)
119+ let l = searchpair(s:opener, '', s:closer, 'bW', s:skip)
120+ return l > 0 ? indent(l) : 0
121+ endif
122+ let prev = prevnonblank(a:lnum - 1)
123+ if prev == 0
124+ return 0
125+ endif
126+ if cur =~# '^\s*\%(else\|elsif\)\>'
127+ call cursor(a:lnum, 1)
128+ let l = searchpair(s:opener, '', s:closer, 'bW', s:skip)
129+ return l > 0 ? indent(l) : indent(prev)
130+ endif
131+ if cur =~# '^\s*|'
132+ call cursor(a:lnum, 1)
133+ let l = searchpair(s:opener, '', s:closer, 'bW', s:skip)
134+ return l > 0 ? indent(l) : indent(prev)
135+ endif
136+ if s:Continues(prev) || cur =~# s:leading
137+ return -1
138+ endif
139+ if s:Code(prev) == ''
140+ return indent(s:Reference(prev))
141+ endif
142+
143+ let start = s:Start(prev)
144+ let ind = indent(start)
145+ let code = join(map(range(start, prev), 's:Code(v:val)'), ' ')
146+ if code =~# '^\%(const\|type\|var\)$' || code =~# '^else\>' && s:Opens(code) >= 0
147+ \ || code =~# '^|.*:$' || code =~# '^elsif\>.*\<then$'
148+ return ind + shiftwidth()
149+ endif
150+ if code =~# '^|' || code =~# '\<match\>.*\<of$'
151+ return ind
152+ endif
153+ if s:Opens(code) > 0
154+ return ind + shiftwidth()
155+ endif
156+ return ind
157+endfunction

editor/vim/syntax/jed.vim deleted +0 -42

@@ -1,42 +0,0 @@
1-" Vim syntax file for jed: reserved words, basic types, built-in
2-" procedures, numbers, characters, strings and nested comments.
3-
4-if exists("b:current_syntax")
5- finish
6-endif
7-
8-syntax case match
9-
10-syntax keyword jedKeyword and begin break by code const defer div do else
11-syntax keyword jedKeyword elsif end extern for forward if import in link
12-syntax keyword jedKeyword match mod module not of or packed proc record
13-syntax keyword jedKeyword repeat return set shl shr then to type until var
14-syntax keyword jedKeyword variant VOLATILE while xor
15-syntax keyword jedType I8 I16 I32 I64 U8 U16 U32 U64 BOOL F32 F64 ERROR
16-syntax keyword jedBuiltin SIZE ADR LEN NEW MSG SYSCALL FENCE CAS XCHG XADD
17-syntax keyword jedBuiltin ARGC ARGV INC DEC
18-syntax keyword jedConstant true false nil
19-
20-" 123, 0FFH, 1.5, 2.0E-3
21-syntax match jedNumber "\<\d[0-9A-F]*H\>"
22-syntax match jedNumber "\<\d\+\>"
23-syntax match jedNumber "\<\d\+\.\d\+\(E[+-]\=\d\+\)\=\>"
24-
25-syntax match jedEscape contained "\\\([ntr0\\'\"]\|x\x\x\|u{\x\+}\)"
26-syntax region jedString start=+"+ skip=+\\.+ end=+"+ contains=jedEscape oneline
27-syntax region jedChar start=+'+ skip=+\\.+ end=+'+ contains=jedEscape oneline
28-
29-syntax region jedComment start="(\*" end="\*)" contains=jedComment,@Spell
30-syntax sync fromstart
31-
32-highlight default link jedKeyword Statement
33-highlight default link jedType Type
34-highlight default link jedBuiltin Function
35-highlight default link jedConstant Constant
36-highlight default link jedNumber Number
37-highlight default link jedString String
38-highlight default link jedChar Character
39-highlight default link jedEscape SpecialChar
40-highlight default link jedComment Comment
41-
42-let b:current_syntax = "jed"

editor/vim/syntax/raz.vim (history) added +42 -0

@@ -0,0 +1,42 @@
1+" Vim syntax file for raz: reserved words, basic types, built-in
2+" procedures, numbers, characters, strings and nested comments.
3+
4+if exists("b:current_syntax")
5+ finish
6+endif
7+
8+syntax case match
9+
10+syntax keyword razKeyword and begin break by code const defer div do else
11+syntax keyword razKeyword elsif end extern for forward if import in link
12+syntax keyword razKeyword match mod module not of or packed proc record
13+syntax keyword razKeyword repeat return set shl shr then to type until var
14+syntax keyword razKeyword variant VOLATILE while xor
15+syntax keyword razType I8 I16 I32 I64 U8 U16 U32 U64 BOOL F32 F64 ERROR
16+syntax keyword razBuiltin SIZE ADR LEN NEW MSG SYSCALL FENCE CAS XCHG XADD
17+syntax keyword razBuiltin ARGC ARGV INC DEC
18+syntax keyword razConstant true false nil
19+
20+" 123, 0FFH, 1.5, 2.0E-3
21+syntax match razNumber "\<\d[0-9A-F]*H\>"
22+syntax match razNumber "\<\d\+\>"
23+syntax match razNumber "\<\d\+\.\d\+\(E[+-]\=\d\+\)\=\>"
24+
25+syntax match razEscape contained "\\\([ntr0\\'\"]\|x\x\x\|u{\x\+}\)"
26+syntax region razString start=+"+ skip=+\\.+ end=+"+ contains=razEscape oneline
27+syntax region razChar start=+'+ skip=+\\.+ end=+'+ contains=razEscape oneline
28+
29+syntax region razComment start="(\*" end="\*)" contains=razComment,@Spell
30+syntax sync fromstart
31+
32+highlight default link razKeyword Statement
33+highlight default link razType Type
34+highlight default link razBuiltin Function
35+highlight default link razConstant Constant
36+highlight default link razNumber Number
37+highlight default link razString String
38+highlight default link razChar Character
39+highlight default link razEscape SpecialChar
40+highlight default link razComment Comment
41+
42+let b:current_syntax = "raz"

examples/Args.jed deleted +0 -25

@@ -1,25 +0,0 @@
1-(* Prints its arguments, one per line, and exits with how many. *)
2-module Args;
3-import Out;
4-
5-(* The length of a C string. *)
6-proc len(s: ^U8): I64;
7-var n: I64;
8-begin
9- n := 0;
10- while s[n] # 0 do n := n + 1; end;
11- return n;
12-end;
13-
14-proc main*: I64;
15-var i: I64; s: ^U8;
16-begin
17- for i := 1 to ARGC() - 1 do
18- s := ARGV()[i];
19- Out.str(s[0..len(s)]);
20- Out.ln;
21- end;
22- return ARGC() - 1;
23-end;
24-
25-end Args.

examples/Args.raz (history) added +25 -0

@@ -0,0 +1,25 @@
1+(* Prints its arguments, one per line, and exits with how many. *)
2+module Args;
3+import Out;
4+
5+(* The length of a C string. *)
6+proc len(s: ^U8): I64;
7+var n: I64;
8+begin
9+ n := 0;
10+ while s[n] # 0 do n := n + 1; end;
11+ return n;
12+end;
13+
14+proc main*: I64;
15+var i: I64; s: ^U8;
16+begin
17+ for i := 1 to ARGC() - 1 do
18+ s := ARGV()[i];
19+ Out.str(s[0..len(s)]);
20+ Out.ln;
21+ end;
22+ return ARGC() - 1;
23+end;
24+
25+end Args.

examples/Cpu.jed deleted +0 -29

@@ -1,29 +0,0 @@
1-(* A code procedure: machine code written as bytes, called like any
2- other procedure. cpuid's vendor string, from leaf 0. *)
3-module Cpu;
4-import Out;
5-
6-(* cpuid leaf 0: puts the 12 bytes of the vendor in buf, rdi. *)
7-proc vendor(buf: ^U8);
8-code 53H, (* push rbx *)
9- 49H, 89H, 0F8H, (* mov r8, rdi *)
10- 31H, 0C0H, (* xor eax, eax *)
11- 0FH, 0A2H, (* cpuid *)
12- 41H, 89H, 18H, (* mov [r8], ebx *)
13- 41H, 89H, 50H, 04H, (* mov [r8+4], edx *)
14- 41H, 89H, 48H, 08H, (* mov [r8+8], ecx *)
15- 5BH, (* pop rbx *)
16- 0C3H; (* ret *)
17-
18-proc main*;
19-var buf: [12]U8; i: I64; ok: BOOL;
20-begin
21- vendor(ADR(buf[0]));
22- ok := true;
23- for i := 0 to 11 do
24- if (buf[i] < ' ') or (buf[i] > '~') then ok := false; end;
25- end;
26- if ok then Out.str("vendor is printable\n"); end;
27-end;
28-
29-end Cpu.

examples/Cpu.raz (history) added +29 -0

@@ -0,0 +1,29 @@
1+(* A code procedure: machine code written as bytes, called like any
2+ other procedure. cpuid's vendor string, from leaf 0. *)
3+module Cpu;
4+import Out;
5+
6+(* cpuid leaf 0: puts the 12 bytes of the vendor in buf, rdi. *)
7+proc vendor(buf: ^U8);
8+code 53H, (* push rbx *)
9+ 49H, 89H, 0F8H, (* mov r8, rdi *)
10+ 31H, 0C0H, (* xor eax, eax *)
11+ 0FH, 0A2H, (* cpuid *)
12+ 41H, 89H, 18H, (* mov [r8], ebx *)
13+ 41H, 89H, 50H, 04H, (* mov [r8+4], edx *)
14+ 41H, 89H, 48H, 08H, (* mov [r8+8], ecx *)
15+ 5BH, (* pop rbx *)
16+ 0C3H; (* ret *)
17+
18+proc main*;
19+var buf: [12]U8; i: I64; ok: BOOL;
20+begin
21+ vendor(ADR(buf[0]));
22+ ok := true;
23+ for i := 0 to 11 do
24+ if (buf[i] < ' ') or (buf[i] > '~') then ok := false; end;
25+ end;
26+ if ok then Out.str("vendor is printable\n"); end;
27+end;
28+
29+end Cpu.

examples/Flags.jed deleted +0 -44

@@ -1,44 +0,0 @@
1-(* Enumerations, sets, record literals and defer: Unix permissions as
2- sets, which are their bits, and a report that closes its brackets
3- however it leaves. *)
4-module Flags;
5-import Out;
6-
7-type
8- Perm = (x, w, r); (* bits 0, 1, 2, as chmod has them *)
9- Perms = set of Perm;
10- Mode = record user, group, other: Perms; end;
11-
12-proc digit(p: Perms): I64;
13-begin
14- return I64(U8(p));
15-end;
16-
17-proc show(p: Perms);
18-begin
19- if r in p then Out.str("r"); else Out.str("-"); end;
20- if w in p then Out.str("w"); else Out.str("-"); end;
21- if x in p then Out.str("x"); else Out.str("-"); end;
22-end;
23-
24-proc report(m: Mode);
25-begin
26- Out.str("[");
27- defer Out.str("]\n");
28- show(m.user); show(m.group); show(m.other);
29- if m.other = {} then return; end;
30- Out.str(" octal ");
31- Out.int(digit(m.user)); Out.int(digit(m.group)); Out.int(digit(m.other));
32-end;
33-
34-proc main*;
35-var m: Mode;
36-begin
37- m := {user: {r, w, x}, group: {r, x}, other: {r}};
38- report(m);
39- m.user := m.user - {x};
40- m.other := {};
41- report(m);
42-end;
43-
44-end Flags.

examples/Flags.raz (history) added +44 -0

@@ -0,0 +1,44 @@
1+(* Enumerations, sets, record literals and defer: Unix permissions as
2+ sets, which are their bits, and a report that closes its brackets
3+ however it leaves. *)
4+module Flags;
5+import Out;
6+
7+type
8+ Perm = (x, w, r); (* bits 0, 1, 2, as chmod has them *)
9+ Perms = set of Perm;
10+ Mode = record user, group, other: Perms; end;
11+
12+proc digit(p: Perms): I64;
13+begin
14+ return I64(U8(p));
15+end;
16+
17+proc show(p: Perms);
18+begin
19+ if r in p then Out.str("r"); else Out.str("-"); end;
20+ if w in p then Out.str("w"); else Out.str("-"); end;
21+ if x in p then Out.str("x"); else Out.str("-"); end;
22+end;
23+
24+proc report(m: Mode);
25+begin
26+ Out.str("[");
27+ defer Out.str("]\n");
28+ show(m.user); show(m.group); show(m.other);
29+ if m.other = {} then return; end;
30+ Out.str(" octal ");
31+ Out.int(digit(m.user)); Out.int(digit(m.group)); Out.int(digit(m.other));
32+end;
33+
34+proc main*;
35+var m: Mode;
36+begin
37+ m := {user: {r, w, x}, group: {r, x}, other: {r}};
38+ report(m);
39+ m.user := m.user - {x};
40+ m.other := {};
41+ report(m);
42+end;
43+
44+end Flags.

examples/Hello.jed deleted +0 -9

@@ -1,9 +0,0 @@
1-module Hello;
2-import Out;
3-
4-proc main*;
5-begin
6- Out.str("hello, world\n");
7-end;
8-
9-end Hello.

examples/Hello.raz (history) added +9 -0

@@ -0,0 +1,9 @@
1+module Hello;
2+import Out;
3+
4+proc main*;
5+begin
6+ Out.str("hello, world\n");
7+end;
8+
9+end Hello.

examples/Printf.expect (history) modified +3 -3

@@ -1,6 +1,6 @@
1-jed says 1
1+raz says 1
22 C says 1, squared
3-jed says 2
3+raz says 2
44 C says 4, squared
5-jed says 3
5+raz says 3
66 C says 9, squared

examples/Printf.jed deleted +0 -17

@@ -1,17 +0,0 @@
1-(* Out and C's printf, writing to the same standard output. Each keeps
2- a buffer of its own, so each is flushed before the other writes. *)
3-module Printf;
4-import Out, C;
5-
6-proc main*;
7-var i: I64;
8-begin
9- for i := 1 to 3 do
10- Out.str("jed says "); Out.int(i); Out.ln;
11- Out.flush;
12- C.printf("C says %d, %s\n", I32(i * i), "squared");
13- C.fflush(C.stdout);
14- end;
15-end;
16-
17-end Printf.

examples/Printf.raz (history) added +17 -0

@@ -0,0 +1,17 @@
1+(* Out and C's printf, writing to the same standard output. Each keeps
2+ a buffer of its own, so each is flushed before the other writes. *)
3+module Printf;
4+import Out, C;
5+
6+proc main*;
7+var i: I64;
8+begin
9+ for i := 1 to 3 do
10+ Out.str("raz says "); Out.int(i); Out.ln;
11+ Out.flush;
12+ C.printf("C says %d, %s\n", I32(i * i), "squared");
13+ C.fflush(C.stdout);
14+ end;
15+end;
16+
17+end Printf.

examples/Pthreads.jed deleted +0 -52

@@ -1,52 +0,0 @@
1-(* Threads from C's pthread_create, each summing its part of an array
2- and using the heap and Out, which lock themselves. *)
3-module Pthreads;
4-import Out, C, Heap, Mem;
5-
6-const
7- Workers = 4;
8- N = 1000000;
9-
10-type
11- Part = record lo, hi, sum: I64; end;
12- Numbers = [N]I64;
13-
14-var numbers: ^Numbers;
15-
16-proc work(arg: ^U8): ^U8;
17-var p: ^Part; i: I64; scratch: ^U8;
18-begin
19- p := ^Part(arg);
20- for i := p^.lo to p^.hi - 1 do
21- p^.sum := p^.sum + numbers^[i];
22- if i mod 1000 = 0 then
23- scratch := Mem.alloc(Heap.heap, 100, 8);
24- Mem.free(Heap.heap, scratch);
25- end;
26- end;
27- Out.str("a part summed\n");
28- return nil;
29-end;
30-
31-proc main*: I64;
32-var t: [Workers]U64; parts: [Workers]Part; i, total: I64;
33-begin
34- NEW(numbers, Heap.heap);
35- for i := 0 to N - 1 do numbers^[i] := i + 1; end;
36- for i := 0 to Workers - 1 do
37- parts[i] := {lo: i * N div Workers, hi: (i + 1) * N div Workers};
38- if C.pthread_create(ADR(t[i]), nil, work, ^U8(ADR(parts[i]))) # 0 then
39- Out.str("can't start a thread\n");
40- return 1;
41- end;
42- end;
43- total := 0;
44- for i := 0 to Workers - 1 do
45- C.pthread_join(t[i], nil);
46- total := total + parts[i].sum;
47- end;
48- Out.str("total "); Out.int(total); Out.ln;
49- return 0;
50-end;
51-
52-end Pthreads.

examples/Pthreads.raz (history) added +52 -0

@@ -0,0 +1,52 @@
1+(* Threads from C's pthread_create, each summing its part of an array
2+ and using the heap and Out, which lock themselves. *)
3+module Pthreads;
4+import Out, C, Heap, Mem;
5+
6+const
7+ Workers = 4;
8+ N = 1000000;
9+
10+type
11+ Part = record lo, hi, sum: I64; end;
12+ Numbers = [N]I64;
13+
14+var numbers: ^Numbers;
15+
16+proc work(arg: ^U8): ^U8;
17+var p: ^Part; i: I64; scratch: ^U8;
18+begin
19+ p := ^Part(arg);
20+ for i := p^.lo to p^.hi - 1 do
21+ p^.sum := p^.sum + numbers^[i];
22+ if i mod 1000 = 0 then
23+ scratch := Mem.alloc(Heap.heap, 100, 8);
24+ Mem.free(Heap.heap, scratch);
25+ end;
26+ end;
27+ Out.str("a part summed\n");
28+ return nil;
29+end;
30+
31+proc main*: I64;
32+var t: [Workers]U64; parts: [Workers]Part; i, total: I64;
33+begin
34+ NEW(numbers, Heap.heap);
35+ for i := 0 to N - 1 do numbers^[i] := i + 1; end;
36+ for i := 0 to Workers - 1 do
37+ parts[i] := {lo: i * N div Workers, hi: (i + 1) * N div Workers};
38+ if C.pthread_create(ADR(t[i]), nil, work, ^U8(ADR(parts[i]))) # 0 then
39+ Out.str("can't start a thread\n");
40+ return 1;
41+ end;
42+ end;
43+ total := 0;
44+ for i := 0 to Workers - 1 do
45+ C.pthread_join(t[i], nil);
46+ total := total + parts[i].sum;
47+ end;
48+ Out.str("total "); Out.int(total); Out.ln;
49+ return 0;
50+end;
51+
52+end Pthreads.

examples/Shapes.jed deleted +0 -39

@@ -1,39 +0,0 @@
1-(* Variants and slices: a list of shapes, measured. *)
2-module Shapes;
3-import Out;
4-
5-type
6- Shape = variant
7- circle(r: I64);
8- rect(w, h: I64);
9- dot;
10- end;
11-
12-(* Twice the area, rounded down, of a circle taken as pi = 22/7. *)
13-proc area(s: Shape): I64;
14-begin
15- match s of
16- | circle(r): return 44 * r * r div 7;
17- | rect(w, h): return 2 * w * h;
18- | dot: return 0;
19- end;
20-end;
21-
22-proc total(shapes: []Shape): I64;
23-var i, sum: I64;
24-begin
25- sum := 0;
26- for i := 0 to LEN(shapes) - 1 do sum := sum + area(shapes[i]); end;
27- return sum;
28-end;
29-
30-proc main*;
31-var shapes: [4]Shape;
32-begin
33- shapes := [circle(7), rect(3, 4), dot, rect(1, 1)];
34- Out.str("all: "); Out.int(total(shapes)); Out.ln;
35- Out.str("last two: "); Out.int(total(shapes[2..4])); Out.ln;
36- Out.str("none: "); Out.int(total(shapes[0..0])); Out.ln;
37-end;
38-
39-end Shapes.

examples/Shapes.raz (history) added +39 -0

@@ -0,0 +1,39 @@
1+(* Variants and slices: a list of shapes, measured. *)
2+module Shapes;
3+import Out;
4+
5+type
6+ Shape = variant
7+ circle(r: I64);
8+ rect(w, h: I64);
9+ dot;
10+ end;
11+
12+(* Twice the area, rounded down, of a circle taken as pi = 22/7. *)
13+proc area(s: Shape): I64;
14+begin
15+ match s of
16+ | circle(r): return 44 * r * r div 7;
17+ | rect(w, h): return 2 * w * h;
18+ | dot: return 0;
19+ end;
20+end;
21+
22+proc total(shapes: []Shape): I64;
23+var i, sum: I64;
24+begin
25+ sum := 0;
26+ for i := 0 to LEN(shapes) - 1 do sum := sum + area(shapes[i]); end;
27+ return sum;
28+end;
29+
30+proc main*;
31+var shapes: [4]Shape;
32+begin
33+ shapes := [circle(7), rect(3, 4), dot, rect(1, 1)];
34+ Out.str("all: "); Out.int(total(shapes)); Out.ln;
35+ Out.str("last two: "); Out.int(total(shapes[2..4])); Out.ln;
36+ Out.str("none: "); Out.int(total(shapes[0..0])); Out.ln;
37+end;
38+
39+end Shapes.

examples/Volatile.jed deleted +0 -32

@@ -1,32 +0,0 @@
1-(* A record laid over memory that something else may change: here a
2- page of the program's own, as a device's registers would be. Every
3- access through the ^VOLATILE pointer is one instruction of its
4- size, in the order written. *)
5-module Volatile;
6-import Out;
7-
8-type
9- Uart = record
10- data: U32;
11- status: U32;
12- control: U8;
13- end;
14-
15-var page: [64]U8;
16-
17-proc main*;
18-var dev: ^VOLATILE Uart; i: I64;
19-begin
20- dev := ^VOLATILE Uart(ADR(page));
21- dev^.control := 1;
22- dev^.status := 0FFH;
23- for i := 0 to 2 do
24- dev^.data := U32('a' + i);
25- Out.char(U8(dev^.data));
26- end;
27- Out.ln;
28- FENCE;
29- Out.int(I64(page[8])); Out.str(" "); Out.int(I64(dev^.status)); Out.ln;
30-end;
31-
32-end Volatile.

examples/Volatile.raz (history) added +32 -0

@@ -0,0 +1,32 @@
1+(* A record laid over memory that something else may change: here a
2+ page of the program's own, as a device's registers would be. Every
3+ access through the ^VOLATILE pointer is one instruction of its
4+ size, in the order written. *)
5+module Volatile;
6+import Out;
7+
8+type
9+ Uart = record
10+ data: U32;
11+ status: U32;
12+ control: U8;
13+ end;
14+
15+var page: [64]U8;
16+
17+proc main*;
18+var dev: ^VOLATILE Uart; i: I64;
19+begin
20+ dev := ^VOLATILE Uart(ADR(page));
21+ dev^.control := 1;
22+ dev^.status := 0FFH;
23+ for i := 0 to 2 do
24+ dev^.data := U32('a' + i);
25+ Out.char(U8(dev^.data));
26+ end;
27+ Out.ln;
28+ FENCE;
29+ Out.int(I64(page[8])); Out.str(" "); Out.int(I64(dev^.status)); Out.ln;
30+end;
31+
32+end Volatile.

examples/Window.jed deleted +0 -70

@@ -1,70 +0,0 @@
1-(* An X11 window that says hello, and closes at a key press. An XEvent
2- is a C union: it is read as an array of words, and the member its
3- type says it holds through a pointer conversion. Compiled by make
4- check, not run: it needs a display. *)
5-module Window;
6-import Out;
7-link "libX11.so.6";
8-
9-const
10- KeyPress = 2;
11- Expose = 12;
12- KeyPressMask = 1;
13- ExposureMask = 8000H;
14-
15-type
16- (* XKeyEvent, laid out as C lays it out *)
17- KeyEvent = record
18- typ: I32;
19- serial: U64;
20- sendEvent: I32;
21- display: ^U8;
22- window, root, subwindow, time: U64;
23- x, y, xRoot, yRoot: I32;
24- state, keycode: U32;
25- sameScreen: I32;
26- end;
27-
28-extern proc XOpenDisplay(name: ^U8): ^U8;
29-extern proc XDefaultScreen(d: ^U8): I32;
30-extern proc XRootWindow(d: ^U8; screen: I32): U64;
31-extern proc XBlackPixel(d: ^U8; screen: I32): U64;
32-extern proc XWhitePixel(d: ^U8; screen: I32): U64;
33-extern proc XDefaultGC(d: ^U8; screen: I32): ^U8;
34-extern proc XCreateSimpleWindow(d: ^U8; parent: U64; x, y: I32;
35- width, height, border: U32; borderColor, background: U64): U64;
36-extern proc XStoreName(d: ^U8; w: U64; name: ^U8): I32;
37-extern proc XSelectInput(d: ^U8; w: U64; mask: I64): I32;
38-extern proc XMapWindow(d: ^U8; w: U64): I32;
39-extern proc XNextEvent(d: ^U8; ev: ^U8): I32;
40-extern proc XDrawString(d: ^U8; w: U64; gc: ^U8; x, y: I32; s: ^U8; n: I32): I32;
41-extern proc XCloseDisplay(d: ^U8): I32;
42-
43-proc main*: I64;
44-const text = "hello, world: press a key";
45-var
46- d: ^U8; s: I32; w: U64;
47- ev: [24]I64; (* XEvent: 192 bytes *)
48- key: ^KeyEvent;
49-begin
50- d := XOpenDisplay(nil);
51- if d = nil then Out.str("no display\n"); return 1; end;
52- s := XDefaultScreen(d);
53- w := XCreateSimpleWindow(d, XRootWindow(d, s), 0, 0, 320, 80, 1,
54- XBlackPixel(d, s), XWhitePixel(d, s));
55- XStoreName(d, w, "jed");
56- XSelectInput(d, w, ExposureMask + KeyPressMask);
57- XMapWindow(d, w);
58- repeat
59- XNextEvent(d, ^U8(ADR(ev)));
60- if I32(ev[0]) = Expose then
61- XDrawString(d, w, XDefaultGC(d, s), 20, 45, text, I32(LEN(text)));
62- end;
63- until I32(ev[0]) = KeyPress;
64- key := ^KeyEvent(ADR(ev));
65- Out.str("key "); Out.int(I64(key^.keycode)); Out.ln;
66- XCloseDisplay(d);
67- return 0;
68-end;
69-
70-end Window.

examples/Window.raz (history) added +70 -0

@@ -0,0 +1,70 @@
1+(* An X11 window that says hello, and closes at a key press. An XEvent
2+ is a C union: it is read as an array of words, and the member its
3+ type says it holds through a pointer conversion. Compiled by make
4+ check, not run: it needs a display. *)
5+module Window;
6+import Out;
7+link "libX11.so.6";
8+
9+const
10+ KeyPress = 2;
11+ Expose = 12;
12+ KeyPressMask = 1;
13+ ExposureMask = 8000H;
14+
15+type
16+ (* XKeyEvent, laid out as C lays it out *)
17+ KeyEvent = record
18+ typ: I32;
19+ serial: U64;
20+ sendEvent: I32;
21+ display: ^U8;
22+ window, root, subwindow, time: U64;
23+ x, y, xRoot, yRoot: I32;
24+ state, keycode: U32;
25+ sameScreen: I32;
26+ end;
27+
28+extern proc XOpenDisplay(name: ^U8): ^U8;
29+extern proc XDefaultScreen(d: ^U8): I32;
30+extern proc XRootWindow(d: ^U8; screen: I32): U64;
31+extern proc XBlackPixel(d: ^U8; screen: I32): U64;
32+extern proc XWhitePixel(d: ^U8; screen: I32): U64;
33+extern proc XDefaultGC(d: ^U8; screen: I32): ^U8;
34+extern proc XCreateSimpleWindow(d: ^U8; parent: U64; x, y: I32;
35+ width, height, border: U32; borderColor, background: U64): U64;
36+extern proc XStoreName(d: ^U8; w: U64; name: ^U8): I32;
37+extern proc XSelectInput(d: ^U8; w: U64; mask: I64): I32;
38+extern proc XMapWindow(d: ^U8; w: U64): I32;
39+extern proc XNextEvent(d: ^U8; ev: ^U8): I32;
40+extern proc XDrawString(d: ^U8; w: U64; gc: ^U8; x, y: I32; s: ^U8; n: I32): I32;
41+extern proc XCloseDisplay(d: ^U8): I32;
42+
43+proc main*: I64;
44+const text = "hello, world: press a key";
45+var
46+ d: ^U8; s: I32; w: U64;
47+ ev: [24]I64; (* XEvent: 192 bytes *)
48+ key: ^KeyEvent;
49+begin
50+ d := XOpenDisplay(nil);
51+ if d = nil then Out.str("no display\n"); return 1; end;
52+ s := XDefaultScreen(d);
53+ w := XCreateSimpleWindow(d, XRootWindow(d, s), 0, 0, 320, 80, 1,
54+ XBlackPixel(d, s), XWhitePixel(d, s));
55+ XStoreName(d, w, "raz");
56+ XSelectInput(d, w, ExposureMask + KeyPressMask);
57+ XMapWindow(d, w);
58+ repeat
59+ XNextEvent(d, ^U8(ADR(ev)));
60+ if I32(ev[0]) = Expose then
61+ XDrawString(d, w, XDefaultGC(d, s), 20, 45, text, I32(LEN(text)));
62+ end;
63+ until I32(ev[0]) = KeyPress;
64+ key := ^KeyEvent(ADR(ev));
65+ Out.str("key "); Out.int(I64(key^.keycode)); Out.ln;
66+ XCloseDisplay(d);
67+ return 0;
68+end;
69+
70+end Window.

examples/Words.jed deleted +0 -37

@@ -1,37 +0,0 @@
1-(* Generic modules: counts the words of a text in a Map from []U8 to
2- I64, hashed and compared by Str's procedures, keeps them in order of
3- first sight in a List([]U8), and prints them with Fmt. *)
4-module Words;
5-import Fmt, Str, Heap, Count := Map([]U8, I64, Str.hash, Str.eq), Names := List([]U8);
6-
7-const Text = "the cat and the hat and the bat";
8-
9-proc main*;
10-var
11- counts: Count.Map; order: Names.List; n: ^Names.Node;
12- i, start, k, total: I64; found, ok: BOOL; w: []U8;
13-begin
14- Count.init(ADR(counts), Heap.heap);
15- Names.init(ADR(order), Heap.heap);
16- start := 0;
17- for i := 0 to LEN(Text) do
18- if (i = LEN(Text)) or (Text[i] = ' ') then
19- w := Text[start..i];
20- INC(total);
21- k, found := Count.get(ADR(counts), w);
22- if not found then ok := Names.push(ADR(order), w); end;
23- ok := Count.put(ADR(counts), w, k + 1);
24- start := i + 1;
25- end;
26- end;
27- Names.reverse(ADR(order));
28- n := order.head;
29- while n # nil do
30- k, found := Count.get(ADR(counts), n^.val);
31- Fmt.print("{} {}\n", [Fmt.str(n^.val), Fmt.int(k)]);
32- n := n^.next;
33- end;
34- Fmt.print("{} words, {} different\n", [Fmt.int(total), Fmt.int(counts.len)]);
35-end;
36-
37-end Words.

examples/Words.raz (history) added +37 -0

@@ -0,0 +1,37 @@
1+(* Generic modules: counts the words of a text in a Map from []U8 to
2+ I64, hashed and compared by Str's procedures, keeps them in order of
3+ first sight in a List([]U8), and prints them with Fmt. *)
4+module Words;
5+import Fmt, Str, Heap, Count := Map([]U8, I64, Str.hash, Str.eq), Names := List([]U8);
6+
7+const Text = "the cat and the hat and the bat";
8+
9+proc main*;
10+var
11+ counts: Count.Map; order: Names.List; n: ^Names.Node;
12+ i, start, k, total: I64; found, ok: BOOL; w: []U8;
13+begin
14+ Count.init(ADR(counts), Heap.heap);
15+ Names.init(ADR(order), Heap.heap);
16+ start := 0;
17+ for i := 0 to LEN(Text) do
18+ if (i = LEN(Text)) or (Text[i] = ' ') then
19+ w := Text[start..i];
20+ INC(total);
21+ k, found := Count.get(ADR(counts), w);
22+ if not found then ok := Names.push(ADR(order), w); end;
23+ ok := Count.put(ADR(counts), w, k + 1);
24+ start := i + 1;
25+ end;
26+ end;
27+ Names.reverse(ADR(order));
28+ n := order.head;
29+ while n # nil do
30+ k, found := Count.get(ADR(counts), n^.val);
31+ Fmt.print("{} {}\n", [Fmt.str(n^.val), Fmt.int(k)]);
32+ n := n^.next;
33+ end;
34+ Fmt.print("{} words, {} different\n", [Fmt.int(total), Fmt.int(counts.len)]);
35+end;
36+
37+end Words.

examples/Workers.jed deleted +0 -48

@@ -1,48 +0,0 @@
1-(* Native threads, for a program without C: workers that take jobs
2- from a shared counter and add up their results under a Mutex. *)
3-module Workers;
4-import Out, Thread;
5-
6-const
7- Workers = 4;
8- Jobs = 100;
9-
10-var
11- next: I64; (* the next job, taken with XADD *)
12- m: Thread.Mutex;
13- total: I64;
14-
15-(* job n: the sum of the squares up to n *)
16-proc job(n: I64): I64;
17-var i, s: I64;
18-begin
19- s := 0;
20- for i := 1 to n do s := s + i * i; end;
21- return s;
22-end;
23-
24-proc work(arg: ^U8);
25-var n, r: I64;
26-begin
27- n := XADD(ADR(next), 1);
28- while n < Jobs do
29- r := job(n * 1000);
30- Thread.lock(ADR(m));
31- total := total + r;
32- Thread.unlock(ADR(m));
33- n := XADD(ADR(next), 1);
34- end;
35-end;
36-
37-proc main*;
38-var t: [Workers]^Thread.Thread; i: I64; err: ERROR;
39-begin
40- for i := 0 to Workers - 1 do
41- t[i], err := Thread.spawn(work, nil);
42- if err # nil then Out.str(MSG(err)); Out.ln; return; end;
43- end;
44- for i := 0 to Workers - 1 do Thread.join(t[i]); end;
45- Out.str("total "); Out.int(total); Out.ln;
46-end;
47-
48-end Workers.

examples/Workers.raz (history) added +48 -0

@@ -0,0 +1,48 @@
1+(* Native threads, for a program without C: workers that take jobs
2+ from a shared counter and add up their results under a Mutex. *)
3+module Workers;
4+import Out, Thread;
5+
6+const
7+ Workers = 4;
8+ Jobs = 100;
9+
10+var
11+ next: I64; (* the next job, taken with XADD *)
12+ m: Thread.Mutex;
13+ total: I64;
14+
15+(* job n: the sum of the squares up to n *)
16+proc job(n: I64): I64;
17+var i, s: I64;
18+begin
19+ s := 0;
20+ for i := 1 to n do s := s + i * i; end;
21+ return s;
22+end;
23+
24+proc work(arg: ^U8);
25+var n, r: I64;
26+begin
27+ n := XADD(ADR(next), 1);
28+ while n < Jobs do
29+ r := job(n * 1000);
30+ Thread.lock(ADR(m));
31+ total := total + r;
32+ Thread.unlock(ADR(m));
33+ n := XADD(ADR(next), 1);
34+ end;
35+end;
36+
37+proc main*;
38+var t: [Workers]^Thread.Thread; i: I64; err: ERROR;
39+begin
40+ for i := 0 to Workers - 1 do
41+ t[i], err := Thread.spawn(work, nil);
42+ if err # nil then Out.str(MSG(err)); Out.ln; return; end;
43+ end;
44+ for i := 0 to Workers - 1 do Thread.join(t[i]); end;
45+ Out.str("total "); Out.int(total); Out.ln;
46+end;
47+
48+end Workers.

lib/Arena.jed deleted +0 -68

@@ -1,68 +0,0 @@
1-(* An allocator that hands out memory from one block and frees it all
2- at once: free does nothing, reset forgets everything. An Arena is
3- its allocator: ADR(arena.base) is the ^Mem.Allocator to give NEW. *)
4-module Arena;
5-import Mem, Rt;
6-
7-type
8- Arena* = record
9- base*: Mem.Allocator; (* first, so that ^Arena(a) finds the rest *)
10- buf: ^U8;
11- used, cap: I64;
12- end;
13-
14-proc alloc(a: ^Mem.Allocator; size, align: I64): ^U8;
15-var ar: ^Arena; at: I64;
16-begin
17- ar := ^Arena(a);
18- at := (ar^.used + align - 1) div align * align;
19- if (size < 0) or (at + size > ar^.cap) then return nil; end;
20- ar^.used := at + size;
21- return ar^.buf + at;
22-end;
23-
24-proc free(a: ^Mem.Allocator; p: ^U8);
25-begin
26-end;
27-
28-(* An arena of size bytes; false if the system has none. *)
29-proc init*(ar: ^Arena; size: I64): BOOL;
30-begin
31- ar^.base := {alloc: alloc, free: free};
32- ar^.buf := Mem.pages(size);
33- ar^.used := 0;
34- ar^.cap := size;
35- if ar^.buf = nil then ar^.cap := 0; end;
36- return ar^.buf # nil;
37-end;
38-
39-(* Forgets every allocation; the memory is used again. *)
40-proc reset*(ar: ^Arena);
41-begin
42- ar^.used := 0;
43-end;
44-
45-proc done*(ar: ^Arena);
46-begin
47- if ar^.buf # nil then Mem.unmap(ar^.buf, ar^.cap); end;
48- ar^.buf := nil;
49- ar^.cap := 0;
50-end;
51-
52-(* The module's test. *)
53-proc main*;
54-var ar: Arena; a: ^Mem.Allocator; p, q: ^U8;
55-begin
56- if not init(ADR(ar), 4096) then Rt.stop("Arena.init"); end;
57- a := ADR(ar.base);
58- p := Mem.alloc(a, 3, 1);
59- q := Mem.alloc(a, 8, 8);
60- if (p = nil) or (q # p + 8) then Rt.stop("Arena: alignment"); end;
61- if Mem.alloc(a, 5000, 1) # nil then Rt.stop("Arena: too big"); end;
62- if Mem.alloc(a, -1, 1) # nil then Rt.stop("Arena: negative"); end;
63- reset(ADR(ar));
64- if Mem.alloc(a, 4096, 1) # p then Rt.stop("Arena.reset"); end;
65- done(ADR(ar));
66-end;
67-
68-end Arena.

lib/Arena.raz (history) added +68 -0

@@ -0,0 +1,68 @@
1+(* An allocator that hands out memory from one block and frees it all
2+ at once: free does nothing, reset forgets everything. An Arena is
3+ its allocator: ADR(arena.base) is the ^Mem.Allocator to give NEW. *)
4+module Arena;
5+import Mem, Rt;
6+
7+type
8+ Arena* = record
9+ base*: Mem.Allocator; (* first, so that ^Arena(a) finds the rest *)
10+ buf: ^U8;
11+ used, cap: I64;
12+ end;
13+
14+proc alloc(a: ^Mem.Allocator; size, align: I64): ^U8;
15+var ar: ^Arena; at: I64;
16+begin
17+ ar := ^Arena(a);
18+ at := (ar^.used + align - 1) div align * align;
19+ if (size < 0) or (at + size > ar^.cap) then return nil; end;
20+ ar^.used := at + size;
21+ return ar^.buf + at;
22+end;
23+
24+proc free(a: ^Mem.Allocator; p: ^U8);
25+begin
26+end;
27+
28+(* An arena of size bytes; false if the system has none. *)
29+proc init*(ar: ^Arena; size: I64): BOOL;
30+begin
31+ ar^.base := {alloc: alloc, free: free};
32+ ar^.buf := Mem.pages(size);
33+ ar^.used := 0;
34+ ar^.cap := size;
35+ if ar^.buf = nil then ar^.cap := 0; end;
36+ return ar^.buf # nil;
37+end;
38+
39+(* Forgets every allocation; the memory is used again. *)
40+proc reset*(ar: ^Arena);
41+begin
42+ ar^.used := 0;
43+end;
44+
45+proc done*(ar: ^Arena);
46+begin
47+ if ar^.buf # nil then Mem.unmap(ar^.buf, ar^.cap); end;
48+ ar^.buf := nil;
49+ ar^.cap := 0;
50+end;
51+
52+(* The module's test. *)
53+proc main*;
54+var ar: Arena; a: ^Mem.Allocator; p, q: ^U8;
55+begin
56+ if not init(ADR(ar), 4096) then Rt.stop("Arena.init"); end;
57+ a := ADR(ar.base);
58+ p := Mem.alloc(a, 3, 1);
59+ q := Mem.alloc(a, 8, 8);
60+ if (p = nil) or (q # p + 8) then Rt.stop("Arena: alignment"); end;
61+ if Mem.alloc(a, 5000, 1) # nil then Rt.stop("Arena: too big"); end;
62+ if Mem.alloc(a, -1, 1) # nil then Rt.stop("Arena: negative"); end;
63+ reset(ADR(ar));
64+ if Mem.alloc(a, 4096, 1) # p then Rt.stop("Arena.reset"); end;
65+ done(ADR(ar));
66+end;
67+
68+end Arena.

lib/Buf.jed deleted +0 -91

@@ -1,91 +0,0 @@
1-(* A growable byte buffer, its memory from an allocator. *)
2-module Buf;
3-import Mem, Arena, Rt;
4-
5-type
6- Buf* = record
7- a: ^Mem.Allocator;
8- data: ^U8;
9- len*, cap: I64;
10- end;
11-
12-proc init*(b: ^Buf; a: ^Mem.Allocator);
13-begin
14- b^ := {a: a};
15-end;
16-
17-(* Room for n more bytes; false if the allocator has none. *)
18-proc room*(b: ^Buf; n: I64): BOOL;
19-var cap, i: I64; p: ^U8;
20-begin
21- if b^.len + n <= b^.cap then return true; end;
22- cap := b^.cap * 2;
23- if cap < 64 then cap := 64; end;
24- while cap < b^.len + n do cap := cap * 2; end;
25- p := Mem.alloc(b^.a, cap, 1);
26- if p = nil then return false; end;
27- for i := 0 to b^.len - 1 do p[i] := b^.data[i]; end;
28- if b^.data # nil then Mem.free(b^.a, b^.data); end;
29- b^.data := p;
30- b^.cap := cap;
31- return true;
32-end;
33-
34-proc add*(b: ^Buf; c: U8);
35-begin
36- if room(b, 1) then
37- b^.data[b^.len] := c;
38- INC(b^.len);
39- end;
40-end;
41-
42-proc str*(b: ^Buf; s: []U8);
43-var i: I64;
44-begin
45- if room(b, LEN(s)) then
46- for i := 0 to LEN(s) - 1 do b^.data[b^.len + i] := s[i]; end;
47- INC(b^.len, LEN(s));
48- end;
49-end;
50-
51-(* What the buffer holds, until it next grows. *)
52-proc bytes*(b: ^Buf): []U8;
53-begin
54- if b^.len = 0 then return ""; end;
55- return b^.data[0..b^.len];
56-end;
57-
58-proc reset*(b: ^Buf);
59-begin
60- b^.len := 0;
61-end;
62-
63-proc done*(b: ^Buf);
64-begin
65- if b^.data # nil then Mem.free(b^.a, b^.data); end;
66- b^.data := nil;
67- b^.len := 0;
68- b^.cap := 0;
69-end;
70-
71-(* The module's test, over an arena. *)
72-proc main*;
73-var ar: Arena.Arena; b: Buf; i: I64; s: []U8;
74-begin
75- if not Arena.init(ADR(ar), 1 shl 20) then Rt.stop("Buf: no arena"); end;
76- init(ADR(b), ADR(ar.base));
77- if LEN(bytes(ADR(b))) # 0 then Rt.stop("Buf: not empty"); end;
78- for i := 0 to 9999 do add(ADR(b), U8(i mod 251)); end;
79- str(ADR(b), "end");
80- s := bytes(ADR(b));
81- if (LEN(s) # 10003) or (s[9998] # U8(9998 mod 251)) or (s[10000..10003] # "end") then
82- Rt.stop("Buf: contents");
83- end;
84- reset(ADR(b));
85- str(ADR(b), "again");
86- if bytes(ADR(b)) # "again" then Rt.stop("Buf.reset"); end;
87- done(ADR(b));
88- Arena.done(ADR(ar));
89-end;
90-
91-end Buf.

lib/Buf.raz (history) added +91 -0

@@ -0,0 +1,91 @@
1+(* A growable byte buffer, its memory from an allocator. *)
2+module Buf;
3+import Mem, Arena, Rt;
4+
5+type
6+ Buf* = record
7+ a: ^Mem.Allocator;
8+ data: ^U8;
9+ len*, cap: I64;
10+ end;
11+
12+proc init*(b: ^Buf; a: ^Mem.Allocator);
13+begin
14+ b^ := {a: a};
15+end;
16+
17+(* Room for n more bytes; false if the allocator has none. *)
18+proc room*(b: ^Buf; n: I64): BOOL;
19+var cap, i: I64; p: ^U8;
20+begin
21+ if b^.len + n <= b^.cap then return true; end;
22+ cap := b^.cap * 2;
23+ if cap < 64 then cap := 64; end;
24+ while cap < b^.len + n do cap := cap * 2; end;
25+ p := Mem.alloc(b^.a, cap, 1);
26+ if p = nil then return false; end;
27+ for i := 0 to b^.len - 1 do p[i] := b^.data[i]; end;
28+ if b^.data # nil then Mem.free(b^.a, b^.data); end;
29+ b^.data := p;
30+ b^.cap := cap;
31+ return true;
32+end;
33+
34+proc add*(b: ^Buf; c: U8);
35+begin
36+ if room(b, 1) then
37+ b^.data[b^.len] := c;
38+ INC(b^.len);
39+ end;
40+end;
41+
42+proc str*(b: ^Buf; s: []U8);
43+var i: I64;
44+begin
45+ if room(b, LEN(s)) then
46+ for i := 0 to LEN(s) - 1 do b^.data[b^.len + i] := s[i]; end;
47+ INC(b^.len, LEN(s));
48+ end;
49+end;
50+
51+(* What the buffer holds, until it next grows. *)
52+proc bytes*(b: ^Buf): []U8;
53+begin
54+ if b^.len = 0 then return ""; end;
55+ return b^.data[0..b^.len];
56+end;
57+
58+proc reset*(b: ^Buf);
59+begin
60+ b^.len := 0;
61+end;
62+
63+proc done*(b: ^Buf);
64+begin
65+ if b^.data # nil then Mem.free(b^.a, b^.data); end;
66+ b^.data := nil;
67+ b^.len := 0;
68+ b^.cap := 0;
69+end;
70+
71+(* The module's test, over an arena. *)
72+proc main*;
73+var ar: Arena.Arena; b: Buf; i: I64; s: []U8;
74+begin
75+ if not Arena.init(ADR(ar), 1 shl 20) then Rt.stop("Buf: no arena"); end;
76+ init(ADR(b), ADR(ar.base));
77+ if LEN(bytes(ADR(b))) # 0 then Rt.stop("Buf: not empty"); end;
78+ for i := 0 to 9999 do add(ADR(b), U8(i mod 251)); end;
79+ str(ADR(b), "end");
80+ s := bytes(ADR(b));
81+ if (LEN(s) # 10003) or (s[9998] # U8(9998 mod 251)) or (s[10000..10003] # "end") then
82+ Rt.stop("Buf: contents");
83+ end;
84+ reset(ADR(b));
85+ str(ADR(b), "again");
86+ if bytes(ADR(b)) # "again" then Rt.stop("Buf.reset"); end;
87+ done(ADR(b));
88+ Arena.done(ADR(ar));
89+end;
90+
91+end Buf.

lib/C.jed deleted +0 -25

@@ -1,25 +0,0 @@
1-(* The C library: what jed's own library calls in it, and what most
2- programs reach for. A program that imports C uses C, and so is
3- linked dynamically and starts through the C library. *)
4-module C;
5-
6-extern proc write*(fd: I32; buf: ^U8; n: U64): I64;
7-extern proc read*(fd: I32; buf: ^U8; n: U64): I64;
8-extern proc open*(path: ^U8; flags: I32; ...): I32;
9-extern proc creat*(path: ^U8; mode: U32): I32;
10-extern proc close*(fd: I32): I32;
11-extern proc mmap*(addr: ^U8; n: U64; prot, flags, fd: I32; off: I64): ^U8;
12-extern proc munmap*(addr: ^U8; n: U64): I32;
13-extern proc isatty*(fd: I32): I32;
14-extern proc exit*(status: I32);
15-extern proc _exit*(status: I32);
16-extern proc __errno_location*: ^I32; (* errno is this thread's: through here *)
17-extern proc sched_yield*: I32;
18-extern proc pthread_create*(t: ^U64; attr: ^U8; start: proc(arg: ^U8): ^U8; arg: ^U8): I32;
19-extern proc pthread_join*(t: U64; result: ^^U8): I32;
20-extern proc printf*(format: ^U8; ...): I32;
21-extern proc fflush*(f: ^U8): I32;
22-extern var stdout*: ^U8; (* FILE * *)
23-extern var stderr*: ^U8;
24-
25-end C.

lib/C.raz (history) added +25 -0

@@ -0,0 +1,25 @@
1+(* The C library: what raz's own library calls in it, and what most
2+ programs reach for. A program that imports C uses C, and so is
3+ linked dynamically and starts through the C library. *)
4+module C;
5+
6+extern proc write*(fd: I32; buf: ^U8; n: U64): I64;
7+extern proc read*(fd: I32; buf: ^U8; n: U64): I64;
8+extern proc open*(path: ^U8; flags: I32; ...): I32;
9+extern proc creat*(path: ^U8; mode: U32): I32;
10+extern proc close*(fd: I32): I32;
11+extern proc mmap*(addr: ^U8; n: U64; prot, flags, fd: I32; off: I64): ^U8;
12+extern proc munmap*(addr: ^U8; n: U64): I32;
13+extern proc isatty*(fd: I32): I32;
14+extern proc exit*(status: I32);
15+extern proc _exit*(status: I32);
16+extern proc __errno_location*: ^I32; (* errno is this thread's: through here *)
17+extern proc sched_yield*: I32;
18+extern proc pthread_create*(t: ^U64; attr: ^U8; start: proc(arg: ^U8): ^U8; arg: ^U8): I32;
19+extern proc pthread_join*(t: U64; result: ^^U8): I32;
20+extern proc printf*(format: ^U8; ...): I32;
21+extern proc fflush*(f: ^U8): I32;
22+extern var stdout*: ^U8; (* FILE * *)
23+extern var stderr*: ^U8;
24+
25+end C.

lib/Fmt.jed deleted +0 -105

@@ -1,105 +0,0 @@
1-(* Formatted output. Each {} in the format takes the next argument:
2- Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)]);
3- {{ and }} stand for { and }. print writes to standard output,
4- write appends to a Buf. *)
5-module Fmt;
6-import Out, Buf, Arena, Rt;
7-
8-type
9- Arg* = variant
10- int(i: I64);
11- uint(u: U64);
12- hex(h: U64);
13- str(s: []U8);
14- char(c: U8);
15- bool(b: BOOL);
16- end;
17-
18-(* The digits of u in base, at the end of the array: it and where they start. *)
19-proc digits(u: U64; base: U64): ([24]U8, I64);
20-var d: [24]U8; i: I64; v: U8;
21-begin
22- i := 24;
23- repeat
24- DEC(i);
25- v := U8(u mod base);
26- if v < 10 then d[i] := v + '0'; else d[i] := v - 10 + 'A'; end;
27- u := u div base;
28- until u = 0;
29- return d, i;
30-end;
31-
32-(* Where the pieces go: to b, or to standard output if b is nil. *)
33-proc put(b: ^Buf.Buf; s: []U8);
34-begin
35- if b = nil then Out.str(s); else Buf.str(b, s); end;
36-end;
37-
38-proc arg(b: ^Buf.Buf; a: Arg);
39-var d: [24]U8; at: I64; one: [1]U8;
40-begin
41- match a of
42- | int(i):
43- if i < 0 then
44- put(b, "-");
45- d, at := digits(0 - U64(i), 10);
46- else
47- d, at := digits(U64(i), 10);
48- end;
49- put(b, d[at..24]);
50- | uint(u): d, at := digits(u, 10); put(b, d[at..24]);
51- | hex(h): d, at := digits(h, 16); put(b, d[at..24]);
52- | str(s): put(b, s);
53- | char(c): one[0] := c; put(b, one);
54- | bool(t): if t then put(b, "true"); else put(b, "false"); end;
55- end;
56-end;
57-
58-proc format(b: ^Buf.Buf; f: []U8; args: []Arg);
59-var i, start, n: I64;
60-begin
61- i := 0; start := 0; n := 0;
62- while i < LEN(f) do
63- if (f[i] = '{') or (f[i] = '}') then
64- put(b, f[start..i]);
65- if (i + 1 < LEN(f)) and (f[i + 1] = f[i]) then
66- put(b, f[i..i + 1]);
67- INC(i);
68- elsif (f[i] = '{') and (i + 1 < LEN(f)) and (f[i + 1] = '}') then
69- if n < LEN(args) then arg(b, args[n]); end;
70- INC(n);
71- INC(i);
72- end;
73- start := i + 1;
74- end;
75- INC(i);
76- end;
77- put(b, f[start..LEN(f)]);
78-end;
79-
80-proc print*(f: []U8; args: []Arg);
81-begin
82- format(nil, f, args);
83-end;
84-
85-proc write*(b: ^Buf.Buf; f: []U8; args: []Arg);
86-begin
87- format(b, f, args);
88-end;
89-
90-(* The module's test: formats into a buffer over an arena. *)
91-proc main*;
92-var ar: Arena.Arena; b: Buf.Buf;
93-begin
94- if not Arena.init(ADR(ar), 1 shl 16) then Rt.stop("Fmt: no arena"); end;
95- Buf.init(ADR(b), ADR(ar.base));
96- write(ADR(b), "{} {} {} {}|{}{}{} {{}}", [int(-42), uint(0FFFFFFFFFFFFFFFFH), hex(48879),
97- str("s"), char('c'), bool(true), int(0)]);
98- if Buf.bytes(ADR(b)) # "-42 18446744073709551615 BEEF s|ctrue0 {}" then Rt.stop("Fmt.write"); end;
99- Buf.reset(ADR(b));
100- write(ADR(b), "{} and {}", [int(1)]);
101- if Buf.bytes(ADR(b)) # "1 and " then Rt.stop("Fmt: too few arguments"); end;
102- Arena.done(ADR(ar));
103-end;
104-
105-end Fmt.

lib/Fmt.raz (history) added +105 -0

@@ -0,0 +1,105 @@
1+(* Formatted output. Each {} in the format takes the next argument:
2+ Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)]);
3+ {{ and }} stand for { and }. print writes to standard output,
4+ write appends to a Buf. *)
5+module Fmt;
6+import Out, Buf, Arena, Rt;
7+
8+type
9+ Arg* = variant
10+ int(i: I64);
11+ uint(u: U64);
12+ hex(h: U64);
13+ str(s: []U8);
14+ char(c: U8);
15+ bool(b: BOOL);
16+ end;
17+
18+(* The digits of u in base, at the end of the array: it and where they start. *)
19+proc digits(u: U64; base: U64): ([24]U8, I64);
20+var d: [24]U8; i: I64; v: U8;
21+begin
22+ i := 24;
23+ repeat
24+ DEC(i);
25+ v := U8(u mod base);
26+ if v < 10 then d[i] := v + '0'; else d[i] := v - 10 + 'A'; end;
27+ u := u div base;
28+ until u = 0;
29+ return d, i;
30+end;
31+
32+(* Where the pieces go: to b, or to standard output if b is nil. *)
33+proc put(b: ^Buf.Buf; s: []U8);
34+begin
35+ if b = nil then Out.str(s); else Buf.str(b, s); end;
36+end;
37+
38+proc arg(b: ^Buf.Buf; a: Arg);
39+var d: [24]U8; at: I64; one: [1]U8;
40+begin
41+ match a of
42+ | int(i):
43+ if i < 0 then
44+ put(b, "-");
45+ d, at := digits(0 - U64(i), 10);
46+ else
47+ d, at := digits(U64(i), 10);
48+ end;
49+ put(b, d[at..24]);
50+ | uint(u): d, at := digits(u, 10); put(b, d[at..24]);
51+ | hex(h): d, at := digits(h, 16); put(b, d[at..24]);
52+ | str(s): put(b, s);
53+ | char(c): one[0] := c; put(b, one);
54+ | bool(t): if t then put(b, "true"); else put(b, "false"); end;
55+ end;
56+end;
57+
58+proc format(b: ^Buf.Buf; f: []U8; args: []Arg);
59+var i, start, n: I64;
60+begin
61+ i := 0; start := 0; n := 0;
62+ while i < LEN(f) do
63+ if (f[i] = '{') or (f[i] = '}') then
64+ put(b, f[start..i]);
65+ if (i + 1 < LEN(f)) and (f[i + 1] = f[i]) then
66+ put(b, f[i..i + 1]);
67+ INC(i);
68+ elsif (f[i] = '{') and (i + 1 < LEN(f)) and (f[i + 1] = '}') then
69+ if n < LEN(args) then arg(b, args[n]); end;
70+ INC(n);
71+ INC(i);
72+ end;
73+ start := i + 1;
74+ end;
75+ INC(i);
76+ end;
77+ put(b, f[start..LEN(f)]);
78+end;
79+
80+proc print*(f: []U8; args: []Arg);
81+begin
82+ format(nil, f, args);
83+end;
84+
85+proc write*(b: ^Buf.Buf; f: []U8; args: []Arg);
86+begin
87+ format(b, f, args);
88+end;
89+
90+(* The module's test: formats into a buffer over an arena. *)
91+proc main*;
92+var ar: Arena.Arena; b: Buf.Buf;
93+begin
94+ if not Arena.init(ADR(ar), 1 shl 16) then Rt.stop("Fmt: no arena"); end;
95+ Buf.init(ADR(b), ADR(ar.base));
96+ write(ADR(b), "{} {} {} {}|{}{}{} {{}}", [int(-42), uint(0FFFFFFFFFFFFFFFFH), hex(48879),
97+ str("s"), char('c'), bool(true), int(0)]);
98+ if Buf.bytes(ADR(b)) # "-42 18446744073709551615 BEEF s|ctrue0 {}" then Rt.stop("Fmt.write"); end;
99+ Buf.reset(ADR(b));
100+ write(ADR(b), "{} and {}", [int(1)]);
101+ if Buf.bytes(ADR(b)) # "1 and " then Rt.stop("Fmt: too few arguments"); end;
102+ Arena.done(ADR(ar));
103+end;
104+
105+end Fmt.

lib/Heap.jed deleted +0 -128

@@ -1,128 +0,0 @@
1-(* A general allocator: Heap.heap. Small blocks come in nine sizes,
2- 16 to 4096 bytes with their header, each with a list of the free
3- ones; a block bigger than that gets pages of its own. Every block
4- has a 16-byte header before it: its size class, or minus the size
5- of its pages for a big one, which start less than a page before it;
6- then a marker, which says the block is out,
7- so that freeing it twice, or freeing what the heap never gave out,
8- stops the program. One lock keeps it whole across threads. *)
9-module Heap;
10-import Mem, Lock, Rt;
11-
12-const
13- Classes = 9;
14- Header = 16;
15- Refill = 65536;
16- Largest = 1 shl 46; (* bigger sizes are refused *)
17- Out = 5A6564426C6F636BH; (* the marker, xor the header's address *)
18-
19-type
20- Block = record next: ^Block; end;
21- Head = record size, mark: I64; end;
22-
23-var
24- lists: [Classes]^Block;
25- cur: ^U8; (* where the next new small block comes from *)
26- left: I64;
27- lock: Lock.Lock;
28- std: Mem.Allocator;
29- heap*: ^Mem.Allocator;
30-
31-(* The block p, with size for its header, given out. *)
32-proc give(p: ^U8; size: I64): ^U8;
33-var h: ^Head;
34-begin
35- h := ^Head(p);
36- h^.size := size;
37- h^.mark := Out xor I64(h);
38- return p + Header;
39-end;
40-
41-(* size bytes aligned to align, or nil: also for a size below zero or
42- too big, and an alignment that isn't a power of two up to a page. *)
43-proc alloc(a: ^Mem.Allocator; size, align: I64): ^U8;
44-var c, n: I64; b: ^Block; p: ^U8;
45-begin
46- if (size < 0) or (size > Largest) or (align < 1) or (align > Mem.Page)
47- or (align and (align - 1) # 0) then
48- return nil;
49- end;
50- n := size + Header;
51- c := 0;
52- while (c < Classes) and (16 shl c < n) do INC(c); end;
53- if (c = Classes) or (align > Header) then
54- (* pages of its own, the block at align from their start *)
55- if align < Header then align := Header; end;
56- n := (size + align + Mem.Page - 1) div Mem.Page * Mem.Page;
57- p := Mem.pages(n);
58- if p = nil then return nil; end;
59- return give(p + align - Header, -n);
60- end;
61- Lock.take(ADR(lock));
62- defer Lock.give(ADR(lock));
63- b := lists[c];
64- if b # nil then
65- lists[c] := b^.next;
66- p := ^U8(b);
67- else
68- if left < 16 shl c then
69- cur := Mem.pages(Refill);
70- if cur = nil then left := 0; return nil; end;
71- left := Refill;
72- end;
73- p := cur;
74- cur := cur + (16 shl c);
75- left := left - (16 shl c);
76- end;
77- return give(p, c);
78-end;
79-
80-proc free(a: ^Mem.Allocator; p: ^U8);
81-var h: ^Head; b: ^Block; c: I64;
82-begin
83- if p = nil then return; end;
84- h := ^Head(p - Header);
85- Lock.take(ADR(lock));
86- if h^.mark # Out xor I64(h) then
87- Rt.stop("Heap: a block freed twice, or never given out");
88- end;
89- h^.mark := 0;
90- if h^.size < 0 then
91- Lock.give(ADR(lock));
92- Mem.unmap(^U8(I64(h) - I64(h) mod Mem.Page), -h^.size);
93- else
94- c := h^.size; (* before next, which takes its place, is set *)
95- b := ^Block(h);
96- b^.next := lists[c];
97- lists[c] := b;
98- Lock.give(ADR(lock));
99- end;
100-end;
101-
102-(* The module's test: blocks of every class and big ones, written,
103- freed and taken again. *)
104-proc main*;
105-var p: [40]^U8; i, j, n: I64; again: ^U8;
106-begin
107- for i := 0 to 39 do
108- n := (i * i * 37) mod 9000 + 1;
109- p[i] := Mem.alloc(heap, n, 8);
110- if (p[i] = nil) or (I64(p[i]) mod 8 # 0) then Rt.stop("Heap: alloc"); end;
111- for j := 0 to n - 1 do p[i][j] := U8(i); end;
112- end;
113- for i := 0 to 39 do
114- n := (i * i * 37) mod 9000 + 1;
115- if (p[i][0] # U8(i)) or (p[i][n - 1] # U8(i)) then Rt.stop("Heap: overlap"); end;
116- end;
117- Mem.free(heap, p[5]);
118- again := Mem.alloc(heap, (25 * 37) mod 9000 + 1, 8);
119- if again # p[5] then Rt.stop("Heap: a freed block isn't taken again"); end;
120- for i := 0 to 39 do Mem.free(heap, p[i]); end;
121- if Mem.alloc(heap, -1, 8) # nil then Rt.stop("Heap: negative size"); end;
122- if Mem.alloc(heap, 7FFFFFFFFFFFFFFFH - 4, 8) # nil then Rt.stop("Heap: huge size"); end;
123-end;
124-
125-begin
126- std := {alloc: alloc, free: free};
127- heap := ADR(std);
128-end Heap.

lib/Heap.raz (history) added +128 -0

@@ -0,0 +1,128 @@
1+(* A general allocator: Heap.heap. Small blocks come in nine sizes,
2+ 16 to 4096 bytes with their header, each with a list of the free
3+ ones; a block bigger than that gets pages of its own. Every block
4+ has a 16-byte header before it: its size class, or minus the size
5+ of its pages for a big one, which start less than a page before it;
6+ then a marker, which says the block is out,
7+ so that freeing it twice, or freeing what the heap never gave out,
8+ stops the program. One lock keeps it whole across threads. *)
9+module Heap;
10+import Mem, Lock, Rt;
11+
12+const
13+ Classes = 9;
14+ Header = 16;
15+ Refill = 65536;
16+ Largest = 1 shl 46; (* bigger sizes are refused *)
17+ Out = 5A6564426C6F636BH; (* the marker, xor the header's address *)
18+
19+type
20+ Block = record next: ^Block; end;
21+ Head = record size, mark: I64; end;
22+
23+var
24+ lists: [Classes]^Block;
25+ cur: ^U8; (* where the next new small block comes from *)
26+ left: I64;
27+ lock: Lock.Lock;
28+ std: Mem.Allocator;
29+ heap*: ^Mem.Allocator;
30+
31+(* The block p, with size for its header, given out. *)
32+proc give(p: ^U8; size: I64): ^U8;
33+var h: ^Head;
34+begin
35+ h := ^Head(p);
36+ h^.size := size;
37+ h^.mark := Out xor I64(h);
38+ return p + Header;
39+end;
40+
41+(* size bytes aligned to align, or nil: also for a size below zero or
42+ too big, and an alignment that isn't a power of two up to a page. *)
43+proc alloc(a: ^Mem.Allocator; size, align: I64): ^U8;
44+var c, n: I64; b: ^Block; p: ^U8;
45+begin
46+ if (size < 0) or (size > Largest) or (align < 1) or (align > Mem.Page)
47+ or (align and (align - 1) # 0) then
48+ return nil;
49+ end;
50+ n := size + Header;
51+ c := 0;
52+ while (c < Classes) and (16 shl c < n) do INC(c); end;
53+ if (c = Classes) or (align > Header) then
54+ (* pages of its own, the block at align from their start *)
55+ if align < Header then align := Header; end;
56+ n := (size + align + Mem.Page - 1) div Mem.Page * Mem.Page;
57+ p := Mem.pages(n);
58+ if p = nil then return nil; end;
59+ return give(p + align - Header, -n);
60+ end;
61+ Lock.take(ADR(lock));
62+ defer Lock.give(ADR(lock));
63+ b := lists[c];
64+ if b # nil then
65+ lists[c] := b^.next;
66+ p := ^U8(b);
67+ else
68+ if left < 16 shl c then
69+ cur := Mem.pages(Refill);
70+ if cur = nil then left := 0; return nil; end;
71+ left := Refill;
72+ end;
73+ p := cur;
74+ cur := cur + (16 shl c);
75+ left := left - (16 shl c);
76+ end;
77+ return give(p, c);
78+end;
79+
80+proc free(a: ^Mem.Allocator; p: ^U8);
81+var h: ^Head; b: ^Block; c: I64;
82+begin
83+ if p = nil then return; end;
84+ h := ^Head(p - Header);
85+ Lock.take(ADR(lock));
86+ if h^.mark # Out xor I64(h) then
87+ Rt.stop("Heap: a block freed twice, or never given out");
88+ end;
89+ h^.mark := 0;
90+ if h^.size < 0 then
91+ Lock.give(ADR(lock));
92+ Mem.unmap(^U8(I64(h) - I64(h) mod Mem.Page), -h^.size);
93+ else
94+ c := h^.size; (* before next, which takes its place, is set *)
95+ b := ^Block(h);
96+ b^.next := lists[c];
97+ lists[c] := b;
98+ Lock.give(ADR(lock));
99+ end;
100+end;
101+
102+(* The module's test: blocks of every class and big ones, written,
103+ freed and taken again. *)
104+proc main*;
105+var p: [40]^U8; i, j, n: I64; again: ^U8;
106+begin
107+ for i := 0 to 39 do
108+ n := (i * i * 37) mod 9000 + 1;
109+ p[i] := Mem.alloc(heap, n, 8);
110+ if (p[i] = nil) or (I64(p[i]) mod 8 # 0) then Rt.stop("Heap: alloc"); end;
111+ for j := 0 to n - 1 do p[i][j] := U8(i); end;
112+ end;
113+ for i := 0 to 39 do
114+ n := (i * i * 37) mod 9000 + 1;
115+ if (p[i][0] # U8(i)) or (p[i][n - 1] # U8(i)) then Rt.stop("Heap: overlap"); end;
116+ end;
117+ Mem.free(heap, p[5]);
118+ again := Mem.alloc(heap, (25 * 37) mod 9000 + 1, 8);
119+ if again # p[5] then Rt.stop("Heap: a freed block isn't taken again"); end;
120+ for i := 0 to 39 do Mem.free(heap, p[i]); end;
121+ if Mem.alloc(heap, -1, 8) # nil then Rt.stop("Heap: negative size"); end;
122+ if Mem.alloc(heap, 7FFFFFFFFFFFFFFFH - 4, 8) # nil then Rt.stop("Heap: huge size"); end;
123+end;
124+
125+begin
126+ std := {alloc: alloc, free: free};
127+ heap := ADR(std);
128+end Heap.

lib/List.jed deleted +0 -68

@@ -1,68 +0,0 @@
1-(* A singly linked list of T, its nodes from an allocator. *)
2-module List(T);
3-import Mem;
4-
5-type
6- Node* = record
7- next*: ^Node;
8- val*: T;
9- end;
10- List* = record
11- head*: ^Node;
12- len*: I64;
13- a: ^Mem.Allocator;
14- end;
15-
16-proc init*(l: ^List; a: ^Mem.Allocator);
17-begin
18- l^ := {a: a};
19-end;
20-
21-(* v at the front; false if the allocator has no room. *)
22-proc push*(l: ^List; v: T): BOOL;
23-var n: ^Node;
24-begin
25- NEW(n, l^.a);
26- if n = nil then return false; end;
27- n^.val := v;
28- n^.next := l^.head;
29- l^.head := n;
30- INC(l^.len);
31- return true;
32-end;
33-
34-(* The front value, taken off; false if the list is empty. *)
35-proc pop*(l: ^List): (T, BOOL);
36-var n: ^Node; v: T;
37-begin
38- n := l^.head;
39- if n = nil then return v, false; end;
40- v := n^.val;
41- l^.head := n^.next;
42- DEC(l^.len);
43- Mem.free(l^.a, ^U8(n));
44- return v, true;
45-end;
46-
47-(* The list backwards. *)
48-proc reverse*(l: ^List);
49-var p, q, next: ^Node;
50-begin
51- p := l^.head;
52- q := nil;
53- while p # nil do
54- next := p^.next;
55- p^.next := q;
56- q := p;
57- p := next;
58- end;
59- l^.head := q;
60-end;
61-
62-proc clear*(l: ^List);
63-var ok: BOOL; v: T;
64-begin
65- while l^.head # nil do v, ok := pop(l); end;
66-end;
67-
68-end List.

lib/List.raz (history) added +68 -0

@@ -0,0 +1,68 @@
1+(* A singly linked list of T, its nodes from an allocator. *)
2+module List(T);
3+import Mem;
4+
5+type
6+ Node* = record
7+ next*: ^Node;
8+ val*: T;
9+ end;
10+ List* = record
11+ head*: ^Node;
12+ len*: I64;
13+ a: ^Mem.Allocator;
14+ end;
15+
16+proc init*(l: ^List; a: ^Mem.Allocator);
17+begin
18+ l^ := {a: a};
19+end;
20+
21+(* v at the front; false if the allocator has no room. *)
22+proc push*(l: ^List; v: T): BOOL;
23+var n: ^Node;
24+begin
25+ NEW(n, l^.a);
26+ if n = nil then return false; end;
27+ n^.val := v;
28+ n^.next := l^.head;
29+ l^.head := n;
30+ INC(l^.len);
31+ return true;
32+end;
33+
34+(* The front value, taken off; false if the list is empty. *)
35+proc pop*(l: ^List): (T, BOOL);
36+var n: ^Node; v: T;
37+begin
38+ n := l^.head;
39+ if n = nil then return v, false; end;
40+ v := n^.val;
41+ l^.head := n^.next;
42+ DEC(l^.len);
43+ Mem.free(l^.a, ^U8(n));
44+ return v, true;
45+end;
46+
47+(* The list backwards. *)
48+proc reverse*(l: ^List);
49+var p, q, next: ^Node;
50+begin
51+ p := l^.head;
52+ q := nil;
53+ while p # nil do
54+ next := p^.next;
55+ p^.next := q;
56+ q := p;
57+ p := next;
58+ end;
59+ l^.head := q;
60+end;
61+
62+proc clear*(l: ^List);
63+var ok: BOOL; v: T;
64+begin
65+ while l^.head # nil do v, ok := pop(l); end;
66+end;
67+
68+end List.

lib/Lock.jed deleted +0 -37

@@ -1,37 +0,0 @@
1-(* A lock for short sections of code: a word set to 1, atomically, by
2- the thread that takes it. A thread that finds it taken tries again,
3- giving up the processor now and then. It works with C's threads and
4- with Thread's alike; Thread.Mutex is the one that sleeps. *)
5-module Lock;
6-import Sys, Rt;
7-
8-type Lock* = record held: I64; end;
9-
10-proc take*(l: ^Lock);
11-var tries: I64;
12-begin
13- tries := 0;
14- while not CAS(ADR(l^.held), 0, 1) do
15- INC(tries);
16- if tries = 64 then Sys.yield; tries := 0; end;
17- end;
18-end;
19-
20-proc give*(l: ^Lock);
21-begin
22- XCHG(ADR(l^.held), 0);
23-end;
24-
25-(* The module's test, in one thread: taken, given, taken again. *)
26-proc main*;
27-var l: Lock;
28-begin
29- take(ADR(l));
30- if l.held # 1 then Rt.stop("Lock.take"); end;
31- give(ADR(l));
32- take(ADR(l));
33- give(ADR(l));
34- if l.held # 0 then Rt.stop("Lock.give"); end;
35-end;
36-
37-end Lock.

lib/Lock.raz (history) added +37 -0

@@ -0,0 +1,37 @@
1+(* A lock for short sections of code: a word set to 1, atomically, by
2+ the thread that takes it. A thread that finds it taken tries again,
3+ giving up the processor now and then. It works with C's threads and
4+ with Thread's alike; Thread.Mutex is the one that sleeps. *)
5+module Lock;
6+import Sys, Rt;
7+
8+type Lock* = record held: I64; end;
9+
10+proc take*(l: ^Lock);
11+var tries: I64;
12+begin
13+ tries := 0;
14+ while not CAS(ADR(l^.held), 0, 1) do
15+ INC(tries);
16+ if tries = 64 then Sys.yield; tries := 0; end;
17+ end;
18+end;
19+
20+proc give*(l: ^Lock);
21+begin
22+ XCHG(ADR(l^.held), 0);
23+end;
24+
25+(* The module's test, in one thread: taken, given, taken again. *)
26+proc main*;
27+var l: Lock;
28+begin
29+ take(ADR(l));
30+ if l.held # 1 then Rt.stop("Lock.take"); end;
31+ give(ADR(l));
32+ take(ADR(l));
33+ give(ADR(l));
34+ if l.held # 0 then Rt.stop("Lock.give"); end;
35+end;
36+
37+end Lock.

lib/Map.jed deleted +0 -81

@@ -1,81 +0,0 @@
1-(* A hash map from K to V, by open addressing; it hashes and compares
2- keys with the procedures it is given:
3- import Count := Map([]U8, I64, Str.hash, Str.eq); *)
4-module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL);
5-import Mem;
6-
7-type
8- Entry = record
9- key: K;
10- val: V;
11- used: BOOL;
12- end;
13- Map* = record
14- a: ^Mem.Allocator;
15- slots: ^Entry;
16- cap: I64; (* a power of two, or 0 *)
17- len*: I64;
18- end;
19-
20-proc init*(m: ^Map; a: ^Mem.Allocator);
21-begin
22- m^ := {a: a};
23-end;
24-
25-(* The slot of k, or of the empty slot where it would go. *)
26-proc slot(m: ^Map; k: K): I64;
27-var i: I64;
28-begin
29- i := I64(hash(k) and U64(m^.cap - 1));
30- while m^.slots[i].used and not eq(m^.slots[i].key, k) do
31- i := (i + 1) and (m^.cap - 1);
32- end;
33- return i;
34-end;
35-
36-proc grow(m: ^Map): BOOL;
37-var old: ^Entry; n, i, j: I64;
38-begin
39- old := m^.slots;
40- n := m^.cap;
41- if n = 0 then m^.cap := 16; else m^.cap := n * 2; end;
42- m^.slots := ^Entry(Mem.alloc(m^.a, m^.cap * SIZE(Entry), 8));
43- if m^.slots = nil then m^.slots := old; m^.cap := n; return false; end;
44- for i := 0 to m^.cap - 1 do m^.slots[i].used := false; end;
45- for i := 0 to n - 1 do
46- if old[i].used then
47- j := slot(m, old[i].key);
48- m^.slots[j] := old[i];
49- end;
50- end;
51- if old # nil then Mem.free(m^.a, ^U8(old)); end;
52- return true;
53-end;
54-
55-(* k now maps to v; false if there was no room. *)
56-proc put*(m: ^Map; k: K; v: V): BOOL;
57-var i: I64;
58-begin
59- if (m^.len + 1) * 4 > m^.cap * 3 then
60- if not grow(m) then return false; end;
61- end;
62- i := slot(m, k);
63- if not m^.slots[i].used then
64- m^.slots[i] := {key: k, used: true};
65- INC(m^.len);
66- end;
67- m^.slots[i].val := v;
68- return true;
69-end;
70-
71-(* What k maps to, and whether it maps to anything. *)
72-proc get*(m: ^Map; k: K): (V, BOOL);
73-var i: I64; none: V;
74-begin
75- if m^.cap = 0 then return none, false; end;
76- i := slot(m, k);
77- if not m^.slots[i].used then return none, false; end;
78- return m^.slots[i].val, true;
79-end;
80-
81-end Map.

lib/Map.raz (history) added +81 -0

@@ -0,0 +1,81 @@
1+(* A hash map from K to V, by open addressing; it hashes and compares
2+ keys with the procedures it is given:
3+ import Count := Map([]U8, I64, Str.hash, Str.eq); *)
4+module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL);
5+import Mem;
6+
7+type
8+ Entry = record
9+ key: K;
10+ val: V;
11+ used: BOOL;
12+ end;
13+ Map* = record
14+ a: ^Mem.Allocator;
15+ slots: ^Entry;
16+ cap: I64; (* a power of two, or 0 *)
17+ len*: I64;
18+ end;
19+
20+proc init*(m: ^Map; a: ^Mem.Allocator);
21+begin
22+ m^ := {a: a};
23+end;
24+
25+(* The slot of k, or of the empty slot where it would go. *)
26+proc slot(m: ^Map; k: K): I64;
27+var i: I64;
28+begin
29+ i := I64(hash(k) and U64(m^.cap - 1));
30+ while m^.slots[i].used and not eq(m^.slots[i].key, k) do
31+ i := (i + 1) and (m^.cap - 1);
32+ end;
33+ return i;
34+end;
35+
36+proc grow(m: ^Map): BOOL;
37+var old: ^Entry; n, i, j: I64;
38+begin
39+ old := m^.slots;
40+ n := m^.cap;
41+ if n = 0 then m^.cap := 16; else m^.cap := n * 2; end;
42+ m^.slots := ^Entry(Mem.alloc(m^.a, m^.cap * SIZE(Entry), 8));
43+ if m^.slots = nil then m^.slots := old; m^.cap := n; return false; end;
44+ for i := 0 to m^.cap - 1 do m^.slots[i].used := false; end;
45+ for i := 0 to n - 1 do
46+ if old[i].used then
47+ j := slot(m, old[i].key);
48+ m^.slots[j] := old[i];
49+ end;
50+ end;
51+ if old # nil then Mem.free(m^.a, ^U8(old)); end;
52+ return true;
53+end;
54+
55+(* k now maps to v; false if there was no room. *)
56+proc put*(m: ^Map; k: K; v: V): BOOL;
57+var i: I64;
58+begin
59+ if (m^.len + 1) * 4 > m^.cap * 3 then
60+ if not grow(m) then return false; end;
61+ end;
62+ i := slot(m, k);
63+ if not m^.slots[i].used then
64+ m^.slots[i] := {key: k, used: true};
65+ INC(m^.len);
66+ end;
67+ m^.slots[i].val := v;
68+ return true;
69+end;
70+
71+(* What k maps to, and whether it maps to anything. *)
72+proc get*(m: ^Map; k: K): (V, BOOL);
73+var i: I64; none: V;
74+begin
75+ if m^.cap = 0 then return none, false; end;
76+ i := slot(m, k);
77+ if not m^.slots[i].used then return none, false; end;
78+ return m^.slots[i].val, true;
79+end;
80+
81+end Map.

lib/Mem.jed deleted +0 -48

@@ -1,48 +0,0 @@
1-(* Memory: Allocator, the interface every allocator offers, and pages
2- from the system. NEW(p, a) calls a^.alloc. *)
3-module Mem;
4-import Sys, Rt;
5-
6-type
7- Allocator* = record
8- alloc*: proc(a: ^Allocator; size, align: I64): ^U8; (* nil if out of room *)
9- free*: proc(a: ^Allocator; p: ^U8);
10- end;
11-
12-const Page* = 4096;
13-
14-(* size bytes, rounded up to whole pages, zeroed; or nil. *)
15-proc pages*(size: I64): ^U8;
16-begin
17- return Sys.mmap((size + Page - 1) div Page * Page);
18-end;
19-
20-proc unmap*(p: ^U8; size: I64);
21-begin
22- Sys.munmap(p, (size + Page - 1) div Page * Page);
23-end;
24-
25-proc alloc*(a: ^Allocator; size, align: I64): ^U8;
26-begin
27- return a^.alloc(a, size, align);
28-end;
29-
30-proc free*(a: ^Allocator; p: ^U8);
31-begin
32- a^.free(a, p);
33-end;
34-
35-(* The module's test. *)
36-proc main*;
37-var p: ^U8; i: I64;
38-begin
39- p := pages(10000);
40- if p = nil then Rt.stop("Mem.pages"); end;
41- for i := 0 to 12287 do
42- if p[i] # 0 then Rt.stop("Mem.pages: not zeroed"); end;
43- end;
44- p[12287] := 1;
45- unmap(p, 10000);
46-end;
47-
48-end Mem.

lib/Mem.raz (history) added +48 -0

@@ -0,0 +1,48 @@
1+(* Memory: Allocator, the interface every allocator offers, and pages
2+ from the system. NEW(p, a) calls a^.alloc. *)
3+module Mem;
4+import Sys, Rt;
5+
6+type
7+ Allocator* = record
8+ alloc*: proc(a: ^Allocator; size, align: I64): ^U8; (* nil if out of room *)
9+ free*: proc(a: ^Allocator; p: ^U8);
10+ end;
11+
12+const Page* = 4096;
13+
14+(* size bytes, rounded up to whole pages, zeroed; or nil. *)
15+proc pages*(size: I64): ^U8;
16+begin
17+ return Sys.mmap((size + Page - 1) div Page * Page);
18+end;
19+
20+proc unmap*(p: ^U8; size: I64);
21+begin
22+ Sys.munmap(p, (size + Page - 1) div Page * Page);
23+end;
24+
25+proc alloc*(a: ^Allocator; size, align: I64): ^U8;
26+begin
27+ return a^.alloc(a, size, align);
28+end;
29+
30+proc free*(a: ^Allocator; p: ^U8);
31+begin
32+ a^.free(a, p);
33+end;
34+
35+(* The module's test. *)
36+proc main*;
37+var p: ^U8; i: I64;
38+begin
39+ p := pages(10000);
40+ if p = nil then Rt.stop("Mem.pages"); end;
41+ for i := 0 to 12287 do
42+ if p[i] # 0 then Rt.stop("Mem.pages: not zeroed"); end;
43+ end;
44+ p[12287] := 1;
45+ unmap(p, 10000);
46+end;
47+
48+end Mem.

lib/Out.jed deleted +0 -100

@@ -1,100 +0,0 @@
1-(* Writing text and numbers to standard output, through a buffer of
2- 4 KB. The buffer is written out when it is full, at each line feed
3- when standard output is a terminal, by flush, and when the program
4- ends by Rt.exit. C's stdio keeps a buffer of its own: a program that
5- writes with both flushes one before writing with the other. A lock
6- keeps what each call writes together when threads write at once. *)
7-module Out;
8-import Rt, Sys, Lock;
9-
10-var
11- buf: [4096]U8;
12- n: I64; (* bytes in buf *)
13- tty: BOOL; (* standard output is a terminal *)
14- lock: Lock.Lock;
15-
16-(* Writes out the buffer, with the lock held. What can't be written is
17- dropped. *)
18-proc out;
19-var i, k: I64;
20-begin
21- i := 0;
22- while i < n do
23- k := Sys.write(Sys.stdout, buf[i..n]);
24- if k > 0 then i := i + k;
25- elsif k # -4 then break; (* -EINTR: try again *)
26- end;
27- end;
28- n := 0;
29-end;
30-
31-proc flush*;
32-begin
33- Lock.take(ADR(lock));
34- out;
35- Lock.give(ADR(lock));
36-end;
37-
38-proc str*(s: []U8);
39-var i: I64;
40-begin
41- Lock.take(ADR(lock));
42- for i := 0 to LEN(s) - 1 do
43- if n = LEN(buf) then out; end;
44- buf[n] := s[i];
45- INC(n);
46- if (s[i] = '\n') and tty then out; end;
47- end;
48- Lock.give(ADR(lock));
49-end;
50-
51-proc char*(c: U8);
52-var b: [1]U8;
53-begin
54- b[0] := c;
55- str(b);
56-end;
57-
58-proc ln*;
59-begin
60- char('\n');
61-end;
62-
63-(* n in decimal *)
64-proc int*(n: I64);
65-var buf: [20]U8; i: I64; u: U64;
66-begin
67- u := U64(n);
68- if n < 0 then u := 0 - u; end;
69- i := 20;
70- repeat
71- i := i - 1;
72- buf[i] := U8(u mod 10) + '0';
73- u := u div 10;
74- until u = 0;
75- if n < 0 then
76- i := i - 1;
77- buf[i] := '-';
78- end;
79- str(buf[i..20]);
80-end;
81-
82-(* n in hexadecimal, digits digits at least *)
83-proc hex*(n: U64; digits: I64);
84-var buf: [16]U8; i: I64; d: U8;
85-begin
86- i := 16;
87- repeat
88- i := i - 1;
89- d := U8(n and 15);
90- if d < 10 then buf[i] := d + '0'; else buf[i] := d - 10 + 'A'; end;
91- n := n shr 4;
92- digits := digits - 1;
93- until (n = 0) and (digits <= 0) or (i = 0);
94- str(buf[i..16]);
95-end;
96-
97-begin
98- tty := Sys.isTerminal(Sys.stdout);
99- Rt.atExit(flush);
100-end Out.

lib/Out.raz (history) added +100 -0

@@ -0,0 +1,100 @@
1+(* Writing text and numbers to standard output, through a buffer of
2+ 4 KB. The buffer is written out when it is full, at each line feed
3+ when standard output is a terminal, by flush, and when the program
4+ ends by Rt.exit. C's stdio keeps a buffer of its own: a program that
5+ writes with both flushes one before writing with the other. A lock
6+ keeps what each call writes together when threads write at once. *)
7+module Out;
8+import Rt, Sys, Lock;
9+
10+var
11+ buf: [4096]U8;
12+ n: I64; (* bytes in buf *)
13+ tty: BOOL; (* standard output is a terminal *)
14+ lock: Lock.Lock;
15+
16+(* Writes out the buffer, with the lock held. What can't be written is
17+ dropped. *)
18+proc out;
19+var i, k: I64;
20+begin
21+ i := 0;
22+ while i < n do
23+ k := Sys.write(Sys.stdout, buf[i..n]);
24+ if k > 0 then i := i + k;
25+ elsif k # -4 then break; (* -EINTR: try again *)
26+ end;
27+ end;
28+ n := 0;
29+end;
30+
31+proc flush*;
32+begin
33+ Lock.take(ADR(lock));
34+ out;
35+ Lock.give(ADR(lock));
36+end;
37+
38+proc str*(s: []U8);
39+var i: I64;
40+begin
41+ Lock.take(ADR(lock));
42+ for i := 0 to LEN(s) - 1 do
43+ if n = LEN(buf) then out; end;
44+ buf[n] := s[i];
45+ INC(n);
46+ if (s[i] = '\n') and tty then out; end;
47+ end;
48+ Lock.give(ADR(lock));
49+end;
50+
51+proc char*(c: U8);
52+var b: [1]U8;
53+begin
54+ b[0] := c;
55+ str(b);
56+end;
57+
58+proc ln*;
59+begin
60+ char('\n');
61+end;
62+
63+(* n in decimal *)
64+proc int*(n: I64);
65+var buf: [20]U8; i: I64; u: U64;
66+begin
67+ u := U64(n);
68+ if n < 0 then u := 0 - u; end;
69+ i := 20;
70+ repeat
71+ i := i - 1;
72+ buf[i] := U8(u mod 10) + '0';
73+ u := u div 10;
74+ until u = 0;
75+ if n < 0 then
76+ i := i - 1;
77+ buf[i] := '-';
78+ end;
79+ str(buf[i..20]);
80+end;
81+
82+(* n in hexadecimal, digits digits at least *)
83+proc hex*(n: U64; digits: I64);
84+var buf: [16]U8; i: I64; d: U8;
85+begin
86+ i := 16;
87+ repeat
88+ i := i - 1;
89+ d := U8(n and 15);
90+ if d < 10 then buf[i] := d + '0'; else buf[i] := d - 10 + 'A'; end;
91+ n := n shr 4;
92+ digits := digits - 1;
93+ until (n = 0) and (digits <= 0) or (i = 0);
94+ str(buf[i..16]);
95+end;
96+
97+begin
98+ tty := Sys.isTerminal(Sys.stdout);
99+ Rt.atExit(flush);
100+end Out.

lib/Rt.jed deleted +0 -83

@@ -1,83 +0,0 @@
1-(* The run time: ending the program, and what the compiler's code
2- calls: fail when a check fails, eq when = or # compares two strings;
3- and stop, for the library's own failures.
4- The compiler finds fail, eq, exit and cExit by these names. *)
5-module Rt;
6-import Sys;
7-
8-const
9- Full*: ERROR = "too many procedures to run at exit";
10- MaxAtExit = 32;
11-
12-var
13- atExits: [MaxAtExit]proc;
14- numAtExit: I64;
15- cExit: proc(status: I32); (* C's exit, set first thing in a program that uses C *)
16-
17-(* Registers p to run when the program ends by exit. *)
18-proc atExit*(p: proc): ERROR;
19-begin
20- if numAtExit = MaxAtExit then return Full; end;
21- atExits[numAtExit] := p;
22- INC(numAtExit);
23- return nil;
24-end;
25-
26-(* Runs the procedures registered with atExit, the last first, then
27- ends the program with status: through C's exit in a program that
28- uses C, so that C flushes its buffers too. Each procedure is taken
29- off the list before it runs, so it runs once even if it fails or
30- calls exit itself. *)
31-proc exit*(status: I64);
32-var p: proc;
33-begin
34- while numAtExit > 0 do
35- DEC(numAtExit);
36- p := atExits[numAtExit];
37- p();
38- end;
39- if cExit # nil then cExit(I32(status)); end;
40- Sys.exit(status);
41-end;
42-
43-(* Stops the program: says msg on standard error, then ends it by exit
44- with status 2, as a failed check does. *)
45-proc stop*(msg: []U8);
46-begin
47- Sys.write(Sys.stderr, msg);
48- Sys.write(Sys.stderr, "\n");
49- exit(2);
50-end;
51-
52-(* A check failed at line of file: says so on standard error and ends
53- the program with status 2. *)
54-proc fail*(file: ^U8; line: I64);
55-var buf: [20]U8; i, n: I64;
56-begin
57- n := 0;
58- while file[n] # 0 do n := n + 1; end;
59- Sys.write(Sys.stderr, file[0..n]);
60- i := 20;
61- repeat
62- i := i - 1;
63- buf[i] := U8(line mod 10) + '0';
64- line := line div 10;
65- until line = 0;
66- i := i - 1;
67- buf[i] := ':';
68- Sys.write(Sys.stderr, buf[i..20]);
69- Sys.write(Sys.stderr, ": index out of range\n");
70- exit(2);
71-end;
72-
73-proc eq*(a, b: []U8): BOOL;
74-var i: I64;
75-begin
76- if LEN(a) # LEN(b) then return false; end;
77- for i := 0 to LEN(a) - 1 do
78- if a[i] # b[i] then return false; end;
79- end;
80- return true;
81-end;
82-
83-end Rt.

lib/Rt.raz (history) added +83 -0

@@ -0,0 +1,83 @@
1+(* The run time: ending the program, and what the compiler's code
2+ calls: fail when a check fails, eq when = or # compares two strings;
3+ and stop, for the library's own failures.
4+ The compiler finds fail, eq, exit and cExit by these names. *)
5+module Rt;
6+import Sys;
7+
8+const
9+ Full*: ERROR = "too many procedures to run at exit";
10+ MaxAtExit = 32;
11+
12+var
13+ atExits: [MaxAtExit]proc;
14+ numAtExit: I64;
15+ cExit: proc(status: I32); (* C's exit, set first thing in a program that uses C *)
16+
17+(* Registers p to run when the program ends by exit. *)
18+proc atExit*(p: proc): ERROR;
19+begin
20+ if numAtExit = MaxAtExit then return Full; end;
21+ atExits[numAtExit] := p;
22+ INC(numAtExit);
23+ return nil;
24+end;
25+
26+(* Runs the procedures registered with atExit, the last first, then
27+ ends the program with status: through C's exit in a program that
28+ uses C, so that C flushes its buffers too. Each procedure is taken
29+ off the list before it runs, so it runs once even if it fails or
30+ calls exit itself. *)
31+proc exit*(status: I64);
32+var p: proc;
33+begin
34+ while numAtExit > 0 do
35+ DEC(numAtExit);
36+ p := atExits[numAtExit];
37+ p();
38+ end;
39+ if cExit # nil then cExit(I32(status)); end;
40+ Sys.exit(status);
41+end;
42+
43+(* Stops the program: says msg on standard error, then ends it by exit
44+ with status 2, as a failed check does. *)
45+proc stop*(msg: []U8);
46+begin
47+ Sys.write(Sys.stderr, msg);
48+ Sys.write(Sys.stderr, "\n");
49+ exit(2);
50+end;
51+
52+(* A check failed at line of file: says so on standard error and ends
53+ the program with status 2. *)
54+proc fail*(file: ^U8; line: I64);
55+var buf: [20]U8; i, n: I64;
56+begin
57+ n := 0;
58+ while file[n] # 0 do n := n + 1; end;
59+ Sys.write(Sys.stderr, file[0..n]);
60+ i := 20;
61+ repeat
62+ i := i - 1;
63+ buf[i] := U8(line mod 10) + '0';
64+ line := line div 10;
65+ until line = 0;
66+ i := i - 1;
67+ buf[i] := ':';
68+ Sys.write(Sys.stderr, buf[i..20]);
69+ Sys.write(Sys.stderr, ": index out of range\n");
70+ exit(2);
71+end;
72+
73+proc eq*(a, b: []U8): BOOL;
74+var i: I64;
75+begin
76+ if LEN(a) # LEN(b) then return false; end;
77+ for i := 0 to LEN(a) - 1 do
78+ if a[i] # b[i] then return false; end;
79+ end;
80+ return true;
81+end;
82+
83+end Rt.

lib/Str.jed deleted +0 -66

@@ -1,66 +0,0 @@
1-(* Operations on strings, which are []U8. = and # compare them; this
2- module orders, searches and hashes them. *)
3-module Str;
4-import Rt;
5-
6-(* -1, 0 or 1 as a sorts before, with or after b, byte by byte. *)
7-proc cmp*(a, b: []U8): I64;
8-var i, n: I64;
9-begin
10- n := LEN(a);
11- if LEN(b) < n then n := LEN(b); end;
12- for i := 0 to n - 1 do
13- if a[i] # b[i] then
14- if a[i] < b[i] then return -1; end;
15- return 1;
16- end;
17- end;
18- if LEN(a) < LEN(b) then return -1; end;
19- if LEN(a) > LEN(b) then return 1; end;
20- return 0;
21-end;
22-
23-proc eq*(a, b: []U8): BOOL;
24-begin
25- return a = b;
26-end;
27-
28-(* FNV-1a, 64 bits. *)
29-proc hash*(s: []U8): U64;
30-var h: U64; i: I64;
31-begin
32- h := 0CBF29CE484222325H;
33- for i := 0 to LEN(s) - 1 do
34- h := (h xor U64(s[i])) * 100000001B3H;
35- end;
36- return h;
37-end;
38-
39-(* Where sub first starts in s, or -1. *)
40-proc find*(s, sub: []U8): I64;
41-var i: I64;
42-begin
43- for i := 0 to LEN(s) - LEN(sub) do
44- if s[i..i + LEN(sub)] = sub then return i; end;
45- end;
46- return -1;
47-end;
48-
49-proc hasPrefix*(s, p: []U8): BOOL;
50-begin
51- return (LEN(s) >= LEN(p)) and (s[0..LEN(p)] = p);
52-end;
53-
54-(* The module's test: stops the program if something is wrong. *)
55-proc main*;
56-begin
57- if (cmp("a", "b") # -1) or (cmp("b", "a") # 1) or (cmp("ab", "ab") # 0)
58- or (cmp("a", "ab") # -1) or (cmp("", "") # 0) then Rt.stop("Str.cmp"); end;
59- if not eq("x", "x") or eq("x", "y") then Rt.stop("Str.eq"); end;
60- if (hash("") # 0CBF29CE484222325H) or (hash("a") # 0AF63DC4C8601EC8CH) then Rt.stop("Str.hash"); end;
61- if (find("hello", "ll") # 2) or (find("hello", "x") # -1) or (find("", "") # 0)
62- or (find("ab", "abc") # -1) then Rt.stop("Str.find"); end;
63- if not hasPrefix("hello", "he") or hasPrefix("he", "hello") then Rt.stop("Str.hasPrefix"); end;
64-end;
65-
66-end Str.

lib/Str.raz (history) added +66 -0

@@ -0,0 +1,66 @@
1+(* Operations on strings, which are []U8. = and # compare them; this
2+ module orders, searches and hashes them. *)
3+module Str;
4+import Rt;
5+
6+(* -1, 0 or 1 as a sorts before, with or after b, byte by byte. *)
7+proc cmp*(a, b: []U8): I64;
8+var i, n: I64;
9+begin
10+ n := LEN(a);
11+ if LEN(b) < n then n := LEN(b); end;
12+ for i := 0 to n - 1 do
13+ if a[i] # b[i] then
14+ if a[i] < b[i] then return -1; end;
15+ return 1;
16+ end;
17+ end;
18+ if LEN(a) < LEN(b) then return -1; end;
19+ if LEN(a) > LEN(b) then return 1; end;
20+ return 0;
21+end;
22+
23+proc eq*(a, b: []U8): BOOL;
24+begin
25+ return a = b;
26+end;
27+
28+(* FNV-1a, 64 bits. *)
29+proc hash*(s: []U8): U64;
30+var h: U64; i: I64;
31+begin
32+ h := 0CBF29CE484222325H;
33+ for i := 0 to LEN(s) - 1 do
34+ h := (h xor U64(s[i])) * 100000001B3H;
35+ end;
36+ return h;
37+end;
38+
39+(* Where sub first starts in s, or -1. *)
40+proc find*(s, sub: []U8): I64;
41+var i: I64;
42+begin
43+ for i := 0 to LEN(s) - LEN(sub) do
44+ if s[i..i + LEN(sub)] = sub then return i; end;
45+ end;
46+ return -1;
47+end;
48+
49+proc hasPrefix*(s, p: []U8): BOOL;
50+begin
51+ return (LEN(s) >= LEN(p)) and (s[0..LEN(p)] = p);
52+end;
53+
54+(* The module's test: stops the program if something is wrong. *)
55+proc main*;
56+begin
57+ if (cmp("a", "b") # -1) or (cmp("b", "a") # 1) or (cmp("ab", "ab") # 0)
58+ or (cmp("a", "ab") # -1) or (cmp("", "") # 0) then Rt.stop("Str.cmp"); end;
59+ if not eq("x", "x") or eq("x", "y") then Rt.stop("Str.eq"); end;
60+ if (hash("") # 0CBF29CE484222325H) or (hash("a") # 0AF63DC4C8601EC8CH) then Rt.stop("Str.hash"); end;
61+ if (find("hello", "ll") # 2) or (find("hello", "x") # -1) or (find("", "") # 0)
62+ or (find("ab", "abc") # -1) then Rt.stop("Str.find"); end;
63+ if not hasPrefix("hello", "he") or hasPrefix("he", "hello") then Rt.stop("Str.hasPrefix"); end;
64+end;
65+
66+end Str.

lib/Sys.jed deleted +0 -130

@@ -1,130 +0,0 @@
1-(* System calls through the C library: Sys for the targets that have no
2- file of their own, with the same exports. A program that imports it
3- uses C. *)
4-module Sys;
5-import C;
6-
7-const
8- stdin* = 0;
9- stdout* = 1;
10- stderr* = 2;
11-
12-(* minus errno, as a system call returns it *)
13-proc failed: I64;
14-var e: ^I32;
15-begin
16- e := C.__errno_location();
17- return -I64(e^);
18-end;
19-
20-(* Writes s to the file descriptor fd; the number of bytes written, or
21- minus an errno. *)
22-proc write*(fd: I64; s: []U8): I64;
23-var r: I64;
24-begin
25- if LEN(s) = 0 then return 0; end;
26- r := C.write(I32(fd), ADR(s[0]), U64(LEN(s)));
27- if r < 0 then return failed(); end;
28- return r;
29-end;
30-
31-(* Reads into buf from fd; the number of bytes read, 0 at the end, or
32- minus an errno. *)
33-proc read*(fd: I64; buf: []U8): I64;
34-var r: I64;
35-begin
36- if LEN(buf) = 0 then return 0; end;
37- r := C.read(I32(fd), ADR(buf[0]), U64(LEN(buf)));
38- if r < 0 then return failed(); end;
39- return r;
40-end;
41-
42-(* path, a C string in buf, or false if it doesn't fit. *)
43-proc cstr(path: []U8; var buf: [4096]U8): BOOL;
44-var i: I64;
45-begin
46- if LEN(path) >= LEN(buf) then return false; end;
47- for i := 0 to LEN(path) - 1 do buf[i] := path[i]; end;
48- buf[LEN(path)] := 0;
49- return true;
50-end;
51-
52-(* The file at path, opened for reading: its file descriptor, or minus
53- an errno. *)
54-proc openRead*(path: []U8): I64;
55-var buf: [4096]U8; r: I64;
56-begin
57- if not cstr(path, buf) then return -36; end;
58- r := I64(C.open(ADR(buf[0]), 0)); (* O_RDONLY is 0 everywhere *)
59- if r < 0 then return failed(); end;
60- return r;
61-end;
62-
63-(* The file at path, made empty or new, opened for writing, readable by
64- all: its file descriptor, or minus an errno. *)
65-proc create*(path: []U8): I64;
66-var buf: [4096]U8; r: I64;
67-begin
68- if not cstr(path, buf) then return -36; end;
69- r := I64(C.creat(ADR(buf[0]), 420)); (* mode 644 *)
70- if r < 0 then return failed(); end;
71- return r;
72-end;
73-
74-proc close*(fd: I64);
75-begin
76- C.close(I32(fd));
77-end;
78-
79-(* size bytes of fresh, zeroed memory from the system, a multiple of
80- pages, or nil. *)
81-proc mmap*(size: I64): ^U8;
82-var p: ^U8;
83-begin
84- p := C.mmap(nil, U64(size), 3, 22H, -1, 0); (* read, write; private, anonymous *)
85- if I64(p) = -1 then return nil; end;
86- return p;
87-end;
88-
89-proc munmap*(p: ^U8; size: I64);
90-begin
91- C.munmap(p, U64(size));
92-end;
93-
94-proc isTerminal*(fd: I64): BOOL;
95-begin
96- return C.isatty(I32(fd)) = 1;
97-end;
98-
99-proc yield*;
100-begin
101- C.sched_yield();
102-end;
103-
104-(* Ends the program, at once, with status. *)
105-proc exit*(status: I64);
106-begin
107- C._exit(I32(status));
108-end;
109-
110-(* The module's test: a file written, read back and closed. *)
111-proc main*;
112-var fd, n: I64; buf: [16]U8; p: ^U8;
113-begin
114- fd := create("/tmp/jed-sys-test");
115- if fd < 0 then exit(2); end;
116- if write(fd, "hello") # 5 then exit(2); end;
117- close(fd);
118- fd := openRead("/tmp/jed-sys-test");
119- if fd < 0 then exit(2); end;
120- n := read(fd, buf);
121- if (n # 5) or (buf[0..5] # "hello") or (read(fd, buf) # 0) then exit(2); end;
122- close(fd);
123- if openRead("/no/such/file") >= 0 then exit(2); end;
124- if isTerminal(-1) then exit(2); end;
125- p := mmap(100);
126- if (p = nil) or (p[99] # 0) then exit(2); end;
127- munmap(p, 100);
128-end;
129-
130-end Sys.

lib/Sys.linux-x86_64.jed deleted +0 -114

@@ -1,114 +0,0 @@
1-(* System calls on Linux for x86-64. Other targets supply their own
2- Sys, with the same exports. *)
3-module Sys;
4-
5-const
6- stdin* = 0;
7- stdout* = 1;
8- stderr* = 2;
9-
10-(* Writes s to the file descriptor fd; the number of bytes written, or
11- minus an errno. *)
12-proc write*(fd: I64; s: []U8): I64;
13-begin
14- if LEN(s) = 0 then return 0; end;
15- return SYSCALL(1, fd, ADR(s[0]), LEN(s));
16-end;
17-
18-(* Reads into buf from fd; the number of bytes read, 0 at the end, or
19- minus an errno. *)
20-proc read*(fd: I64; buf: []U8): I64;
21-begin
22- if LEN(buf) = 0 then return 0; end;
23- return SYSCALL(0, fd, ADR(buf[0]), LEN(buf));
24-end;
25-
26-(* path, a C string in buf, or false if it doesn't fit. *)
27-proc cstr(path: []U8; var buf: [4096]U8): BOOL;
28-var i: I64;
29-begin
30- if LEN(path) >= LEN(buf) then return false; end;
31- for i := 0 to LEN(path) - 1 do buf[i] := path[i]; end;
32- buf[LEN(path)] := 0;
33- return true;
34-end;
35-
36-(* The file at path, opened for reading: its file descriptor, or minus
37- an errno. *)
38-proc openRead*(path: []U8): I64;
39-var buf: [4096]U8;
40-begin
41- if not cstr(path, buf) then return -36; end; (* ENAMETOOLONG *)
42- return SYSCALL(2, ADR(buf), 0); (* open, O_RDONLY *)
43-end;
44-
45-(* The file at path, made empty or new, opened for writing, readable by
46- all: its file descriptor, or minus an errno. *)
47-proc create*(path: []U8): I64;
48-var buf: [4096]U8;
49-begin
50- if not cstr(path, buf) then return -36; end;
51- return SYSCALL(85, ADR(buf), 420); (* creat, mode 644 *)
52-end;
53-
54-proc close*(fd: I64);
55-begin
56- SYSCALL(3, fd);
57-end;
58-
59-(* size bytes of fresh, zeroed memory from the system, a multiple of
60- pages, or nil. *)
61-proc mmap*(size: I64): ^U8;
62-var p: I64;
63-begin
64- p := SYSCALL(9, 0, size, 3, 22H, -1, 0); (* read, write; private, anonymous *)
65- if p < 0 then return nil; end;
66- return ^U8(p);
67-end;
68-
69-proc munmap*(p: ^U8; size: I64);
70-begin
71- SYSCALL(11, p, size);
72-end;
73-
74-(* Whether the file descriptor fd is a terminal: whether it has a
75- terminal's settings to read (ioctl TCGETS). *)
76-proc isTerminal*(fd: I64): BOOL;
77-var t: [8]I64; (* struct termios: 60 bytes *)
78-begin
79- return SYSCALL(16, fd, 5401H, ADR(t)) = 0;
80-end;
81-
82-(* Gives the processor to another thread. *)
83-proc yield*;
84-begin
85- SYSCALL(24);
86-end;
87-
88-(* Ends the program, at once, with status. *)
89-proc exit*(status: I64);
90-begin
91- SYSCALL(231, status);
92-end;
93-
94-(* The module's test: a file written, read back and closed. *)
95-proc main*;
96-var fd, n: I64; buf: [16]U8; p: ^U8;
97-begin
98- fd := create("/tmp/jed-sys-test");
99- if fd < 0 then exit(2); end;
100- if write(fd, "hello") # 5 then exit(2); end;
101- close(fd);
102- fd := openRead("/tmp/jed-sys-test");
103- if fd < 0 then exit(2); end;
104- n := read(fd, buf);
105- if (n # 5) or (buf[0..5] # "hello") or (read(fd, buf) # 0) then exit(2); end;
106- close(fd);
107- if openRead("/no/such/file") >= 0 then exit(2); end;
108- if isTerminal(-1) then exit(2); end;
109- p := mmap(100);
110- if (p = nil) or (p[99] # 0) then exit(2); end;
111- munmap(p, 100);
112-end;
113-
114-end Sys.

lib/Sys.linux-x86_64.raz (history) added +114 -0

@@ -0,0 +1,114 @@
1+(* System calls on Linux for x86-64. Other targets supply their own
2+ Sys, with the same exports. *)
3+module Sys;
4+
5+const
6+ stdin* = 0;
7+ stdout* = 1;
8+ stderr* = 2;
9+
10+(* Writes s to the file descriptor fd; the number of bytes written, or
11+ minus an errno. *)
12+proc write*(fd: I64; s: []U8): I64;
13+begin
14+ if LEN(s) = 0 then return 0; end;
15+ return SYSCALL(1, fd, ADR(s[0]), LEN(s));
16+end;
17+
18+(* Reads into buf from fd; the number of bytes read, 0 at the end, or
19+ minus an errno. *)
20+proc read*(fd: I64; buf: []U8): I64;
21+begin
22+ if LEN(buf) = 0 then return 0; end;
23+ return SYSCALL(0, fd, ADR(buf[0]), LEN(buf));
24+end;
25+
26+(* path, a C string in buf, or false if it doesn't fit. *)
27+proc cstr(path: []U8; var buf: [4096]U8): BOOL;
28+var i: I64;
29+begin
30+ if LEN(path) >= LEN(buf) then return false; end;
31+ for i := 0 to LEN(path) - 1 do buf[i] := path[i]; end;
32+ buf[LEN(path)] := 0;
33+ return true;
34+end;
35+
36+(* The file at path, opened for reading: its file descriptor, or minus
37+ an errno. *)
38+proc openRead*(path: []U8): I64;
39+var buf: [4096]U8;
40+begin
41+ if not cstr(path, buf) then return -36; end; (* ENAMETOOLONG *)
42+ return SYSCALL(2, ADR(buf), 0); (* open, O_RDONLY *)
43+end;
44+
45+(* The file at path, made empty or new, opened for writing, readable by
46+ all: its file descriptor, or minus an errno. *)
47+proc create*(path: []U8): I64;
48+var buf: [4096]U8;
49+begin
50+ if not cstr(path, buf) then return -36; end;
51+ return SYSCALL(85, ADR(buf), 420); (* creat, mode 644 *)
52+end;
53+
54+proc close*(fd: I64);
55+begin
56+ SYSCALL(3, fd);
57+end;
58+
59+(* size bytes of fresh, zeroed memory from the system, a multiple of
60+ pages, or nil. *)
61+proc mmap*(size: I64): ^U8;
62+var p: I64;
63+begin
64+ p := SYSCALL(9, 0, size, 3, 22H, -1, 0); (* read, write; private, anonymous *)
65+ if p < 0 then return nil; end;
66+ return ^U8(p);
67+end;
68+
69+proc munmap*(p: ^U8; size: I64);
70+begin
71+ SYSCALL(11, p, size);
72+end;
73+
74+(* Whether the file descriptor fd is a terminal: whether it has a
75+ terminal's settings to read (ioctl TCGETS). *)
76+proc isTerminal*(fd: I64): BOOL;
77+var t: [8]I64; (* struct termios: 60 bytes *)
78+begin
79+ return SYSCALL(16, fd, 5401H, ADR(t)) = 0;
80+end;
81+
82+(* Gives the processor to another thread. *)
83+proc yield*;
84+begin
85+ SYSCALL(24);
86+end;
87+
88+(* Ends the program, at once, with status. *)
89+proc exit*(status: I64);
90+begin
91+ SYSCALL(231, status);
92+end;
93+
94+(* The module's test: a file written, read back and closed. *)
95+proc main*;
96+var fd, n: I64; buf: [16]U8; p: ^U8;
97+begin
98+ fd := create("/tmp/raz-sys-test");
99+ if fd < 0 then exit(2); end;
100+ if write(fd, "hello") # 5 then exit(2); end;
101+ close(fd);
102+ fd := openRead("/tmp/raz-sys-test");
103+ if fd < 0 then exit(2); end;
104+ n := read(fd, buf);
105+ if (n # 5) or (buf[0..5] # "hello") or (read(fd, buf) # 0) then exit(2); end;
106+ close(fd);
107+ if openRead("/no/such/file") >= 0 then exit(2); end;
108+ if isTerminal(-1) then exit(2); end;
109+ p := mmap(100);
110+ if (p = nil) or (p[99] # 0) then exit(2); end;
111+ munmap(p, 100);
112+end;
113+
114+end Sys.

lib/Sys.raz (history) added +130 -0

@@ -0,0 +1,130 @@
1+(* System calls through the C library: Sys for the targets that have no
2+ file of their own, with the same exports. A program that imports it
3+ uses C. *)
4+module Sys;
5+import C;
6+
7+const
8+ stdin* = 0;
9+ stdout* = 1;
10+ stderr* = 2;
11+
12+(* minus errno, as a system call returns it *)
13+proc failed: I64;
14+var e: ^I32;
15+begin
16+ e := C.__errno_location();
17+ return -I64(e^);
18+end;
19+
20+(* Writes s to the file descriptor fd; the number of bytes written, or
21+ minus an errno. *)
22+proc write*(fd: I64; s: []U8): I64;
23+var r: I64;
24+begin
25+ if LEN(s) = 0 then return 0; end;
26+ r := C.write(I32(fd), ADR(s[0]), U64(LEN(s)));
27+ if r < 0 then return failed(); end;
28+ return r;
29+end;
30+
31+(* Reads into buf from fd; the number of bytes read, 0 at the end, or
32+ minus an errno. *)
33+proc read*(fd: I64; buf: []U8): I64;
34+var r: I64;
35+begin
36+ if LEN(buf) = 0 then return 0; end;
37+ r := C.read(I32(fd), ADR(buf[0]), U64(LEN(buf)));
38+ if r < 0 then return failed(); end;
39+ return r;
40+end;
41+
42+(* path, a C string in buf, or false if it doesn't fit. *)
43+proc cstr(path: []U8; var buf: [4096]U8): BOOL;
44+var i: I64;
45+begin
46+ if LEN(path) >= LEN(buf) then return false; end;
47+ for i := 0 to LEN(path) - 1 do buf[i] := path[i]; end;
48+ buf[LEN(path)] := 0;
49+ return true;
50+end;
51+
52+(* The file at path, opened for reading: its file descriptor, or minus
53+ an errno. *)
54+proc openRead*(path: []U8): I64;
55+var buf: [4096]U8; r: I64;
56+begin
57+ if not cstr(path, buf) then return -36; end;
58+ r := I64(C.open(ADR(buf[0]), 0)); (* O_RDONLY is 0 everywhere *)
59+ if r < 0 then return failed(); end;
60+ return r;
61+end;
62+
63+(* The file at path, made empty or new, opened for writing, readable by
64+ all: its file descriptor, or minus an errno. *)
65+proc create*(path: []U8): I64;
66+var buf: [4096]U8; r: I64;
67+begin
68+ if not cstr(path, buf) then return -36; end;
69+ r := I64(C.creat(ADR(buf[0]), 420)); (* mode 644 *)
70+ if r < 0 then return failed(); end;
71+ return r;
72+end;
73+
74+proc close*(fd: I64);
75+begin
76+ C.close(I32(fd));
77+end;
78+
79+(* size bytes of fresh, zeroed memory from the system, a multiple of
80+ pages, or nil. *)
81+proc mmap*(size: I64): ^U8;
82+var p: ^U8;
83+begin
84+ p := C.mmap(nil, U64(size), 3, 22H, -1, 0); (* read, write; private, anonymous *)
85+ if I64(p) = -1 then return nil; end;
86+ return p;
87+end;
88+
89+proc munmap*(p: ^U8; size: I64);
90+begin
91+ C.munmap(p, U64(size));
92+end;
93+
94+proc isTerminal*(fd: I64): BOOL;
95+begin
96+ return C.isatty(I32(fd)) = 1;
97+end;
98+
99+proc yield*;
100+begin
101+ C.sched_yield();
102+end;
103+
104+(* Ends the program, at once, with status. *)
105+proc exit*(status: I64);
106+begin
107+ C._exit(I32(status));
108+end;
109+
110+(* The module's test: a file written, read back and closed. *)
111+proc main*;
112+var fd, n: I64; buf: [16]U8; p: ^U8;
113+begin
114+ fd := create("/tmp/raz-sys-test");
115+ if fd < 0 then exit(2); end;
116+ if write(fd, "hello") # 5 then exit(2); end;
117+ close(fd);
118+ fd := openRead("/tmp/raz-sys-test");
119+ if fd < 0 then exit(2); end;
120+ n := read(fd, buf);
121+ if (n # 5) or (buf[0..5] # "hello") or (read(fd, buf) # 0) then exit(2); end;
122+ close(fd);
123+ if openRead("/no/such/file") >= 0 then exit(2); end;
124+ if isTerminal(-1) then exit(2); end;
125+ p := mmap(100);
126+ if (p = nil) or (p[99] # 0) then exit(2); end;
127+ munmap(p, 100);
128+end;
129+
130+end Sys.

lib/Thread.linux-x86_64.jed deleted +0 -178

@@ -1,178 +0,0 @@
1-(* Threads for programs without C, made with the clone system call.
2- Each runs on a stack of its own, mmaped, with a page below it that
3- can't be touched, so that running off the stack stops the program
4- rather than spoiling what lies below. join waits on the thread's id,
5- which the kernel clears, and wakes it for, when the thread ends;
6- a Mutex sleeps on a futex. A program with C threads uses C's,
7- through pthread_create, and so can't use these. *)
8-module Thread;
9-import Sys, Rt;
10-link static;
11-
12-const
13- Failed*: ERROR = "can't start a thread";
14- Stack = 1 shl 20;
15- Page = 4096;
16- (* clone: share memory, files, signal handlers, the thread group;
17- write the id to tid, and clear it at the end *)
18- Flags = 350F00H;
19- FutexWait = 0;
20- FutexWake = 1;
21- Private = 128;
22-
23-type
24- Thread* = record
25- tid: I64; (* the kernel's id, until the thread ends *)
26- base: ^U8; (* its stack's mapping, the guard page first *)
27- size: I64;
28- end;
29- (* 0 free, 1 taken, 2 taken with a thread waiting *)
30- Mutex* = record state: I64; end;
31-
32-(* clone(flags, stack, tid, tid), the new thread starting with fn(arg)
33- on stack and ending, when fn returns, with the exit system call.
34- fn and arg go on the new stack first, since the new thread has no
35- registers but rsp of its own to find them by. Returns the new
36- thread's id, or minus an errno. *)
37-proc start(flags: I64; stack: ^U8; ptid, ctid: ^I64; fn: proc(arg: ^U8); arg: ^U8): I64;
38-code 48H, 83H, 0EEH, 10H, (* sub rsi, 16 *)
39- 4CH, 89H, 06H, (* mov [rsi], r8 *)
40- 4CH, 89H, 4EH, 08H, (* mov [rsi + 8], r9 *)
41- 49H, 89H, 0CAH, (* mov r10, rcx *)
42- 45H, 31H, 0C0H, (* xor r8d, r8d: no tls *)
43- 0B8H, 38H, 0, 0, 0, (* mov eax, 56: clone *)
44- 0FH, 05H, (* syscall *)
45- 48H, 85H, 0C0H, (* test rax, rax *)
46- 75H, 0DH, (* jnz parent *)
47- 58H, (* pop rax: fn *)
48- 5FH, (* pop rdi: arg *)
49- 0FFH, 0D0H, (* call rax *)
50- 31H, 0FFH, (* xor edi, edi *)
51- 0B8H, 3CH, 0, 0, 0, (* mov eax, 60: exit, this thread only *)
52- 0FH, 05H, (* syscall *)
53- 0C3H; (* parent: ret *)
54-
55-proc futex(word: ^I64; op, val: I64): I64;
56-begin
57- return SYSCALL(202, word, op, val, 0);
58-end;
59-
60-(* Starts p(arg) in a new thread. *)
61-proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR);
62-var base: ^U8; t: ^Thread; size: I64;
63-begin
64- size := Stack + Page;
65- base := Sys.mmap(size);
66- if base = nil then return nil, Failed; end;
67- (* mprotect: the guard page, no access; it fails when the process
68- has as many mappings as it may *)
69- if SYSCALL(10, base, Page, 0) < 0 then
70- Sys.munmap(base, size);
71- return nil, Failed;
72- end;
73- (* the Thread at the top, the stack below it, aligned to 16 *)
74- t := ^Thread(base + size - 32);
75- t^.base := base;
76- t^.size := size;
77- if start(Flags, base + size - 32, ADR(t^.tid), ADR(t^.tid), p, arg) < 0 then
78- Sys.munmap(base, size);
79- return nil, Failed;
80- end;
81- return t, nil;
82-end;
83-
84-(* Waits for t to end, then frees its stack. *)
85-proc join*(t: ^Thread);
86-var tid: ^VOLATILE I64; v: I64; base: ^U8; size: I64;
87-begin
88- tid := ADR(t^.tid);
89- v := tid^;
90- while v # 0 do
91- futex(ADR(t^.tid), FutexWait, v);
92- v := tid^;
93- end;
94- base := t^.base;
95- size := t^.size;
96- Sys.munmap(base, size);
97-end;
98-
99-proc lock*(m: ^Mutex);
100-var c: I64;
101-begin
102- if CAS(ADR(m^.state), 0, 1) then return; end;
103- c := XCHG(ADR(m^.state), 2);
104- while c # 0 do
105- futex(ADR(m^.state), FutexWait + Private, 2);
106- c := XCHG(ADR(m^.state), 2);
107- end;
108-end;
109-
110-proc unlock*(m: ^Mutex);
111-begin
112- if XADD(ADR(m^.state), -1) # 1 then
113- XCHG(ADR(m^.state), 0);
114- futex(ADR(m^.state), FutexWake + Private, 1);
115- end;
116-end;
117-
118-(* The module's test, and make stress's. It starts n threads, in waves
119- of up to alive at a time, all waiting on one Mutex the test holds
120- until the wave is out; each, given it, adds one to a count. Every
121- thread is joined, so that a stack join didn't free would, over
122- enough of them, run the process out of mappings. With "fail", it
123- starts threads, all waiting, until spawn fails, which it must do
124- with Failed: make stress and make check run it with little memory.
125- Thread [n alive], Thread fail *)
126-var
127- testLock: Mutex;
128- testCount: I64;
129- wave: [1000]^Thread;
130-
131-proc testWork(arg: ^U8);
132-begin
133- lock(ADR(testLock));
134- INC(testCount);
135- unlock(ADR(testLock));
136-end;
137-
138-proc testArg(i: I64): I64;
139-var s: ^U8; n, v: I64;
140-begin
141- s := ARGV()[i];
142- v := 0;
143- n := 0;
144- while s[n] # 0 do v := v * 10 + I64(s[n]) - '0'; INC(n); end;
145- return v;
146-end;
147-
148-proc main*;
149-var n, alive, started, k, i: I64; t: ^Thread; err: ERROR; fail: BOOL;
150-begin
151- n := 2000; alive := 50;
152- fail := (ARGC() = 2) and (ARGV()[1][0] = 'f');
153- if ARGC() = 3 then n := testArg(1); alive := testArg(2); end;
154- if fail then n := LEN(wave); alive := LEN(wave); end;
155- if (alive < 1) or (alive > LEN(wave)) then Rt.stop("Thread: alive is 1 to 1000"); end;
156- started := 0;
157- while started < n do
158- lock(ADR(testLock));
159- k := 0;
160- while (k < alive) and (started + k < n) do
161- t, err := spawn(testWork, nil);
162- if err # nil then
163- if not fail or (err # Failed) then Rt.stop("Thread.spawn failed"); end;
164- n := started + k;
165- break;
166- end;
167- wave[k] := t;
168- INC(k);
169- end;
170- unlock(ADR(testLock));
171- for i := 0 to k - 1 do join(wave[i]); end;
172- started := started + k;
173- end;
174- if testCount # started then Rt.stop("Thread: a thread didn't run"); end;
175- if fail and (started = LEN(wave)) then Rt.stop("Thread: spawn never failed"); end;
176-end;
177-
178-end Thread.

lib/Thread.linux-x86_64.raz (history) added +178 -0

@@ -0,0 +1,178 @@
1+(* Threads for programs without C, made with the clone system call.
2+ Each runs on a stack of its own, mmaped, with a page below it that
3+ can't be touched, so that running off the stack stops the program
4+ rather than spoiling what lies below. join waits on the thread's id,
5+ which the kernel clears, and wakes it for, when the thread ends;
6+ a Mutex sleeps on a futex. A program with C threads uses C's,
7+ through pthread_create, and so can't use these. *)
8+module Thread;
9+import Sys, Rt;
10+link static;
11+
12+const
13+ Failed*: ERROR = "can't start a thread";
14+ Stack = 1 shl 20;
15+ Page = 4096;
16+ (* clone: share memory, files, signal handlers, the thread group;
17+ write the id to tid, and clear it at the end *)
18+ Flags = 350F00H;
19+ FutexWait = 0;
20+ FutexWake = 1;
21+ Private = 128;
22+
23+type
24+ Thread* = record
25+ tid: I64; (* the kernel's id, until the thread ends *)
26+ base: ^U8; (* its stack's mapping, the guard page first *)
27+ size: I64;
28+ end;
29+ (* 0 free, 1 taken, 2 taken with a thread waiting *)
30+ Mutex* = record state: I64; end;
31+
32+(* clone(flags, stack, tid, tid), the new thread starting with fn(arg)
33+ on stack and ending, when fn returns, with the exit system call.
34+ fn and arg go on the new stack first, since the new thread has no
35+ registers but rsp of its own to find them by. Returns the new
36+ thread's id, or minus an errno. *)
37+proc start(flags: I64; stack: ^U8; ptid, ctid: ^I64; fn: proc(arg: ^U8); arg: ^U8): I64;
38+code 48H, 83H, 0EEH, 10H, (* sub rsi, 16 *)
39+ 4CH, 89H, 06H, (* mov [rsi], r8 *)
40+ 4CH, 89H, 4EH, 08H, (* mov [rsi + 8], r9 *)
41+ 49H, 89H, 0CAH, (* mov r10, rcx *)
42+ 45H, 31H, 0C0H, (* xor r8d, r8d: no tls *)
43+ 0B8H, 38H, 0, 0, 0, (* mov eax, 56: clone *)
44+ 0FH, 05H, (* syscall *)
45+ 48H, 85H, 0C0H, (* test rax, rax *)
46+ 75H, 0DH, (* jnz parent *)
47+ 58H, (* pop rax: fn *)
48+ 5FH, (* pop rdi: arg *)
49+ 0FFH, 0D0H, (* call rax *)
50+ 31H, 0FFH, (* xor edi, edi *)
51+ 0B8H, 3CH, 0, 0, 0, (* mov eax, 60: exit, this thread only *)
52+ 0FH, 05H, (* syscall *)
53+ 0C3H; (* parent: ret *)
54+
55+proc futex(word: ^I64; op, val: I64): I64;
56+begin
57+ return SYSCALL(202, word, op, val, 0);
58+end;
59+
60+(* Starts p(arg) in a new thread. *)
61+proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR);
62+var base: ^U8; t: ^Thread; size: I64;
63+begin
64+ size := Stack + Page;
65+ base := Sys.mmap(size);
66+ if base = nil then return nil, Failed; end;
67+ (* mprotect: the guard page, no access; it fails when the process
68+ has as many mappings as it may *)
69+ if SYSCALL(10, base, Page, 0) < 0 then
70+ Sys.munmap(base, size);
71+ return nil, Failed;
72+ end;
73+ (* the Thread at the top, the stack below it, aligned to 16 *)
74+ t := ^Thread(base + size - 32);
75+ t^.base := base;
76+ t^.size := size;
77+ if start(Flags, base + size - 32, ADR(t^.tid), ADR(t^.tid), p, arg) < 0 then
78+ Sys.munmap(base, size);
79+ return nil, Failed;
80+ end;
81+ return t, nil;
82+end;
83+
84+(* Waits for t to end, then frees its stack. *)
85+proc join*(t: ^Thread);
86+var tid: ^VOLATILE I64; v: I64; base: ^U8; size: I64;
87+begin
88+ tid := ADR(t^.tid);
89+ v := tid^;
90+ while v # 0 do
91+ futex(ADR(t^.tid), FutexWait, v);
92+ v := tid^;
93+ end;
94+ base := t^.base;
95+ size := t^.size;
96+ Sys.munmap(base, size);
97+end;
98+
99+proc lock*(m: ^Mutex);
100+var c: I64;
101+begin
102+ if CAS(ADR(m^.state), 0, 1) then return; end;
103+ c := XCHG(ADR(m^.state), 2);
104+ while c # 0 do
105+ futex(ADR(m^.state), FutexWait + Private, 2);
106+ c := XCHG(ADR(m^.state), 2);
107+ end;
108+end;
109+
110+proc unlock*(m: ^Mutex);
111+begin
112+ if XADD(ADR(m^.state), -1) # 1 then
113+ XCHG(ADR(m^.state), 0);
114+ futex(ADR(m^.state), FutexWake + Private, 1);
115+ end;
116+end;
117+
118+(* The module's test, and make stress's. It starts n threads, in waves
119+ of up to alive at a time, all waiting on one Mutex the test holds
120+ until the wave is out; each, given it, adds one to a count. Every
121+ thread is joined, so that a stack join didn't free would, over
122+ enough of them, run the process out of mappings. With "fail", it
123+ starts threads, all waiting, until spawn fails, which it must do
124+ with Failed: make stress and make check run it with little memory.
125+ Thread [n alive], Thread fail *)
126+var
127+ testLock: Mutex;
128+ testCount: I64;
129+ wave: [1000]^Thread;
130+
131+proc testWork(arg: ^U8);
132+begin
133+ lock(ADR(testLock));
134+ INC(testCount);
135+ unlock(ADR(testLock));
136+end;
137+
138+proc testArg(i: I64): I64;
139+var s: ^U8; n, v: I64;
140+begin
141+ s := ARGV()[i];
142+ v := 0;
143+ n := 0;
144+ while s[n] # 0 do v := v * 10 + I64(s[n]) - '0'; INC(n); end;
145+ return v;
146+end;
147+
148+proc main*;
149+var n, alive, started, k, i: I64; t: ^Thread; err: ERROR; fail: BOOL;
150+begin
151+ n := 2000; alive := 50;
152+ fail := (ARGC() = 2) and (ARGV()[1][0] = 'f');
153+ if ARGC() = 3 then n := testArg(1); alive := testArg(2); end;
154+ if fail then n := LEN(wave); alive := LEN(wave); end;
155+ if (alive < 1) or (alive > LEN(wave)) then Rt.stop("Thread: alive is 1 to 1000"); end;
156+ started := 0;
157+ while started < n do
158+ lock(ADR(testLock));
159+ k := 0;
160+ while (k < alive) and (started + k < n) do
161+ t, err := spawn(testWork, nil);
162+ if err # nil then
163+ if not fail or (err # Failed) then Rt.stop("Thread.spawn failed"); end;
164+ n := started + k;
165+ break;
166+ end;
167+ wave[k] := t;
168+ INC(k);
169+ end;
170+ unlock(ADR(testLock));
171+ for i := 0 to k - 1 do join(wave[i]); end;
172+ started := started + k;
173+ end;
174+ if testCount # started then Rt.stop("Thread: a thread didn't run"); end;
175+ if fail and (started = LEN(wave)) then Rt.stop("Thread: spawn never failed"); end;
176+end;
177+
178+end Thread.

src/elf.pas modified +1 -1

@@ -195,7 +195,7 @@
195195 PutStr(mainPath);
196196 if FpGetcwd(@cwd, SizeOf(cwd)) = nil then cwd[0] := #0;
197197 PutStr(PChar(@cwd));
198- PutStr('jed');
198+ PutStr('raz');
199199 PutN(0, 4); { the line table, at 0 }
200200 PutN(Base + textOff, 8); PutN(textSize, 8); { the code, all of it }
201201 Patch(off[1], len - off[1] - 4, 4);

src/jed.pas deleted +0 -214

@@ -1,214 +0,0 @@
1-{ jed.pas: the command line.
2-
3- jed [-I dir]... [-o file] Main.jed
4- jed run [-I dir]... Main.jed [arg]...
5- jed --version
6-
7- Compiles the main module and every module it imports, writes the
8- entry point, links what it reaches, and writes the executable: by
9- default the main module's file without its .jed. jed run writes it
10- to a memfd instead, a file that lives only in memory, and executes
11- it in jed's place with the arguments after Main.jed, so its status
12- is the program's; its argv[0] is Main.jed.
13-
14- The program starts by saving argc and argv, runs every module's body
15- (those of the modules the program imports, imported modules first),
16- then the main module's main, and ends with Rt.exit and main's
17- status. A static program does this from its entry point. One that
18- uses C starts through the C library, __libc_start_main, which sets
19- C up and calls this as C's main; first it gives Rt C's exit, which
20- Rt.exit then ends the program with.
21-
22- Depends on: everything else. }
23-
24-program jed;
25-
26-{$mode objfpc}{$H-}
27-
28-uses math, BaseUnix, syscall, scan, sym, x64, gen, parse, link, elf;
29-
30-const
31- Version = '0.3.0';
32- Report = '2026-10.0'; { the version of doc/jed.md it follows }
33- MemfdCreate = 319; { the system call; FPC 3.2.2 has no name for it }
34- MfdCloexec = 1; { an ELF still executes: the kernel opens it first }
35-
36-{ The modules the program uses: the main module, Rt, and every module
37- they import. A module read only for the interface check is not. }
38-procedure Use(m: PModule);
39-var i: PImport;
40-begin
41- if m^.used then exit;
42- m^.used := true;
43- i := m^.imports;
44- while i <> nil do begin
45- Use(i^.module);
46- i := i^.next;
47- end;
48-end;
49-
50-{ Whether the program uses C: if so, the libraries it needs go to
51- elf.pas, the C library first. }
52-function UsesC: boolean;
53-var m, st, c: PModule; l: PLib; i: longint; seen: boolean;
54-begin
55- st := nil; c := nil;
56- numNeeded := 1;
57- needed[0] := Intern(PChar('libc.so.6'), 9);
58- m := firstModule;
59- while m <> nil do begin
60- if m^.used and m^.linkStatic then st := m;
61- if m^.used and m^.usesC then c := m;
62- l := m^.libs;
63- while m^.used and (l <> nil) do begin
64- seen := false;
65- for i := 0 to numNeeded - 1 do seen := seen or (needed[i] = l^.name);
66- if not seen then begin
67- if numNeeded > High(needed) then Fatal('too many libraries');
68- needed[numNeeded] := l^.name;
69- inc(numNeeded);
70- end;
71- l := l^.next;
72- end;
73- m := m^.next;
74- end;
75- if (st <> nil) and (c <> nil) then
76- Fatal(NameOf(st^.name) + ' says link static, but ' + NameOf(c^.name) + ' uses C');
77- if c = nil then numNeeded := 0;
78- UsesC := c <> nil;
79-end;
80-
81-function RtObj(rt: PModule; const n: shortstring): PObj;
82-var o: PObj;
83-begin
84- o := Find(rt^.scope, Intern(@n[1], length(n)));
85- if o = nil then Fatal('Rt has no ' + n);
86- RtObj := o;
87-end;
88-
89-var
90- path, outPath, dir, s: shortstring;
91- i, first, entry, start, fd: longint;
92- m, rt: PModule;
93- main: PObj;
94- hasResult, dynamic, run: boolean;
95-
96-begin
97- { constants fold as the machine computes: NaN and infinities, no traps }
98- SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, exUnderflow, exPrecision]);
99- path := '';
100- outPath := '';
101- numInc := 0;
102- run := (ParamCount >= 1) and (ParamStr(1) = 'run');
103- i := 1 + ord(run);
104- while i <= ParamCount do begin
105- s := ParamStr(i);
106- if s = '-I' then begin
107- inc(i);
108- if numInc > High(incDirs) then Fatal('too many -I');
109- incDirs[numInc] := ParamStr(i);
110- inc(numInc);
111- end else if s = '-o' then begin
112- inc(i);
113- outPath := ParamStr(i);
114- end else if s = '--version' then begin
115- writeln('jed ', Version, ', report ', Report);
116- Halt(0);
117- end else if (s <> '') and (s[1] = '-') then
118- Fatal('unknown option ' + s)
119- else begin
120- path := s;
121- first := i;
122- if run then break; { the rest are the program's }
123- end;
124- inc(i);
125- end;
126- if path = '' then
127- Fatal('usage: jed [-I dir]... [-o file] Main.jed, or jed run [-I dir]... Main.jed [arg]...');
128- if run and (outPath <> '') then Fatal('jed run takes no -o');
129- dir := ParamStr(0);
130- i := length(dir);
131- while (i > 0) and (dir[i] <> '/') do dec(i);
132- if i = 0 then libDir := 'lib' else libDir := copy(dir, 1, i) + 'lib';
133- if outPath = '' then begin
134- outPath := path;
135- if copy(outPath, length(outPath) - 3, 4) = '.jed' then
136- outPath := copy(outPath, 1, length(outPath) - 4)
137- else outPath := outPath + '.out';
138- end;
139-
140- m := CompileMain(path);
141-
142- Use(m);
143- rt := firstModule;
144- while (rt <> nil) and (NameOf(rt^.name) <> 'Rt') do rt := rt^.next;
145- if rt <> nil then Use(rt);
146-
147- main := Find(m^.scope, Intern('main', 4));
148- hasResult := false;
149- if main <> nil then begin
150- if (main^.cls <> oProc) or not main^.exported then Fatal('main must be an exported procedure');
151- if (main^.typ^.len <> 0) or ((main^.typ^.base <> nil) and (main^.typ^.base <> tI64)) then
152- Fatal('main must be proc main* or proc main*: I64');
153- hasResult := main^.typ^.base <> nil;
154- end;
155-
156- if rt = nil then Fatal('can''t find module Rt');
157- dynamic := UsesC;
158- entry := NewChunk(secText, -1, Intern('_start', 6));
159- if dynamic then begin
160- { _start as C's crt1 does it: __libc_start_main(main, argc, argv,
161- nil, nil, rtld_fini, stack_end), with rsp aligned }
162- start := NewChunk(secText, -1, Intern('main', 4));
163- BeginChunk(entry);
164- MovRI(RBP, 0);
165- MovRR(R9, RDX);
166- Pop(RSI);
167- MovRR(RDX, RSP);
168- AluI(aluAnd, RSP, -16);
169- Push(RAX);
170- Push(RSP);
171- MovRI(R8, 0);
172- MovRI(RCX, 0);
173- Lea(RDI, MemRip(start, 0));
174- CallM(MemRip(ExternChunk(Intern('__libc_start_main', 17)), 0));
175- Ud2;
176- EndChunk(entry);
177- BeginChunk(start);
178- Push(RBP); { aligns the stack again }
179- Store(MemRip(argcChunk, 0), RDI, 8);
180- Store(MemRip(argvChunk, 0), RSI, 8);
181- Load(RAX, MemRip(ExternChunk(Intern('exit', 4)), 0), 8, false);
182- Store(MemRip(RtObj(rt, 'cExit')^.chunk, 0), RAX, 8);
183- end else begin
184- start := entry;
185- BeginChunk(entry);
186- Load(RAX, Mem(RSP, 0), 8, false);
187- Store(MemRip(argcChunk, 0), RAX, 8);
188- Lea(RAX, Mem(RSP, 8));
189- Store(MemRip(argvChunk, 0), RAX, 8);
190- end;
191- m := firstModule;
192- while m <> nil do begin
193- if m^.used and (m^.body >= 0) then CallChunk(m^.body);
194- m := m^.next;
195- end;
196- if main <> nil then CallChunk(main^.chunk);
197- if hasResult then MovRR(RDI, RAX) else MovRI(RDI, 0);
198- CallChunk(RtObj(rt, 'exit')^.chunk);
199- Ud2;
200- EndChunk(start);
201-
202- mainPath := path;
203- if run then begin
204- { argv from Main.jed on is the program's, ending in nil as it must }
205- fd := Do_SysCall(MemfdCreate, TSysParam(PChar('jed')), MfdCloexec);
206- if fd < 0 then Fatal('can''t create a memfd');
207- Str(fd, s);
208- outPath := '/proc/self/fd/' + s + #0;
209- WriteElf(outPath, entry);
210- FpExecve(@outPath[1], @argv[first], envp);
211- Fatal('can''t run ' + path);
212- end;
213- WriteElf(outPath, entry);
214-end.

src/parse.pas modified +3 -3

@@ -6,7 +6,7 @@
66 each comes after the modules it imports; that is the order in which
77 their bodies run.
88
9- A module may come in one file per target (Name.linux-x86_64.jed and
9+ A module may come in one file per target (Name.linux-x86_64.raz and
1010 so on). The file for this target is compiled; the others beside it
1111 are read for their declarations only, and must export the same
1212 interface.
@@ -1741,7 +1741,7 @@
17411741 inc(i);
17421742 end;
17431743 if (copy(f, 1, length(prefix)) = prefix) and (length(f) > 4)
1744- and (copy(f, length(f) - 3, 4) = '.jed') and (f <> chosen)
1744+ and (copy(f, length(f) - 3, 4) = '.raz') and (f <> chosen)
17451745 and (numOthers <= High(others)) then begin
17461746 others[numOthers] := f;
17471747 inc(numOthers);
@@ -1765,7 +1765,7 @@
17651765 else if i = numInc then dir := libDir
17661766 else dir := incDirs[i];
17671767 for j := 0 to 3 do begin
1768- f := NameOf(name) + Suffixes[j] + '.jed';
1768+ f := NameOf(name) + Suffixes[j] + '.raz';
17691769 if Exists(dir + '/' + f) then begin
17701770 m := CompileFile(dir + '/' + f, name, args, false);
17711771 CheckSiblings(dir, f, name, m, args);

src/raz.pas added +214 -0

@@ -0,0 +1,214 @@
1+{ raz.pas: the command line.
2+
3+ raz [-I dir]... [-o file] Main.raz
4+ raz run [-I dir]... Main.raz [arg]...
5+ raz --version
6+
7+ Compiles the main module and every module it imports, writes the
8+ entry point, links what it reaches, and writes the executable: by
9+ default the main module's file without its .raz. raz run writes it
10+ to a memfd instead, a file that lives only in memory, and executes
11+ it in raz's place with the arguments after Main.raz, so its status
12+ is the program's; its argv[0] is Main.raz.
13+
14+ The program starts by saving argc and argv, runs every module's body
15+ (those of the modules the program imports, imported modules first),
16+ then the main module's main, and ends with Rt.exit and main's
17+ status. A static program does this from its entry point. One that
18+ uses C starts through the C library, __libc_start_main, which sets
19+ C up and calls this as C's main; first it gives Rt C's exit, which
20+ Rt.exit then ends the program with.
21+
22+ Depends on: everything else. }
23+
24+program raz;
25+
26+{$mode objfpc}{$H-}
27+
28+uses math, BaseUnix, syscall, scan, sym, x64, gen, parse, link, elf;
29+
30+const
31+ Version = '0.3.0';
32+ Report = '2026-10.0'; { the version of doc/raz.md it follows }
33+ MemfdCreate = 319; { the system call; FPC 3.2.2 has no name for it }
34+ MfdCloexec = 1; { an ELF still executes: the kernel opens it first }
35+
36+{ The modules the program uses: the main module, Rt, and every module
37+ they import. A module read only for the interface check is not. }
38+procedure Use(m: PModule);
39+var i: PImport;
40+begin
41+ if m^.used then exit;
42+ m^.used := true;
43+ i := m^.imports;
44+ while i <> nil do begin
45+ Use(i^.module);
46+ i := i^.next;
47+ end;
48+end;
49+
50+{ Whether the program uses C: if so, the libraries it needs go to
51+ elf.pas, the C library first. }
52+function UsesC: boolean;
53+var m, st, c: PModule; l: PLib; i: longint; seen: boolean;
54+begin
55+ st := nil; c := nil;
56+ numNeeded := 1;
57+ needed[0] := Intern(PChar('libc.so.6'), 9);
58+ m := firstModule;
59+ while m <> nil do begin
60+ if m^.used and m^.linkStatic then st := m;
61+ if m^.used and m^.usesC then c := m;
62+ l := m^.libs;
63+ while m^.used and (l <> nil) do begin
64+ seen := false;
65+ for i := 0 to numNeeded - 1 do seen := seen or (needed[i] = l^.name);
66+ if not seen then begin
67+ if numNeeded > High(needed) then Fatal('too many libraries');
68+ needed[numNeeded] := l^.name;
69+ inc(numNeeded);
70+ end;
71+ l := l^.next;
72+ end;
73+ m := m^.next;
74+ end;
75+ if (st <> nil) and (c <> nil) then
76+ Fatal(NameOf(st^.name) + ' says link static, but ' + NameOf(c^.name) + ' uses C');
77+ if c = nil then numNeeded := 0;
78+ UsesC := c <> nil;
79+end;
80+
81+function RtObj(rt: PModule; const n: shortstring): PObj;
82+var o: PObj;
83+begin
84+ o := Find(rt^.scope, Intern(@n[1], length(n)));
85+ if o = nil then Fatal('Rt has no ' + n);
86+ RtObj := o;
87+end;
88+
89+var
90+ path, outPath, dir, s: shortstring;
91+ i, first, entry, start, fd: longint;
92+ m, rt: PModule;
93+ main: PObj;
94+ hasResult, dynamic, run: boolean;
95+
96+begin
97+ { constants fold as the machine computes: NaN and infinities, no traps }
98+ SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, exUnderflow, exPrecision]);
99+ path := '';
100+ outPath := '';
101+ numInc := 0;
102+ run := (ParamCount >= 1) and (ParamStr(1) = 'run');
103+ i := 1 + ord(run);
104+ while i <= ParamCount do begin
105+ s := ParamStr(i);
106+ if s = '-I' then begin
107+ inc(i);
108+ if numInc > High(incDirs) then Fatal('too many -I');
109+ incDirs[numInc] := ParamStr(i);
110+ inc(numInc);
111+ end else if s = '-o' then begin
112+ inc(i);
113+ outPath := ParamStr(i);
114+ end else if s = '--version' then begin
115+ writeln('raz ', Version, ', report ', Report);
116+ Halt(0);
117+ end else if (s <> '') and (s[1] = '-') then
118+ Fatal('unknown option ' + s)
119+ else begin
120+ path := s;
121+ first := i;
122+ if run then break; { the rest are the program's }
123+ end;
124+ inc(i);
125+ end;
126+ if path = '' then
127+ Fatal('usage: raz [-I dir]... [-o file] Main.raz, or raz run [-I dir]... Main.raz [arg]...');
128+ if run and (outPath <> '') then Fatal('raz run takes no -o');
129+ dir := ParamStr(0);
130+ i := length(dir);
131+ while (i > 0) and (dir[i] <> '/') do dec(i);
132+ if i = 0 then libDir := 'lib' else libDir := copy(dir, 1, i) + 'lib';
133+ if outPath = '' then begin
134+ outPath := path;
135+ if copy(outPath, length(outPath) - 3, 4) = '.raz' then
136+ outPath := copy(outPath, 1, length(outPath) - 4)
137+ else outPath := outPath + '.out';
138+ end;
139+
140+ m := CompileMain(path);
141+
142+ Use(m);
143+ rt := firstModule;
144+ while (rt <> nil) and (NameOf(rt^.name) <> 'Rt') do rt := rt^.next;
145+ if rt <> nil then Use(rt);
146+
147+ main := Find(m^.scope, Intern('main', 4));
148+ hasResult := false;
149+ if main <> nil then begin
150+ if (main^.cls <> oProc) or not main^.exported then Fatal('main must be an exported procedure');
151+ if (main^.typ^.len <> 0) or ((main^.typ^.base <> nil) and (main^.typ^.base <> tI64)) then
152+ Fatal('main must be proc main* or proc main*: I64');
153+ hasResult := main^.typ^.base <> nil;
154+ end;
155+
156+ if rt = nil then Fatal('can''t find module Rt');
157+ dynamic := UsesC;
158+ entry := NewChunk(secText, -1, Intern('_start', 6));
159+ if dynamic then begin
160+ { _start as C's crt1 does it: __libc_start_main(main, argc, argv,
161+ nil, nil, rtld_fini, stack_end), with rsp aligned }
162+ start := NewChunk(secText, -1, Intern('main', 4));
163+ BeginChunk(entry);
164+ MovRI(RBP, 0);
165+ MovRR(R9, RDX);
166+ Pop(RSI);
167+ MovRR(RDX, RSP);
168+ AluI(aluAnd, RSP, -16);
169+ Push(RAX);
170+ Push(RSP);
171+ MovRI(R8, 0);
172+ MovRI(RCX, 0);
173+ Lea(RDI, MemRip(start, 0));
174+ CallM(MemRip(ExternChunk(Intern('__libc_start_main', 17)), 0));
175+ Ud2;
176+ EndChunk(entry);
177+ BeginChunk(start);
178+ Push(RBP); { aligns the stack again }
179+ Store(MemRip(argcChunk, 0), RDI, 8);
180+ Store(MemRip(argvChunk, 0), RSI, 8);
181+ Load(RAX, MemRip(ExternChunk(Intern('exit', 4)), 0), 8, false);
182+ Store(MemRip(RtObj(rt, 'cExit')^.chunk, 0), RAX, 8);
183+ end else begin
184+ start := entry;
185+ BeginChunk(entry);
186+ Load(RAX, Mem(RSP, 0), 8, false);
187+ Store(MemRip(argcChunk, 0), RAX, 8);
188+ Lea(RAX, Mem(RSP, 8));
189+ Store(MemRip(argvChunk, 0), RAX, 8);
190+ end;
191+ m := firstModule;
192+ while m <> nil do begin
193+ if m^.used and (m^.body >= 0) then CallChunk(m^.body);
194+ m := m^.next;
195+ end;
196+ if main <> nil then CallChunk(main^.chunk);
197+ if hasResult then MovRR(RDI, RAX) else MovRI(RDI, 0);
198+ CallChunk(RtObj(rt, 'exit')^.chunk);
199+ Ud2;
200+ EndChunk(start);
201+
202+ mainPath := path;
203+ if run then begin
204+ { argv from Main.raz on is the program's, ending in nil as it must }
205+ fd := Do_SysCall(MemfdCreate, TSysParam(PChar('raz')), MfdCloexec);
206+ if fd < 0 then Fatal('can''t create a memfd');
207+ Str(fd, s);
208+ outPath := '/proc/self/fd/' + s + #0;
209+ WriteElf(outPath, entry);
210+ FpExecve(@outPath[1], @argv[first], envp);
211+ Fatal('can''t run ' + path);
212+ end;
213+ WriteElf(outPath, entry);
214+end.

src/scan.pas modified +2 -2

@@ -1,6 +1,6 @@
11 { scan.pas: the scanner.
22
3- Reads a jed source file and hands the parser one symbol at a time:
3+ Reads a raz source file and hands the parser one symbol at a time:
44 reserved words, identifiers, numbers, characters, strings and
55 operators. Identifiers are interned, so that the rest of the compiler
66 compares names as small integers. The scanner also reports errors,
@@ -191,7 +191,7 @@
191191
192192 procedure Fatal(const msg: shortstring);
193193 begin
194- writeln(StdErr, 'jed: ', msg);
194+ writeln(StdErr, 'raz: ', msg);
195195 Halt(1);
196196 end;
197197

test/check.sh (history) modified +38 -38

@@ -1,17 +1,17 @@
11 #!/bin/sh
22 # Compiles and runs every example and test, and compares what each
33 # prints, and its exit status, with what is expected:
4-# X.jed the program
4+# X.raz the program
55 # X.expect its standard output
66 # X.args its arguments, one per line (optional)
77 # X.status its exit status (optional; 0 if missing)
88 # A program without X.expect is compiled, not run. test/libc puts
9-# lib/Sys.jed, over the C library, before the system call one.
9+# lib/Sys.raz, over the C library, before the system call one.
1010 # Programs in test/err must not compile, and must print X.err. Then
11-# the version, tools/Doc.jed, the report's examples, tools/Pretty.jed,
11+# the version, tools/Doc.raz, the report's examples, tools/Pretty.raz,
1212 # and the library's own tests.
1313
14-jed=./jed
14+raz=./raz
1515 out=build/check
1616 mkdir -p $out
1717 pass=0
@@ -19,7 +19,7 @@
1919
2020 run() { # run dir name
2121 dir=$1; name=$2
22- if ! $jed -I $dir/mods -o $out/$name $dir/$name.jed 2>$out/$name.cerr; then
22+ if ! $raz -I $dir/mods -o $out/$name $dir/$name.raz 2>$out/$name.cerr; then
2323 echo "FAIL $dir/$name: doesn't compile: $(cat $out/$name.cerr)"
2424 fail=$((fail + 1)); return
2525 fi
@@ -44,24 +44,24 @@
4444 fi
4545 }
4646
47-for f in examples/*.jed test/run/*.jed test/libc/*.jed; do
48- run $(dirname $f) $(basename $f .jed)
47+for f in examples/*.raz test/run/*.raz test/libc/*.raz; do
48+ run $(dirname $f) $(basename $f .raz)
4949 done
5050
51-# jed run: a static program and one over C, from memory, with their
51+# raz run: a static program and one over C, from memory, with their
5252 # arguments, output and status passed through
5353 runs() { # runs file status [arg]...
5454 f=$1; want=$2; shift 2
55- $jed run -I $(dirname $f)/mods $f "$@" > $out/run.out 2>/dev/null
55+ $raz run -I $(dirname $f)/mods $f "$@" > $out/run.out 2>/dev/null
5656 status=$?
57- if cmp -s $out/run.out ${f%.jed}.expect && [ $status = $want ]; then pass=$((pass + 1))
58- else echo "FAIL jed run $f: status $status, not $want, or output differs"; fail=$((fail + 1)); fi
57+ if cmp -s $out/run.out ${f%.raz}.expect && [ $status = $want ]; then pass=$((pass + 1))
58+ else echo "FAIL raz run $f: status $status, not $want, or output differs"; fail=$((fail + 1)); fi
5959 }
60-runs test/run/Args.jed 4 one 'two words' é
61-runs test/libc/Through.jed 2
62-for f in test/err/*.jed; do
63- name=$(basename $f .jed)
64- if $jed -I test/err/mods -I test/run/mods -o $out/$name $f 2>$out/$name.cerr; then
60+runs test/run/Args.raz 4 one 'two words' é
61+runs test/libc/Through.raz 2
62+for f in test/err/*.raz; do
63+ name=$(basename $f .raz)
64+ if $raz -I test/err/mods -I test/run/mods -o $out/$name $f 2>$out/$name.cerr; then
6565 echo "FAIL $f: compiles"
6666 fail=$((fail + 1))
6767 elif ! grep -qF "$(cat test/err/$name.err)" $out/$name.cerr; then
@@ -72,19 +72,19 @@
7272 fi
7373 done
7474 # the report's version is the one the compiler says it follows
75-want=$(sed -n 's/^This is version \([0-9.-]*\) of the report.*/\1/p' doc/jed.md)
76-if ./jed --version | grep -qF "report $want"; then pass=$((pass + 1))
77-else echo "FAIL jed --version: not report $want"; fail=$((fail + 1)); fi
75+want=$(sed -n 's/^This is version \([0-9.-]*\) of the report.*/\1/p' doc/raz.md)
76+if ./raz --version | grep -qF "report $want"; then pass=$((pass + 1))
77+else echo "FAIL raz --version: not report $want"; fail=$((fail + 1)); fi
7878
79-# tools/Doc.jed: on every library module, and as test/doc expects
80-if ./jed -o $out/Doc tools/Doc.jed 2>$out/Doc.cerr; then
81- for f in lib/*.jed; do
79+# tools/Doc.raz: on every library module, and as test/doc expects
80+if ./raz -o $out/Doc tools/Doc.raz 2>$out/Doc.cerr; then
81+ for f in lib/*.raz; do
8282 if ! $out/Doc $f > $out/doc.out; then echo "FAIL Doc $f"; fail=$((fail + 1)); fi
8383 done
8484 for f in test/doc/*.expect; do
8585 name=$(basename $f .expect)
86- m=lib/$name.jed
87- [ -f $m ] || m=lib/$name.linux-x86_64.jed
86+ m=lib/$name.raz
87+ [ -f $m ] || m=lib/$name.linux-x86_64.raz
8888 if $out/Doc $m | cmp -s - $f; then pass=$((pass + 1))
8989 else echo "FAIL Doc $m: output differs"; fail=$((fail + 1)); fi
9090 done
@@ -92,42 +92,42 @@
9292 # the report's examples that are whole modules: each compiles, and
9393 # each with a main runs and ends with status 0
9494 rm -rf $out/report; mkdir -p $out/report
95- for name in $($out/Doc examples doc/jed.md $out/report); do
96- if ! $jed -o $out/report/$name $out/report/$name.jed 2>$out/report/$name.cerr; then
95+ for name in $($out/Doc examples doc/raz.md $out/report); do
96+ if ! $raz -o $out/report/$name $out/report/$name.raz 2>$out/report/$name.cerr; then
9797 echo "FAIL report example $name: $(cat $out/report/$name.cerr)"; fail=$((fail + 1))
98- elif grep -q '^proc main\*' $out/report/$name.jed && ! $out/report/$name > /dev/null 2>&1; then
98+ elif grep -q '^proc main\*' $out/report/$name.raz && ! $out/report/$name > /dev/null 2>&1; then
9999 echo "FAIL report example $name: status $?"; fail=$((fail + 1))
100100 else pass=$((pass + 1)); fi
101101 done
102102 else
103- echo "FAIL tools/Doc.jed: $(cat $out/Doc.cerr)"; fail=$((fail + 1))
103+ echo "FAIL tools/Doc.raz: $(cat $out/Doc.cerr)"; fail=$((fail + 1))
104104 fi
105105
106-# tools/Pretty.jed: each test/pretty/X.jed comes out as X.expect, which
106+# tools/Pretty.raz: each test/pretty/X.raz comes out as X.expect, which
107107 # comes out as it is; so do the library, the examples and the tools
108-if ./jed -o $out/Pretty tools/Pretty.jed 2>$out/Pretty.cerr; then
109- for f in test/pretty/*.jed; do
110- want=test/pretty/$(basename $f .jed).expect
108+if ./raz -o $out/Pretty tools/Pretty.raz 2>$out/Pretty.cerr; then
109+ for f in test/pretty/*.raz; do
110+ want=test/pretty/$(basename $f .raz).expect
111111 if $out/Pretty $f | cmp -s - $want && $out/Pretty $want | cmp -s - $want; then
112112 pass=$((pass + 1))
113113 else echo "FAIL Pretty $f: output differs"; fail=$((fail + 1)); fi
114114 done
115- for f in lib/*.jed examples/*.jed tools/*.jed; do
115+ for f in lib/*.raz examples/*.raz tools/*.raz; do
116116 if ! $out/Pretty $f | cmp -s - $f; then
117117 echo "FAIL Pretty $f: not formatted"; fail=$((fail + 1))
118118 fi
119119 done
120120 pass=$((pass + 1))
121121 else
122- echo "FAIL tools/Pretty.jed: $(cat $out/Pretty.cerr)"; fail=$((fail + 1))
122+ echo "FAIL tools/Pretty.raz: $(cat $out/Pretty.cerr)"; fail=$((fail + 1))
123123 fi
124124
125125 # each library module's main is its test; Sys over C is tested in test/libc
126-for f in lib/*.jed; do
127- [ $f = lib/Sys.jed ] && continue
126+for f in lib/*.raz; do
127+ [ $f = lib/Sys.raz ] && continue
128128 grep -q '^proc main\*' $f || continue
129- name=lib_$(basename $f .jed)
130- if ! $jed -o $out/$name $f 2>$out/$name.cerr; then
129+ name=lib_$(basename $f .raz)
130+ if ! $raz -o $out/$name $f 2>$out/$name.cerr; then
131131 echo "FAIL $f: doesn't compile: $(cat $out/$name.cerr)"; fail=$((fail + 1))
132132 elif ! $out/$name > $out/$name.out 2>&1; then
133133 echo "FAIL $f: its test says $(cat $out/$name.out)"; fail=$((fail + 1))

test/editors.sh (history) modified +9 -9

@@ -1,38 +1,38 @@
11 #!/bin/sh
22 # Loads the editor support, headless, on each example: the file must be
3-# taken for jed, coloured without error, and indented again exactly as
4-# it is written; and test/editors/Colours.jed must be coloured as
3+# taken for raz, coloured without error, and indented again exactly as
4+# it is written; and test/editors/Colours.raz must be coloured as
55 # Colours.expect says. Prints one line per failure; quiet if the editor
66 # is missing.
77
88 fail=0
99 if command -v vim >/dev/null; then
10- for f in examples/*.jed; do
10+ for f in examples/*.raz; do
1111 vim -Nu NONE -i NONE -es \
1212 -c 'set rtp^=editor/vim' -c 'filetype plugin indent on' -c 'syntax on' \
1313 -c "edit $f" \
14- -c 'if &filetype !=# "jed" || &shiftwidth != 4 | cquit | endif' \
14+ -c 'if &filetype !=# "raz" || &shiftwidth != 4 | cquit | endif' \
1515 -c 'let before = getline(1, "$")' -c 'normal! gg=G' \
1616 -c 'if getline(1, "$") != before | cquit | endif' -c 'qall!' \
1717 || { echo "FAIL vim on $f"; fail=1; }
1818 done
1919 vim -Nu NONE -i NONE -es -c 'set rtp^=editor/vim' -c 'filetype plugin indent on' \
20- -c 'syntax on' -c 'edit test/editors/Colours.jed' -S test/editors/colours.vim \
20+ -c 'syntax on' -c 'edit test/editors/Colours.raz' -S test/editors/colours.vim \
2121 || { echo "FAIL vim colours"; fail=1; }
2222 fi
2323 if command -v emacs >/dev/null; then
24- for f in examples/*.jed; do
25- emacs -Q --batch -l editor/emacs/jed-mode.el --eval "
24+ for f in examples/*.raz; do
25+ emacs -Q --batch -l editor/emacs/raz-mode.el --eval "
2626 (progn
2727 (find-file \"$f\")
28- (unless (eq major-mode 'jed-mode) (kill-emacs 1))
28+ (unless (eq major-mode 'raz-mode) (kill-emacs 1))
2929 (font-lock-ensure)
3030 (let ((before (buffer-string)))
3131 (indent-region (point-min) (point-max))
3232 (unless (string= before (buffer-string)) (kill-emacs 2))))" \
3333 2>/dev/null || { echo "FAIL emacs on $f"; fail=1; }
3434 done
35- emacs -Q --batch -l editor/emacs/jed-mode.el -l test/editors/colours.el 2>/dev/null \
35+ emacs -Q --batch -l editor/emacs/raz-mode.el -l test/editors/colours.el 2>/dev/null \
3636 || { echo "FAIL emacs colours"; fail=1; }
3737 fi
3838 exit $fail

test/editors/Colours.jed deleted +0 -7

@@ -1,7 +0,0 @@
1-(* outer (* nested *) still comment *)
2-module Colours;
3-const big = 0FFH; small = 2.5E-3; q = '\''; s = "a\"b";
4-var x: I64; ok: BOOL;
5-begin
6- INC(x); ok := true;
7-end Colours.

test/editors/Colours.raz (history) added +7 -0

@@ -0,0 +1,7 @@
1+(* outer (* nested *) still comment *)
2+module Colours;
3+const big = 0FFH; small = 2.5E-3; q = '\''; s = "a\"b";
4+var x: I64; ok: BOOL;
5+begin
6+ INC(x); ok := true;
7+end Colours.

test/editors/colours.el (history) modified +1 -1

@@ -3,7 +3,7 @@
33 (insert-file-contents "test/editors/Colours.expect")
44 (buffer-string))
55 "\n" t)))
6- (find-file "test/editors/Colours.jed")
6+ (find-file "test/editors/Colours.raz")
77 (font-lock-ensure)
88 (dolist (want wants)
99 (let* ((w (split-string want))

test/editors/colours.vim (history) modified +3 -3

@@ -1,7 +1,7 @@
11 " Checks each token of Colours.expect has the colour group it should.
2-let s:kinds = {'jedComment': 'comment', 'jedKeyword': 'keyword', 'jedNumber': 'number',
3- \ 'jedString': 'string', 'jedChar': 'string', 'jedType': 'type',
4- \ 'jedBuiltin': 'builtin', 'jedConstant': 'constant'}
2+let s:kinds = {'razComment': 'comment', 'razKeyword': 'keyword', 'razNumber': 'number',
3+ \ 'razString': 'string', 'razChar': 'string', 'razType': 'type',
4+ \ 'razBuiltin': 'builtin', 'razConstant': 'constant'}
55 for s:want in readfile('test/editors/Colours.expect')
66 let [s:l, s:c, s:k] = split(s:want)
77 let s:group = synIDattr(synID(str2nr(s:l), str2nr(s:c), 1), 'name')

test/err/Assign.jed deleted +0 -7

@@ -1,7 +0,0 @@
1-module Assign;
2-proc main*;
3-var a: I64; b: I32;
4-begin
5- a := b;
6-end;
7-end Assign.

test/err/Assign.raz added +7 -0

@@ -0,0 +1,7 @@
1+module Assign;
2+proc main*;
3+var a: I64; b: I32;
4+begin
5+ a := b;
6+end;
7+end Assign.

test/err/BadProc.jed deleted +0 -3

@@ -1,3 +0,0 @@
1-module BadProc;
2-import Str, M := Map([]U8, I64, Str.cmp, Str.eq);
3-end BadProc.

test/err/BadProc.raz added +3 -0

@@ -0,0 +1,3 @@
1+module BadProc;
2+import Str, M := Map([]U8, I64, Str.cmp, Str.eq);
3+end BadProc.

test/err/BigI64.jed deleted +0 -7

@@ -1,7 +0,0 @@
1-module BigI64;
2-proc main*;
3-var i: I64;
4-begin
5- i := 0FFFFFFFFFFFFFFFFH;
6-end;
7-end BigI64.

test/err/BigI64.raz added +7 -0

@@ -0,0 +1,7 @@
1+module BigI64;
2+proc main*;
3+var i: I64;
4+begin
5+ i := 0FFFFFFFFFFFFFFFFH;
6+end;
7+end BigI64.

test/err/Break.jed deleted +0 -6

@@ -1,6 +0,0 @@
1-module Break;
2-proc main*;
3-begin
4- break;
5-end;
6-end Break.

test/err/Break.raz added +6 -0

@@ -0,0 +1,6 @@
1+module Break;
2+proc main*;
3+begin
4+ break;
5+end;
6+end Break.

test/err/Cycle.jed deleted +0 -3

@@ -1,3 +0,0 @@
1-module Cycle;
2-import CycleB;
3-end Cycle.

test/err/Cycle.raz added +3 -0

@@ -0,0 +1,3 @@
1+module Cycle;
2+import CycleB;
3+end Cycle.

test/err/DeferBreak.jed deleted +0 -8

@@ -1,8 +0,0 @@
1-module DeferBreak;
2-proc f;
3-begin
4- while true do
5- defer break;
6- end;
7-end;
8-end DeferBreak.

test/err/DeferBreak.raz added +8 -0

@@ -0,0 +1,8 @@
1+module DeferBreak;
2+proc f;
3+begin
4+ while true do
5+ defer break;
6+ end;
7+end;
8+end DeferBreak.

test/err/DeferDefer.jed deleted +0 -6

@@ -1,6 +0,0 @@
1-module DeferDefer;
2-proc f;
3-begin
4- defer defer f;
5-end;
6-end DeferDefer.

test/err/DeferDefer.raz added +6 -0

@@ -0,0 +1,6 @@
1+module DeferDefer;
2+proc f;
3+begin
4+ defer defer f;
5+end;
6+end DeferDefer.

test/err/DeferReturn.jed deleted +0 -7

@@ -1,7 +0,0 @@
1-module DeferReturn;
2-proc f: I64;
3-begin
4- defer return 1;
5- return 0;
6-end;
7-end DeferReturn.

test/err/DeferReturn.raz added +7 -0

@@ -0,0 +1,7 @@
1+module DeferReturn;
2+proc f: I64;
3+begin
4+ defer return 1;
5+ return 0;
6+end;
7+end DeferReturn.

test/err/ErrOrder.jed deleted +0 -7

@@ -1,7 +0,0 @@
1-module ErrOrder;
2-const A: ERROR = "a"; B: ERROR = "b";
3-proc main*;
4-begin
5- if A < B then end;
6-end;
7-end ErrOrder.

test/err/ErrOrder.raz added +7 -0

@@ -0,0 +1,7 @@
1+module ErrOrder;
2+const A: ERROR = "a"; B: ERROR = "b";
3+proc main*;
4+begin
5+ if A < B then end;
6+end;
7+end ErrOrder.

test/err/ExternRec.jed deleted +0 -7

@@ -1,7 +0,0 @@
1-module ExternRec;
2-
3-type R = record a, b: I64; end;
4-
5-extern proc f(r: R);
6-
7-end ExternRec.

test/err/ExternRec.raz (history) added +7 -0

@@ -0,0 +1,7 @@
1+module ExternRec;
2+
3+type R = record a, b: I64; end;
4+
5+extern proc f(r: R);
6+
7+end ExternRec.

test/err/F32Dots.jed deleted +0 -11

@@ -1,11 +0,0 @@
1-module F32Dots;
2-import C;
3-
4-proc main*;
5-var x: F32;
6-begin
7- x := 1.5;
8- C.printf("%f\n", x);
9-end;
10-
11-end F32Dots.

test/err/F32Dots.raz (history) added +11 -0

@@ -0,0 +1,11 @@
1+module F32Dots;
2+import C;
3+
4+proc main*;
5+var x: F32;
6+begin
7+ x := 1.5;
8+ C.printf("%f\n", x);
9+end;
10+
11+end F32Dots.

test/err/Field.jed deleted +0 -8

@@ -1,8 +0,0 @@
1-module Field;
2-import Plat;
3-proc main*;
4-var i: Plat.Info;
5-begin
6- i.extra := 1;
7-end;
8-end Field.

test/err/Field.raz (history) added +8 -0

@@ -0,0 +1,8 @@
1+module Field;
2+import Plat;
3+proc main*;
4+var i: Plat.Info;
5+begin
6+ i.extra := 1;
7+end;
8+end Field.

test/err/Match.jed deleted +0 -11

@@ -1,11 +0,0 @@
1-module Match;
2-type S = variant a; b; c; end;
3-proc main*;
4-var s: S;
5-begin
6- match s of
7- | a: s := b;
8- | b:
9- end;
10-end;
11-end Match.

test/err/Match.raz added +11 -0

@@ -0,0 +1,11 @@
1+module Match;
2+type S = variant a; b; c; end;
3+proc main*;
4+var s: S;
5+begin
6+ match s of
7+ | a: s := b;
8+ | b:
9+ end;
10+end;
11+end Match.

test/err/Mixed.jed deleted +0 -9

@@ -1,9 +0,0 @@
1-module Mixed;
2-
3-proc main*;
4-var x: F32; y: F64;
5-begin
6- y := x + y;
7-end;
8-
9-end Mixed.

test/err/Mixed.raz added +9 -0

@@ -0,0 +1,9 @@
1+module Mixed;
2+
3+proc main*;
4+var x: F32; y: F64;
5+begin
6+ y := x + y;
7+end;
8+
9+end Mixed.

test/err/NegU64.jed deleted +0 -7

@@ -1,7 +0,0 @@
1-module NegU64;
2-proc main*;
3-var u: U64;
4-begin
5- u := -1;
6-end;
7-end NegU64.

test/err/NegU64.raz added +7 -0

@@ -0,0 +1,7 @@
1+module NegU64;
2+proc main*;
3+var u: U64;
4+begin
5+ u := -1;
6+end;
7+end NegU64.

test/err/NoArgs.jed deleted +0 -3

@@ -1,3 +0,0 @@
1-module NoArgs;
2-import List;
3-end NoArgs.

test/err/NoArgs.raz added +3 -0

@@ -0,0 +1,3 @@
1+module NoArgs;
2+import List;
3+end NoArgs.

test/err/NotGeneric.jed deleted +0 -3

@@ -1,3 +0,0 @@
1-module NotGeneric;
2-import S := Str(I64);
3-end NotGeneric.

test/err/NotGeneric.raz added +3 -0

@@ -0,0 +1,3 @@
1+module NotGeneric;
2+import S := Str(I64);
3+end NotGeneric.

test/err/PtrArray.jed deleted +0 -8

@@ -1,8 +0,0 @@
1-module PtrArray;
2-proc main*;
3-var a: [4]I64; p: ^[4]I64;
4-begin
5- p := ADR(a);
6- p[1] := 0;
7-end;
8-end PtrArray.

test/err/PtrArray.raz added +8 -0

@@ -0,0 +1,8 @@
1+module PtrArray;
2+proc main*;
3+var a: [4]I64; p: ^[4]I64;
4+begin
5+ p := ADR(a);
6+ p[1] := 0;
7+end;
8+end PtrArray.

test/err/Static.jed deleted +0 -9

@@ -1,9 +0,0 @@
1-module Static;
2-import Bare, C;
3-
4-proc main*;
5-begin
6- C.printf("%d\n", Bare.f());
7-end;
8-
9-end Static.

test/err/Static.raz (history) added +9 -0

@@ -0,0 +1,9 @@
1+module Static;
2+import Bare, C;
3+
4+proc main*;
5+begin
6+ C.printf("%d\n", Bare.f());
7+end;
8+
9+end Static.

test/err/ThreadC.jed deleted +0 -8

@@ -1,8 +0,0 @@
1-module ThreadC;
2-import Thread, C;
3-
4-proc main*;
5-begin
6-end;
7-
8-end ThreadC.

test/err/ThreadC.raz added +8 -0

@@ -0,0 +1,8 @@
1+module ThreadC;
2+import Thread, C;
3+
4+proc main*;
5+begin
6+end;
7+
8+end ThreadC.

test/err/Tuple.jed deleted +0 -8

@@ -1,8 +0,0 @@
1-module Tuple;
2-proc two: (I64, I64); begin return 1, 2; end;
3-proc main*;
4-var a: I64;
5-begin
6- a := two() + 1;
7-end;
8-end Tuple.

test/err/Tuple.raz added +8 -0

@@ -0,0 +1,8 @@
1+module Tuple;
2+proc two: (I64, I64); begin return 1, 2; end;
3+proc main*;
4+var a: I64;
5+begin
6+ a := two() + 1;
7+end;
8+end Tuple.

test/err/TwoTypes.jed deleted +0 -8

@@ -1,8 +0,0 @@
1-module TwoTypes;
2-import A := List(I64), B := List(I32);
3-proc main*;
4-var a: A.List; b: B.List;
5-begin
6- a := b;
7-end;
8-end TwoTypes.

test/err/TwoTypes.raz added +8 -0

@@ -0,0 +1,8 @@
1+module TwoTypes;
2+import A := List(I64), B := List(I32);
3+proc main*;
4+var a: A.List; b: B.List;
5+begin
6+ a := b;
7+end;
8+end TwoTypes.

test/err/UsesExtra.jed deleted +0 -3

@@ -1,3 +0,0 @@
1-module UsesExtra;
2-import Extra;
3-end UsesExtra.

test/err/UsesExtra.raz (history) added +3 -0

@@ -0,0 +1,3 @@
1+module UsesExtra;
2+import Extra;
3+end UsesExtra.

test/err/UsesIface.jed deleted +0 -3

@@ -1,3 +0,0 @@
1-module UsesIface;
2-import Iface;
3-end UsesIface.

test/err/UsesIface.raz (history) added +3 -0

@@ -0,0 +1,3 @@
1+module UsesIface;
2+import Iface;
3+end UsesIface.

test/err/UsesRec.jed deleted +0 -3

@@ -1,3 +0,0 @@
1-module UsesRec;
2-import Rec;
3-end UsesRec.

test/err/UsesRec.raz (history) added +3 -0

@@ -0,0 +1,3 @@
1+module UsesRec;
2+import Rec;
3+end UsesRec.

test/err/Utf.err modified +1 -1

@@ -1 +1 @@
1-Utf.jed:2:5: text outside strings, characters and comments must be ASCII
1+Utf.raz:2:5: text outside strings, characters and comments must be ASCII

test/err/Utf.jed deleted +0 -3

@@ -1,3 +0,0 @@
1-module Utf;
2-var é: I64;
3-end Utf.

test/err/Utf.raz added +3 -0

@@ -0,0 +1,3 @@
1+module Utf;
2+var é: I64;
3+end Utf.

test/err/Variadic.jed deleted +0 -7

@@ -1,7 +0,0 @@
1-module Variadic;
2-
3-proc f(a: I64; ...);
4-begin
5-end;
6-
7-end Variadic.

test/err/Variadic.raz (history) added +7 -0

@@ -0,0 +1,7 @@
1+module Variadic;
2+
3+proc f(a: I64; ...);
4+begin
5+end;
6+
7+end Variadic.

test/err/Volatile.jed deleted +0 -8

@@ -1,8 +0,0 @@
1-module Volatile;
2-proc main*;
3-var x: I64; p: ^VOLATILE I64; q: ^I64;
4-begin
5- p := ADR(x);
6- q := p;
7-end;
8-end Volatile.

test/err/Volatile.raz added +8 -0

@@ -0,0 +1,8 @@
1+module Volatile;
2+proc main*;
3+var x: I64; p: ^VOLATILE I64; q: ^I64;
4+begin
5+ p := ADR(x);
6+ q := p;
7+end;
8+end Volatile.

test/err/mods/Bare.jed deleted +0 -10

@@ -1,10 +0,0 @@
1-(* A module that needs a program without C. *)
2-module Bare;
3-link static;
4-
5-proc f*: I64;
6-begin
7- return 1;
8-end;
9-
10-end Bare.

test/err/mods/Bare.raz (history) added +10 -0

@@ -0,0 +1,10 @@
1+(* A module that needs a program without C. *)
2+module Bare;
3+link static;
4+
5+proc f*: I64;
6+begin
7+ return 1;
8+end;
9+
10+end Bare.

test/err/mods/Cycle.jed deleted +0 -3

@@ -1,3 +0,0 @@
1-module Cycle;
2-import CycleB;
3-end Cycle.

test/err/mods/Cycle.raz added +3 -0

@@ -0,0 +1,3 @@
1+module Cycle;
2+import CycleB;
3+end Cycle.

test/err/mods/CycleB.jed deleted +0 -3

@@ -1,3 +0,0 @@
1-module CycleB;
2-import Cycle;
3-end CycleB.

test/err/mods/CycleB.raz added +3 -0

@@ -0,0 +1,3 @@
1+module CycleB;
2+import Cycle;
3+end CycleB.

test/err/mods/Extra.jed deleted +0 -4

@@ -1,4 +0,0 @@
1-module Extra;
2-type R* = record a*: I64; secret: [4]I64; end;
3-const more* = 1;
4-end Extra.

test/err/mods/Extra.linux.jed deleted +0 -3

@@ -1,3 +0,0 @@
1-module Extra;
2-type R* = record a*: I64; hidden: U8; end;
3-end Extra.

test/err/mods/Extra.linux.raz (history) added +3 -0

@@ -0,0 +1,3 @@
1+module Extra;
2+type R* = record a*: I64; hidden: U8; end;
3+end Extra.

test/err/mods/Extra.raz (history) added +4 -0

@@ -0,0 +1,4 @@
1+module Extra;
2+type R* = record a*: I64; secret: [4]I64; end;
3+const more* = 1;
4+end Extra.

test/err/mods/Iface.jed deleted +0 -3

@@ -1,3 +0,0 @@
1-module Iface;
2-proc f*(x: I32): I64; begin return 0; end;
3-end Iface.

test/err/mods/Iface.linux-x86_64.jed deleted +0 -3

@@ -1,3 +0,0 @@
1-module Iface;
2-proc f*(x: I64): I64; begin return x; end;
3-end Iface.

test/err/mods/Iface.linux-x86_64.raz (history) added +3 -0

@@ -0,0 +1,3 @@
1+module Iface;
2+proc f*(x: I64): I64; begin return x; end;
3+end Iface.

test/err/mods/Iface.raz (history) added +3 -0

@@ -0,0 +1,3 @@
1+module Iface;
2+proc f*(x: I32): I64; begin return 0; end;
3+end Iface.

test/err/mods/Rec.jed deleted +0 -4

@@ -1,4 +0,0 @@
1-module Rec;
2-type R* = record a*: I32; end;
3-proc f*(r: ^R); begin end;
4-end Rec.

test/err/mods/Rec.linux-x86_64.jed deleted +0 -4

@@ -1,4 +0,0 @@
1-module Rec;
2-type R* = record a*: I64; b: I64; end;
3-proc f*(r: ^R); begin end;
4-end Rec.

test/err/mods/Rec.linux-x86_64.raz (history) added +4 -0

@@ -0,0 +1,4 @@
1+module Rec;
2+type R* = record a*: I64; b: I64; end;
3+proc f*(r: ^R); begin end;
4+end Rec.

test/err/mods/Rec.raz (history) added +4 -0

@@ -0,0 +1,4 @@
1+module Rec;
2+type R* = record a*: I32; end;
3+proc f*(r: ^R); begin end;
4+end Rec.

test/gdb.sh (history) modified +5 -5

@@ -4,11 +4,11 @@
44 # caller.
55 out=build/check
66 mkdir -p $out
7-./jed -I test/run/mods -o $out/Procs test/run/Procs.jed || exit 1
8-gdb -batch -ex 'break test/run/Procs.jed:13' -ex run -ex bt $out/Procs > $out/gdb.out 2>&1
9-for want in 'Breakpoint 1, Procs.odd () at test/run/Procs.jed:13' \
10- 'in Procs.even () at test/run/Procs.jed:20' \
11- 'in Procs.main () at test/run/Procs.jed:'; do
7+./raz -I test/run/mods -o $out/Procs test/run/Procs.raz || exit 1
8+gdb -batch -ex 'break test/run/Procs.raz:13' -ex run -ex bt $out/Procs > $out/gdb.out 2>&1
9+for want in 'Breakpoint 1, Procs.odd () at test/run/Procs.raz:13' \
10+ 'in Procs.even () at test/run/Procs.raz:20' \
11+ 'in Procs.main () at test/run/Procs.raz:'; do
1212 if ! grep -qF "$want" $out/gdb.out; then
1313 echo "FAIL gdb: no \"$want\""; cat $out/gdb.out; exit 1
1414 fi

test/genbench.py modified +1 -1

@@ -1,4 +1,4 @@
1-"""Writes a large jed program to standard output, for timing the
1+"""Writes a large raz program to standard output, for timing the
22 compiler: n procedures of loops, conditions, records, slices and calls,
33 each calling the one before, so that none is left out."""
44 import sys

test/libc/SysTest.jed deleted +0 -10

@@ -1,10 +0,0 @@
1-(* Sys over the C library, through its own test. *)
2-module SysTest;
3-import Sys;
4-
5-proc main*;
6-begin
7- Sys.main;
8-end;
9-
10-end SysTest.

test/libc/SysTest.raz (history) added +10 -0

@@ -0,0 +1,10 @@
1+(* Sys over the C library, through its own test. *)
2+module SysTest;
3+import Sys;
4+
5+proc main*;
6+begin
7+ Sys.main;
8+end;
9+
10+end SysTest.

test/libc/Through.jed deleted +0 -33

@@ -1,33 +0,0 @@
1-(* The library over C's Sys, lib/Sys.jed, which this directory puts
2- first: output, memory from the heap, and a failed check that still
3- writes out what Out holds. *)
4-module Through;
5-import Out, Heap, Mem;
6-
7-type Node = record next: ^Node; n: I64; end;
8-
9-proc main*;
10-var p, list: ^Node; i, sum: I64; a: [3]I64;
11-begin
12- Out.str("through C\n");
13- list := nil;
14- for i := 1 to 1000 do
15- NEW(p, Heap.heap);
16- p^.n := i;
17- p^.next := list;
18- list := p;
19- end;
20- sum := 0;
21- while list # nil do
22- sum := sum + list^.n;
23- p := list;
24- list := list^.next;
25- Mem.free(Heap.heap, ^U8(p));
26- end;
27- Out.int(sum); Out.ln;
28- i := 3;
29- a[i] := 1;
30- Out.str("not reached\n");
31-end;
32-
33-end Through.

test/libc/Through.raz (history) added +33 -0

@@ -0,0 +1,33 @@
1+(* The library over C's Sys, lib/Sys.raz, which this directory puts
2+ first: output, memory from the heap, and a failed check that still
3+ writes out what Out holds. *)
4+module Through;
5+import Out, Heap, Mem;
6+
7+type Node = record next: ^Node; n: I64; end;
8+
9+proc main*;
10+var p, list: ^Node; i, sum: I64; a: [3]I64;
11+begin
12+ Out.str("through C\n");
13+ list := nil;
14+ for i := 1 to 1000 do
15+ NEW(p, Heap.heap);
16+ p^.n := i;
17+ p^.next := list;
18+ list := p;
19+ end;
20+ sum := 0;
21+ while list # nil do
22+ sum := sum + list^.n;
23+ p := list;
24+ list := list^.next;
25+ Mem.free(Heap.heap, ^U8(p));
26+ end;
27+ Out.int(sum); Out.ln;
28+ i := 3;
29+ a[i] := 1;
30+ Out.str("not reached\n");
31+end;
32+
33+end Through.

test/libc/mods/Sys.jed deleted +0 -1

@@ -1 +0,0 @@
1-../../../lib/Sys.jed
\ No newline at end of file

test/libc/mods/Sys.raz (history) added (symbolic link) +1 -0

@@ -0,0 +1 @@
1+../../../lib/Sys.raz
\ No newline at end of file

test/pretty/Messy.jed deleted +0 -57

@@ -1,57 +0,0 @@
1-(* A module laid out badly. *)
2- module Messy;
3-import Out,Rt;
4-
5-const
6-max* =10;
7- min=-1;
8-
9-type
10- Pair* = record
11- a*,b: I64; (* two numbers *)
12- end;
13- Shape = variant
14- circle(r: I64);
15- dot;
16- end;
17-
18- (* the bigger *)
19- proc max2*(a,b:I64):I64;
20-var m : I64;
21- begin
22-if a>b then m:=a;
23- elsif a=b then
24- m :=a ;
25- else
26- m:= b;end;
27- return m;
28- end;
29-
30-proc area(s: Shape): I64;
31-begin
32-match s of
33- | circle(r): return 3*r*r;
34-| dot:
35- return 0;
36- end;
37-end;
38-
39-proc main*;
40-var i,s:I64; p: Pair;
41-begin
42- s:=0;
43- for i:=-3 to max-1 do s:=s+i*2- -1;end;
44- repeat
45- s := s-1 ;
46- until s<0;
47- if (s # -1) or (max2(3,4) # 4)
48- or (area({dot}) # 0) then Rt.stop("Messy"); end;
49- p := {a: -s, b:2};
50- Out.int(p.a); (* the first *)
51- Out.ln;
52- (* and done:
53- a comment that moves
54- with its line *)
55-end;
56-
57-end Messy.

test/pretty/Messy.raz (history) added +57 -0

@@ -0,0 +1,57 @@
1+(* A module laid out badly. *)
2+ module Messy;
3+import Out,Rt;
4+
5+const
6+max* =10;
7+ min=-1;
8+
9+type
10+ Pair* = record
11+ a*,b: I64; (* two numbers *)
12+ end;
13+ Shape = variant
14+ circle(r: I64);
15+ dot;
16+ end;
17+
18+ (* the bigger *)
19+ proc max2*(a,b:I64):I64;
20+var m : I64;
21+ begin
22+if a>b then m:=a;
23+ elsif a=b then
24+ m :=a ;
25+ else
26+ m:= b;end;
27+ return m;
28+ end;
29+
30+proc area(s: Shape): I64;
31+begin
32+match s of
33+ | circle(r): return 3*r*r;
34+| dot:
35+ return 0;
36+ end;
37+end;
38+
39+proc main*;
40+var i,s:I64; p: Pair;
41+begin
42+ s:=0;
43+ for i:=-3 to max-1 do s:=s+i*2- -1;end;
44+ repeat
45+ s := s-1 ;
46+ until s<0;
47+ if (s # -1) or (max2(3,4) # 4)
48+ or (area({dot}) # 0) then Rt.stop("Messy"); end;
49+ p := {a: -s, b:2};
50+ Out.int(p.a); (* the first *)
51+ Out.ln;
52+ (* and done:
53+ a comment that moves
54+ with its line *)
55+end;
56+
57+end Messy.

test/run/Alloc.jed deleted +0 -66

@@ -1,66 +0,0 @@
1-module Alloc;
2-import Out, Mem, Arena, Heap;
3-
4-type
5- Node = record next: ^Node; val: I64; pad: [5]I64; end;
6- Big = record data: [1000]I64; end;
7-
8-proc build(a: ^Mem.Allocator; n: I64): ^Node;
9-var head, p: ^Node; i: I64;
10-begin
11- head := nil;
12- for i := 1 to n do
13- NEW(p, a);
14- if p = nil then return nil; end;
15- if p^.val # 0 then Out.str("not zeroed "); end;
16- p^.val := i;
17- p^.pad[4] := i;
18- p^.next := head;
19- head := p;
20- end;
21- return head;
22-end;
23-
24-proc sum(p: ^Node): I64;
25-var s: I64;
26-begin
27- s := 0;
28- while p # nil do s := s + p^.val + p^.pad[4]; p := p^.next; end;
29- return s;
30-end;
31-
32-proc release(a: ^Mem.Allocator; p: ^Node);
33-var next: ^Node;
34-begin
35- while p # nil do
36- next := p^.next;
37- Mem.free(a, ^U8(p));
38- p := next;
39- end;
40-end;
41-
42-proc main*;
43-var ar: Arena.Arena; l, m: ^Node; b: ^Big; i: I64; small: ^U8; again: ^Node;
44-begin
45- l := build(Heap.heap, 1000);
46- Out.int(sum(l)); Out.ln;
47- release(Heap.heap, l);
48- m := build(Heap.heap, 1000);
49- Out.int(sum(m)); Out.ln;
50- NEW(b, Heap.heap);
51- b^.data[999] := 7;
52- Out.int(b^.data[999] + b^.data[0]); Out.ln;
53- Mem.free(Heap.heap, ^U8(b));
54- if not Arena.init(ADR(ar), 8192) then Out.str("no arena"); end;
55- l := build(ADR(ar.base), 100);
56- Out.int(sum(l)); Out.ln;
57- l := build(ADR(ar.base), 1000);
58- if l = nil then Out.str("nil "); end;
59- Arena.reset(ADR(ar));
60- NEW(again, ADR(ar.base));
61- if again # nil then Out.str("again "); Out.int(again^.val); end;
62- Out.ln;
63- Arena.done(ADR(ar));
64-end;
65-
66-end Alloc.

test/run/Alloc.raz (history) added +66 -0

@@ -0,0 +1,66 @@
1+module Alloc;
2+import Out, Mem, Arena, Heap;
3+
4+type
5+ Node = record next: ^Node; val: I64; pad: [5]I64; end;
6+ Big = record data: [1000]I64; end;
7+
8+proc build(a: ^Mem.Allocator; n: I64): ^Node;
9+var head, p: ^Node; i: I64;
10+begin
11+ head := nil;
12+ for i := 1 to n do
13+ NEW(p, a);
14+ if p = nil then return nil; end;
15+ if p^.val # 0 then Out.str("not zeroed "); end;
16+ p^.val := i;
17+ p^.pad[4] := i;
18+ p^.next := head;
19+ head := p;
20+ end;
21+ return head;
22+end;
23+
24+proc sum(p: ^Node): I64;
25+var s: I64;
26+begin
27+ s := 0;
28+ while p # nil do s := s + p^.val + p^.pad[4]; p := p^.next; end;
29+ return s;
30+end;
31+
32+proc release(a: ^Mem.Allocator; p: ^Node);
33+var next: ^Node;
34+begin
35+ while p # nil do
36+ next := p^.next;
37+ Mem.free(a, ^U8(p));
38+ p := next;
39+ end;
40+end;
41+
42+proc main*;
43+var ar: Arena.Arena; l, m: ^Node; b: ^Big; i: I64; small: ^U8; again: ^Node;
44+begin
45+ l := build(Heap.heap, 1000);
46+ Out.int(sum(l)); Out.ln;
47+ release(Heap.heap, l);
48+ m := build(Heap.heap, 1000);
49+ Out.int(sum(m)); Out.ln;
50+ NEW(b, Heap.heap);
51+ b^.data[999] := 7;
52+ Out.int(b^.data[999] + b^.data[0]); Out.ln;
53+ Mem.free(Heap.heap, ^U8(b));
54+ if not Arena.init(ADR(ar), 8192) then Out.str("no arena"); end;
55+ l := build(ADR(ar.base), 100);
56+ Out.int(sum(l)); Out.ln;
57+ l := build(ADR(ar.base), 1000);
58+ if l = nil then Out.str("nil "); end;
59+ Arena.reset(ADR(ar));
60+ NEW(again, ADR(ar.base));
61+ if again # nil then Out.str("again "); Out.int(again^.val); end;
62+ Out.ln;
63+ Arena.done(ADR(ar));
64+end;
65+
66+end Alloc.

test/run/Args.jed deleted +0 -18

@@ -1,18 +0,0 @@
1-module Args;
2-import Out;
3-
4-proc main*: I64;
5-var i, n: I64; a: ^^U8; s: ^U8;
6-begin
7- a := ARGV();
8- for i := 1 to ARGC() - 1 do
9- s := a[i];
10- n := 0;
11- while s[n] # 0 do n := n + 1; end;
12- Out.str(s[0..n]);
13- Out.ln;
14- end;
15- return ARGC();
16-end;
17-
18-end Args.

test/run/Args.raz added +18 -0

@@ -0,0 +1,18 @@
1+module Args;
2+import Out;
3+
4+proc main*: I64;
5+var i, n: I64; a: ^^U8; s: ^U8;
6+begin
7+ a := ARGV();
8+ for i := 1 to ARGC() - 1 do
9+ s := a[i];
10+ n := 0;
11+ while s[n] # 0 do n := n + 1; end;
12+ Out.str(s[0..n]);
13+ Out.ln;
14+ end;
15+ return ARGC();
16+end;
17+
18+end Args.

test/run/Arith.jed deleted +0 -74

@@ -1,74 +0,0 @@
1-module Arith;
2-import Out;
3-
4-const
5- K = 10;
6- M = K * 3 + 2;
7- Big = 0FFFFFFFFFFFFFFFFH;
8-
9-var g: I64;
10-
11-proc show(s: []U8; n: I64);
12-begin
13- Out.str(s); Out.str(" "); Out.int(n); Out.ln;
14-end;
15-
16-proc showb(s: []U8; t: BOOL);
17-begin
18- if t then show(s, 1); else show(s, 0); end;
19-end;
20-
21-proc main*;
22-var a, b: I64; u: U8; i8: I8; w: U32; x: U64; r: F64; t: BOOL;
23-begin
24- show("M", M);
25- a := 17; b := 5;
26- show("add", a + b);
27- show("sub", a - b);
28- show("mul", a * b);
29- show("div", -7 div 2);
30- show("mod", -7 mod 2);
31- show("divv", (0 - a) div b);
32- show("modv", (0 - a) mod b);
33- show("prec", 2 + 3 * 4);
34- show("neg", -a * b);
35- u := 200;
36- u := u + 100;
37- show("u8wrap", I64(u));
38- i8 := 127;
39- i8 := i8 + 1;
40- show("i8wrap", I64(i8));
41- w := 0FFFFFFFFH;
42- w := w + 2;
43- show("u32wrap", I64(w));
44- x := Big;
45- showb("u64>i", x > 5);
46- showb("i64<", -1 < 5);
47- show("shl", 1 shl 10);
48- show("shr", -16 shr 2);
49- show("ushr", I64(U64(-16) shr 60));
50- show("and", 12 and 10);
51- show("or", 12 or 3);
52- show("xor", 12 xor 10);
53- show("not", not 0);
54- r := F64(a) / 2.0;
55- show("real", I64(r * 10.0));
56- r := -2.75;
57- show("trunc", I64(r));
58- showb("nan", 0.0 / 0.0 = 0.0 / 0.0);
59- showb("rlt", 1.5 < 2.5);
60- show("u64real", I64(F64(x) / 1.0E18));
61- t := (a > 3) and (b < 3);
62- if not t then show("bool", 1); end;
63- t := (a > 3) or (g div 0 = 1);
64- if t then show("shortcut", 1); end;
65- g := 42;
66- show("global", g);
67- show("char", 'A');
68- show("utf8", 'é');
69- show("hexconst", 0FFH);
70- show("cut", I64(U8(300)));
71- show("sext", I64(I8(U8(255))));
72-end;
73-
74-end Arith.

test/run/Arith.raz added +74 -0

@@ -0,0 +1,74 @@
1+module Arith;
2+import Out;
3+
4+const
5+ K = 10;
6+ M = K * 3 + 2;
7+ Big = 0FFFFFFFFFFFFFFFFH;
8+
9+var g: I64;
10+
11+proc show(s: []U8; n: I64);
12+begin
13+ Out.str(s); Out.str(" "); Out.int(n); Out.ln;
14+end;
15+
16+proc showb(s: []U8; t: BOOL);
17+begin
18+ if t then show(s, 1); else show(s, 0); end;
19+end;
20+
21+proc main*;
22+var a, b: I64; u: U8; i8: I8; w: U32; x: U64; r: F64; t: BOOL;
23+begin
24+ show("M", M);
25+ a := 17; b := 5;
26+ show("add", a + b);
27+ show("sub", a - b);
28+ show("mul", a * b);
29+ show("div", -7 div 2);
30+ show("mod", -7 mod 2);
31+ show("divv", (0 - a) div b);
32+ show("modv", (0 - a) mod b);
33+ show("prec", 2 + 3 * 4);
34+ show("neg", -a * b);
35+ u := 200;
36+ u := u + 100;
37+ show("u8wrap", I64(u));
38+ i8 := 127;
39+ i8 := i8 + 1;
40+ show("i8wrap", I64(i8));
41+ w := 0FFFFFFFFH;
42+ w := w + 2;
43+ show("u32wrap", I64(w));
44+ x := Big;
45+ showb("u64>i", x > 5);
46+ showb("i64<", -1 < 5);
47+ show("shl", 1 shl 10);
48+ show("shr", -16 shr 2);
49+ show("ushr", I64(U64(-16) shr 60));
50+ show("and", 12 and 10);
51+ show("or", 12 or 3);
52+ show("xor", 12 xor 10);
53+ show("not", not 0);
54+ r := F64(a) / 2.0;
55+ show("real", I64(r * 10.0));
56+ r := -2.75;
57+ show("trunc", I64(r));
58+ showb("nan", 0.0 / 0.0 = 0.0 / 0.0);
59+ showb("rlt", 1.5 < 2.5);
60+ show("u64real", I64(F64(x) / 1.0E18));
61+ t := (a > 3) and (b < 3);
62+ if not t then show("bool", 1); end;
63+ t := (a > 3) or (g div 0 = 1);
64+ if t then show("shortcut", 1); end;
65+ g := 42;
66+ show("global", g);
67+ show("char", 'A');
68+ show("utf8", 'é');
69+ show("hexconst", 0FFH);
70+ show("cut", I64(U8(300)));
71+ show("sext", I64(I8(U8(255))));
72+end;
73+
74+end Arith.

test/run/AtExit.jed deleted +0 -41

@@ -1,41 +0,0 @@
1-(* Rt.exit runs what Rt.atExit registered, the last first, each once,
2- then ends the program with main's status. *)
3-module AtExit;
4-import Out, Rt;
5-
6-proc first;
7-begin
8- Out.str("first\n");
9-end;
10-
11-proc second;
12-begin
13- Out.str("second, which exits again\n");
14- Rt.exit(5); (* the rest still run, once each; the status is now 5 *)
15-end;
16-
17-proc third;
18-begin
19- Out.str("third\n");
20-end;
21-
22-proc nothing;
23-begin
24-end;
25-
26-proc main*: I64;
27-var i, full: I64;
28-begin
29- Rt.atExit(first);
30- Rt.atExit(second);
31- Rt.atExit(third);
32- full := 0;
33- for i := 1 to 40 do
34- if Rt.atExit(nothing) = Rt.Full then INC(full); end;
35- end;
36- Out.int(full); Out.str(" refused\n");
37- Out.str("main ends\n");
38- return 3;
39-end;
40-
41-end AtExit.

test/run/AtExit.raz added +41 -0

@@ -0,0 +1,41 @@
1+(* Rt.exit runs what Rt.atExit registered, the last first, each once,
2+ then ends the program with main's status. *)
3+module AtExit;
4+import Out, Rt;
5+
6+proc first;
7+begin
8+ Out.str("first\n");
9+end;
10+
11+proc second;
12+begin
13+ Out.str("second, which exits again\n");
14+ Rt.exit(5); (* the rest still run, once each; the status is now 5 *)
15+end;
16+
17+proc third;
18+begin
19+ Out.str("third\n");
20+end;
21+
22+proc nothing;
23+begin
24+end;
25+
26+proc main*: I64;
27+var i, full: I64;
28+begin
29+ Rt.atExit(first);
30+ Rt.atExit(second);
31+ Rt.atExit(third);
32+ full := 0;
33+ for i := 1 to 40 do
34+ if Rt.atExit(nothing) = Rt.Full then INC(full); end;
35+ end;
36+ Out.int(full); Out.str(" refused\n");
37+ Out.str("main ends\n");
38+ return 3;
39+end;
40+
41+end AtExit.

test/run/Atomic.jed deleted +0 -35

@@ -1,35 +0,0 @@
1-module Atomic;
2-import Out;
3-
4-var counter: I64; flag: U64; p: ^I64;
5-
6-proc add3*(a, b, c: I64): I64;
7-code 48H, 8DH, 04H, 37H, (* lea rax, [rdi+rsi] *)
8- 48H, 01H, 0D0H, (* add rax, rdx *)
9- 0C3H; (* ret *)
10-
11-proc main*;
12-var old: I64; ok: BOOL; v: ^VOLATILE I64; x: I64;
13-begin
14- old := XADD(ADR(counter), 5);
15- old := XADD(ADR(counter), 2);
16- Out.int(old); Out.str(" "); Out.int(counter); Out.ln;
17- ok := CAS(ADR(counter), 7, 100);
18- if ok then Out.str("cas1 "); end;
19- ok := CAS(ADR(counter), 7, 200);
20- if not ok then Out.str("cas2 "); end;
21- Out.int(counter); Out.ln;
22- Out.int(I64(XCHG(ADR(flag), 9))); Out.str(" ");
23- Out.int(I64(XCHG(ADR(flag), 3))); Out.ln;
24- FENCE;
25- FENCE();
26- Out.int(add3(1, 20, 300)); Out.ln;
27- v := ADR(x);
28- v^ := 5;
29- v^ := v^ + 1;
30- Out.int(x); Out.ln;
31- v := ^VOLATILE I64(ADR(counter));
32- Out.int(v^); Out.ln;
33-end;
34-
35-end Atomic.

test/run/Atomic.raz (history) added +35 -0

@@ -0,0 +1,35 @@
1+module Atomic;
2+import Out;
3+
4+var counter: I64; flag: U64; p: ^I64;
5+
6+proc add3*(a, b, c: I64): I64;
7+code 48H, 8DH, 04H, 37H, (* lea rax, [rdi+rsi] *)
8+ 48H, 01H, 0D0H, (* add rax, rdx *)
9+ 0C3H; (* ret *)
10+
11+proc main*;
12+var old: I64; ok: BOOL; v: ^VOLATILE I64; x: I64;
13+begin
14+ old := XADD(ADR(counter), 5);
15+ old := XADD(ADR(counter), 2);
16+ Out.int(old); Out.str(" "); Out.int(counter); Out.ln;
17+ ok := CAS(ADR(counter), 7, 100);
18+ if ok then Out.str("cas1 "); end;
19+ ok := CAS(ADR(counter), 7, 200);
20+ if not ok then Out.str("cas2 "); end;
21+ Out.int(counter); Out.ln;
22+ Out.int(I64(XCHG(ADR(flag), 9))); Out.str(" ");
23+ Out.int(I64(XCHG(ADR(flag), 3))); Out.ln;
24+ FENCE;
25+ FENCE();
26+ Out.int(add3(1, 20, 300)); Out.ln;
27+ v := ADR(x);
28+ v^ := 5;
29+ v^ := v^ + 1;
30+ Out.int(x); Out.ln;
31+ v := ^VOLATILE I64(ADR(counter));
32+ Out.int(v^); Out.ln;
33+end;
34+
35+end Atomic.

test/run/Bodies.jed deleted +0 -11

@@ -1,11 +0,0 @@
1-module Bodies;
2-import Out, A := First, Second;
3-
4-proc main*;
5-begin
6- Out.str("main "); Out.int(A.count); Out.int(Second.count); Out.ln;
7-end;
8-
9-begin
10- Out.str("Bodies ");
11-end Bodies.

test/run/Bodies.raz added +11 -0

@@ -0,0 +1,11 @@
1+module Bodies;
2+import Out, A := First, Second;
3+
4+proc main*;
5+begin
6+ Out.str("main "); Out.int(A.count); Out.int(Second.count); Out.ln;
7+end;
8+
9+begin
10+ Out.str("Bodies ");
11+end Bodies.

test/run/Bounds.jed deleted +0 -13

@@ -1,13 +0,0 @@
1-module Bounds;
2-import Out;
3-
4-proc main*;
5-var a: [4]I64; i: I64;
6-begin
7- for i := 0 to 4 do
8- a[i] := i;
9- Out.int(a[i]);
10- end;
11-end;
12-
13-end Bounds.

test/run/Bounds.raz added +13 -0

@@ -0,0 +1,13 @@
1+module Bounds;
2+import Out;
3+
4+proc main*;
5+var a: [4]I64; i: I64;
6+begin
7+ for i := 0 to 4 do
8+ a[i] := i;
9+ Out.int(a[i]);
10+ end;
11+end;
12+
13+end Bounds.

test/run/Control.jed deleted +0 -42

@@ -1,42 +0,0 @@
1-module Control;
2-import Out;
3-
4-proc main*;
5-var i, j, n: I64; u: U8; k: I8;
6-begin
7- for i := 1 to 5 do Out.int(i); end; Out.ln;
8- for i := 10 to 1 by -3 do Out.int(i); Out.str(" "); end; Out.ln;
9- for i := 0 to 10 by 4 do Out.int(i); Out.str(" "); end; Out.ln;
10- for i := 5 to 1 do Out.str("never"); end;
11- n := 0;
12- for u := 250 to 255 do n := n + 1; end;
13- Out.int(n); Out.ln;
14- n := 0;
15- for k := 120 to 127 by 3 do n := n + 1; end;
16- Out.int(n); Out.ln;
17- i := 0;
18- while i < 3 do
19- j := 0;
20- while true do
21- if j = 2 then break; end;
22- Out.int(i * 10 + j); Out.str(" ");
23- j := j + 1;
24- end;
25- i := i + 1;
26- end;
27- Out.ln;
28- i := 0;
29- repeat i := i + 1; if i = 4 then break; end; until i = 10;
30- Out.int(i); Out.ln;
31- for i := 1 to 4 do
32- if i = 1 then Out.str("one");
33- elsif i = 2 then Out.str("two");
34- elsif i = 3 then Out.str("three");
35- else Out.str("many");
36- end;
37- Out.str(" ");
38- end;
39- Out.ln;
40-end;
41-
42-end Control.

test/run/Control.raz added +42 -0

@@ -0,0 +1,42 @@
1+module Control;
2+import Out;
3+
4+proc main*;
5+var i, j, n: I64; u: U8; k: I8;
6+begin
7+ for i := 1 to 5 do Out.int(i); end; Out.ln;
8+ for i := 10 to 1 by -3 do Out.int(i); Out.str(" "); end; Out.ln;
9+ for i := 0 to 10 by 4 do Out.int(i); Out.str(" "); end; Out.ln;
10+ for i := 5 to 1 do Out.str("never"); end;
11+ n := 0;
12+ for u := 250 to 255 do n := n + 1; end;
13+ Out.int(n); Out.ln;
14+ n := 0;
15+ for k := 120 to 127 by 3 do n := n + 1; end;
16+ Out.int(n); Out.ln;
17+ i := 0;
18+ while i < 3 do
19+ j := 0;
20+ while true do
21+ if j = 2 then break; end;
22+ Out.int(i * 10 + j); Out.str(" ");
23+ j := j + 1;
24+ end;
25+ i := i + 1;
26+ end;
27+ Out.ln;
28+ i := 0;
29+ repeat i := i + 1; if i = 4 then break; end; until i = 10;
30+ Out.int(i); Out.ln;
31+ for i := 1 to 4 do
32+ if i = 1 then Out.str("one");
33+ elsif i = 2 then Out.str("two");
34+ elsif i = 3 then Out.str("three");
35+ else Out.str("many");
36+ end;
37+ Out.str(" ");
38+ end;
39+ Out.ln;
40+end;
41+
42+end Control.

test/run/Data.jed deleted +0 -72

@@ -1,72 +0,0 @@
1-module Data;
2-import Out;
3-
4-type
5- Cell = record ch: U8; attr: U8; end;
6- Mixed = record a: U8; b: I64; c: U16; end;
7- Packed = packed record a: U8; b: I64; c: U16; end;
8- Node = record next: ^Node; val: I64; end;
9- Grid = [3][4]I32;
10- Pair = record x, y: I64; end;
11-
12-var
13- nodes: [5]Node;
14- grid: Grid;
15- gp: Pair;
16-
17-proc sum(p: ^Node): I64;
18-var s: I64;
19-begin
20- s := 0;
21- while p # nil do
22- s := s + p^.val;
23- p := p^.next;
24- end;
25- return s;
26-end;
27-
28-proc main*;
29-var
30- c: Cell; cells: [4]Cell; m: Mixed; i, j: I64; p, q: ^I64; arr: [8]I64;
31- s: []I64; pp: Pair; bp: ^U8;
32-begin
33- Out.int(SIZE(Cell)); Out.str(" ");
34- Out.int(SIZE(Mixed)); Out.str(" ");
35- Out.int(SIZE(Packed)); Out.str(" ");
36- Out.int(SIZE(Grid)); Out.str(" ");
37- Out.int(SIZE([]U8)); Out.ln;
38- c.ch := 'x'; c.attr := 7;
39- cells[2] := c;
40- Out.int(I64(cells[2].ch)); Out.str(" "); Out.int(I64(cells[2].attr)); Out.ln;
41- for i := 0 to 4 do
42- nodes[i].val := i * i;
43- if i < 4 then nodes[i].next := ADR(nodes[i + 1]); end;
44- end;
45- Out.int(sum(ADR(nodes[0]))); Out.ln;
46- for i := 0 to 2 do
47- for j := 0 to 3 do grid[i][j] := I32(i * 10 + j); end;
48- end;
49- Out.int(I64(grid[2][3])); Out.str(" "); Out.int(I64(grid[1][0])); Out.ln;
50- for i := 0 to 7 do arr[i] := i * 100; end;
51- p := ADR(arr[0]);
52- q := p + 5;
53- Out.int(q^); Out.str(" "); Out.int(q - p); Out.str(" "); Out.int(p[3]); Out.ln;
54- s := arr[2..6];
55- Out.int(LEN(s)); Out.str(" "); Out.int(s[0]); Out.str(" "); Out.int(s[3]); Out.ln;
56- s := s[1..3];
57- Out.int(LEN(s)); Out.str(" "); Out.int(s[0]); Out.ln;
58- s := p[1..3];
59- Out.int(s[1]); Out.ln;
60- s := arr;
61- Out.int(LEN(s)); Out.ln;
62- pp.x := 3; pp.y := 4;
63- gp := pp;
64- pp.x := 99;
65- Out.int(gp.x); Out.str(" "); Out.int(gp.y); Out.ln;
66- m.a := 1; m.b := -2; m.c := 65535;
67- Out.int(m.b); Out.str(" "); Out.int(I64(m.c)); Out.ln;
68- bp := ^U8(ADR(m));
69- Out.int(I64(ADR(m.c)) - I64(bp)); Out.ln;
70-end;
71-
72-end Data.

test/run/Data.raz (history) added +72 -0

@@ -0,0 +1,72 @@
1+module Data;
2+import Out;
3+
4+type
5+ Cell = record ch: U8; attr: U8; end;
6+ Mixed = record a: U8; b: I64; c: U16; end;
7+ Packed = packed record a: U8; b: I64; c: U16; end;
8+ Node = record next: ^Node; val: I64; end;
9+ Grid = [3][4]I32;
10+ Pair = record x, y: I64; end;
11+
12+var
13+ nodes: [5]Node;
14+ grid: Grid;
15+ gp: Pair;
16+
17+proc sum(p: ^Node): I64;
18+var s: I64;
19+begin
20+ s := 0;
21+ while p # nil do
22+ s := s + p^.val;
23+ p := p^.next;
24+ end;
25+ return s;
26+end;
27+
28+proc main*;
29+var
30+ c: Cell; cells: [4]Cell; m: Mixed; i, j: I64; p, q: ^I64; arr: [8]I64;
31+ s: []I64; pp: Pair; bp: ^U8;
32+begin
33+ Out.int(SIZE(Cell)); Out.str(" ");
34+ Out.int(SIZE(Mixed)); Out.str(" ");
35+ Out.int(SIZE(Packed)); Out.str(" ");
36+ Out.int(SIZE(Grid)); Out.str(" ");
37+ Out.int(SIZE([]U8)); Out.ln;
38+ c.ch := 'x'; c.attr := 7;
39+ cells[2] := c;
40+ Out.int(I64(cells[2].ch)); Out.str(" "); Out.int(I64(cells[2].attr)); Out.ln;
41+ for i := 0 to 4 do
42+ nodes[i].val := i * i;
43+ if i < 4 then nodes[i].next := ADR(nodes[i + 1]); end;
44+ end;
45+ Out.int(sum(ADR(nodes[0]))); Out.ln;
46+ for i := 0 to 2 do
47+ for j := 0 to 3 do grid[i][j] := I32(i * 10 + j); end;
48+ end;
49+ Out.int(I64(grid[2][3])); Out.str(" "); Out.int(I64(grid[1][0])); Out.ln;
50+ for i := 0 to 7 do arr[i] := i * 100; end;
51+ p := ADR(arr[0]);
52+ q := p + 5;
53+ Out.int(q^); Out.str(" "); Out.int(q - p); Out.str(" "); Out.int(p[3]); Out.ln;
54+ s := arr[2..6];
55+ Out.int(LEN(s)); Out.str(" "); Out.int(s[0]); Out.str(" "); Out.int(s[3]); Out.ln;
56+ s := s[1..3];
57+ Out.int(LEN(s)); Out.str(" "); Out.int(s[0]); Out.ln;
58+ s := p[1..3];
59+ Out.int(s[1]); Out.ln;
60+ s := arr;
61+ Out.int(LEN(s)); Out.ln;
62+ pp.x := 3; pp.y := 4;
63+ gp := pp;
64+ pp.x := 99;
65+ Out.int(gp.x); Out.str(" "); Out.int(gp.y); Out.ln;
66+ m.a := 1; m.b := -2; m.c := 65535;
67+ Out.int(m.b); Out.str(" "); Out.int(I64(m.c)); Out.ln;
68+ bp := ^U8(ADR(m));
69+ Out.int(I64(ADR(m.c)) - I64(bp)); Out.ln;
70+end;
71+
72+end Data.

test/run/Defers.jed deleted +0 -71

@@ -1,71 +0,0 @@
1-module Defers;
2-import Out;
3-
4-type Pair = record a, b: I64; end;
5-
6-var depth: I64;
7-
8-proc enter(s: []U8);
9-begin
10- Out.str(s); INC(depth);
11-end;
12-
13-proc leave(s: []U8);
14-begin
15- Out.str(s); DEC(depth);
16-end;
17-
18-proc real(x: F64): F64;
19-begin
20- enter("(");
21- defer leave(")");
22- return x * 2.0;
23-end;
24-
25-proc pair(n: I64): Pair;
26-var p: Pair;
27-begin
28- defer p.a := 99;
29- p.a := n; p.b := n + 1;
30- return p;
31-end;
32-
33-proc begin_end(i: I64);
34-var k: I64;
35-begin
36- defer for k := 1 to i do Out.str("*"); end;
37- if i = 1 then return; end;
38- Out.str("+");
39-end;
40-
41-proc nested;
42-var i, j: I64;
43-begin
44- for i := 1 to 2 do
45- enter("[");
46- defer leave("]");
47- defer begin_end(i);
48- j := 0;
49- while true do
50- defer Out.str(".");
51- INC(j);
52- if j = 3 then break; end;
53- end;
54- end;
55-end;
56-
57-proc main*;
58-var p: Pair;
59-begin
60- Out.int(I64(real(1.5) * 10.0)); Out.ln;
61- p := pair(5);
62- Out.int(p.a); Out.int(p.b); Out.ln;
63- nested;
64- Out.ln;
65- Out.int(depth); Out.ln;
66-end;
67-
68-begin
69- defer Out.str("body done\n");
70- Out.str("body ");
71-end Defers.

test/run/Defers.raz added +71 -0

@@ -0,0 +1,71 @@
1+module Defers;
2+import Out;
3+
4+type Pair = record a, b: I64; end;
5+
6+var depth: I64;
7+
8+proc enter(s: []U8);
9+begin
10+ Out.str(s); INC(depth);
11+end;
12+
13+proc leave(s: []U8);
14+begin
15+ Out.str(s); DEC(depth);
16+end;
17+
18+proc real(x: F64): F64;
19+begin
20+ enter("(");
21+ defer leave(")");
22+ return x * 2.0;
23+end;
24+
25+proc pair(n: I64): Pair;
26+var p: Pair;
27+begin
28+ defer p.a := 99;
29+ p.a := n; p.b := n + 1;
30+ return p;
31+end;
32+
33+proc begin_end(i: I64);
34+var k: I64;
35+begin
36+ defer for k := 1 to i do Out.str("*"); end;
37+ if i = 1 then return; end;
38+ Out.str("+");
39+end;
40+
41+proc nested;
42+var i, j: I64;
43+begin
44+ for i := 1 to 2 do
45+ enter("[");
46+ defer leave("]");
47+ defer begin_end(i);
48+ j := 0;
49+ while true do
50+ defer Out.str(".");
51+ INC(j);
52+ if j = 3 then break; end;
53+ end;
54+ end;
55+end;
56+
57+proc main*;
58+var p: Pair;
59+begin
60+ Out.int(I64(real(1.5) * 10.0)); Out.ln;
61+ p := pair(5);
62+ Out.int(p.a); Out.int(p.b); Out.ln;
63+ nested;
64+ Out.ln;
65+ Out.int(depth); Out.ln;
66+end;
67+
68+begin
69+ defer Out.str("body done\n");
70+ Out.str("body ");
71+end Defers.

test/run/Edge.jed deleted +0 -64

@@ -1,64 +0,0 @@
1-module Edge;
2-import Out;
3-
4-type
5- Inner = record vals: [4]I64; name: []U8; end;
6- Outer = record items: [3]Inner; n: I64; end;
7-
8-var g: Outer; calls: I64;
9-
10-(* rsp mod 16 at the call, as the callee sees it after its return
11- address: always 8 when the caller keeps the stack aligned *)
12-proc rspmod: I64;
13-code 48H, 89H, 0E0H, (* mov rax, rsp *)
14- 48H, 83H, 0E0H, 0FH, (* and rax, 15 *)
15- 0C3H;
16-
17-proc next: I64;
18-begin
19- calls := calls + 1;
20- return calls;
21-end;
22-
23-proc setall(var o: Outer; v: I64);
24-var i, j: I64;
25-begin
26- for i := 0 to 2 do
27- for j := 0 to 3 do o.items[i].vals[j] := v + i * 10 + j; end;
28- o.items[i].name := "item";
29- end;
30- o.n := 3;
31-end;
32-
33-proc sumInner(xs: []Inner): I64;
34-var i, j, s: I64;
35-begin
36- s := 0;
37- for i := 0 to LEN(xs) - 1 do
38- for j := 0 to 3 do s := s + xs[i].vals[j]; end;
39- end;
40- return s;
41-end;
42-
43-proc main*;
44-var a: [5]I64; i, r: I64; o: Outer; pa: ^[5]I64;
45-begin
46- r := rspmod() + (1 + (2 + (3 + rspmod())));
47- Out.int(r); Out.ln;
48- a[next()] := next() * 10;
49- Out.int(a[1]); Out.str(" "); Out.int(calls); Out.ln;
50- setall(g, 100);
51- Out.int(g.items[2].vals[3]); Out.str(" "); Out.str(g.items[1].name); Out.ln;
52- o := g;
53- o.items[0].vals[0] := -1;
54- Out.int(g.items[0].vals[0]); Out.str(" "); Out.int(o.items[0].vals[0]); Out.ln;
55- Out.int(sumInner(g.items)); Out.str(" "); Out.int(sumInner(g.items[1..3])); Out.ln;
56- pa := ADR(a);
57- pa^[4] := 44;
58- Out.int(a[4]); Out.str(" "); Out.int(LEN(pa^)); Out.ln;
59- i := 2;
60- g.items[i].vals[i + 1] := g.items[i - 1].vals[i] + 1000;
61- Out.int(g.items[2].vals[3]); Out.ln;
62-end;
63-
64-end Edge.

test/run/Edge.raz (history) added +64 -0

@@ -0,0 +1,64 @@
1+module Edge;
2+import Out;
3+
4+type
5+ Inner = record vals: [4]I64; name: []U8; end;
6+ Outer = record items: [3]Inner; n: I64; end;
7+
8+var g: Outer; calls: I64;
9+
10+(* rsp mod 16 at the call, as the callee sees it after its return
11+ address: always 8 when the caller keeps the stack aligned *)
12+proc rspmod: I64;
13+code 48H, 89H, 0E0H, (* mov rax, rsp *)
14+ 48H, 83H, 0E0H, 0FH, (* and rax, 15 *)
15+ 0C3H;
16+
17+proc next: I64;
18+begin
19+ calls := calls + 1;
20+ return calls;
21+end;
22+
23+proc setall(var o: Outer; v: I64);
24+var i, j: I64;
25+begin
26+ for i := 0 to 2 do
27+ for j := 0 to 3 do o.items[i].vals[j] := v + i * 10 + j; end;
28+ o.items[i].name := "item";
29+ end;
30+ o.n := 3;
31+end;
32+
33+proc sumInner(xs: []Inner): I64;
34+var i, j, s: I64;
35+begin
36+ s := 0;
37+ for i := 0 to LEN(xs) - 1 do
38+ for j := 0 to 3 do s := s + xs[i].vals[j]; end;
39+ end;
40+ return s;
41+end;
42+
43+proc main*;
44+var a: [5]I64; i, r: I64; o: Outer; pa: ^[5]I64;
45+begin
46+ r := rspmod() + (1 + (2 + (3 + rspmod())));
47+ Out.int(r); Out.ln;
48+ a[next()] := next() * 10;
49+ Out.int(a[1]); Out.str(" "); Out.int(calls); Out.ln;
50+ setall(g, 100);
51+ Out.int(g.items[2].vals[3]); Out.str(" "); Out.str(g.items[1].name); Out.ln;
52+ o := g;
53+ o.items[0].vals[0] := -1;
54+ Out.int(g.items[0].vals[0]); Out.str(" "); Out.int(o.items[0].vals[0]); Out.ln;
55+ Out.int(sumInner(g.items)); Out.str(" "); Out.int(sumInner(g.items[1..3])); Out.ln;
56+ pa := ADR(a);
57+ pa^[4] := 44;
58+ Out.int(a[4]); Out.str(" "); Out.int(LEN(pa^)); Out.ln;
59+ i := 2;
60+ g.items[i].vals[i + 1] := g.items[i - 1].vals[i] + 1000;
61+ Out.int(g.items[2].vals[3]); Out.ln;
62+end;
63+
64+end Edge.

test/run/Extern.jed deleted +0 -65

@@ -1,65 +0,0 @@
1-(* Calling C: arguments in registers and on the stack, reals, ...,
2- C variables, jed procedures as C's callbacks. *)
3-module Extern;
4-import Out, C;
5-link "libm.so.6";
6-
7-extern proc strlen(s: ^U8): U64;
8-extern proc qsort(base: ^U8; n, size: U64; cmp: proc(a, b: ^I64): I32);
9-extern proc snprintf(buf: ^U8; n: U64; format: ^U8; ...): I32;
10-extern proc atoi(s: ^U8): I32;
11-extern proc abs(n: I32): I32;
12-extern proc sqrt(x: F64): F64;
13-extern proc getenv(name: ^U8): ^U8;
14-extern proc setenv(name, value: ^U8; overwrite: I32): I32;
15-extern var environ: ^^U8;
16-extern var optind: I32;
17-
18-var calls: I64;
19-
20-proc cmp(a, b: ^I64): I32;
21-begin
22- INC(calls);
23- if a^ < b^ then return -1; elsif a^ > b^ then return 1; end;
24- return 0;
25-end;
26-
27-proc main*;
28-var
29- a: [6]I64; i: I64; buf: [64]U8; n: I32;
30- len: proc(s: ^U8): U64; e: ^^U8;
31-begin
32- Out.int(I64(strlen("hello"))); Out.ln;
33- len := strlen;
34- Out.int(I64(len("hi there"))); Out.ln;
35- Out.int(I64(abs(-7)) + I64(atoi("35"))); Out.ln;
36- Out.int(I64(sqrt(2.0) * 1000.0)); Out.ln;
37-
38- a := [5, -3, 9, 0, 12, 1];
39- qsort(^U8(ADR(a)), 6, 8, cmp);
40- for i := 0 to 5 do Out.int(a[i]); Out.char(' '); end;
41- Out.ln;
42- if calls > 0 then Out.str("cmp called\n"); end;
43-
44- (* nine arguments after the format: some go on the stack *)
45- n := snprintf(ADR(buf[0]), 64, "%d %d %d %d %d %d %d %s|%.3f %g",
46- 1, 2, 3, 4, 5, 6, 7, "eight", 3.14159, 0.5);
47- Out.str(buf[0..I64(n)]); Out.ln;
48-
49- setenv("JED_TEST", "yes", 1);
50- Out.int(I64(strlen(getenv("JED_TEST")))); Out.ln;
51- e := environ;
52- i := 0;
53- while e^ # nil do INC(i); e := e + 1; end;
54- if i > 0 then Out.str("environ has entries\n"); end;
55- Out.int(I64(optind)); Out.ln;
56- optind := 5;
57- Out.int(I64(optind)); Out.ln;
58-
59- Out.flush;
60- C.printf("printf %d %s %.1f\n", -42, "too", 2.5);
61- C.fflush(C.stdout);
62- Out.str("done\n");
63-end;
64-
65-end Extern.

test/run/Extern.raz (history) added +65 -0

@@ -0,0 +1,65 @@
1+(* Calling C: arguments in registers and on the stack, reals, ...,
2+ C variables, raz procedures as C's callbacks. *)
3+module Extern;
4+import Out, C;
5+link "libm.so.6";
6+
7+extern proc strlen(s: ^U8): U64;
8+extern proc qsort(base: ^U8; n, size: U64; cmp: proc(a, b: ^I64): I32);
9+extern proc snprintf(buf: ^U8; n: U64; format: ^U8; ...): I32;
10+extern proc atoi(s: ^U8): I32;
11+extern proc abs(n: I32): I32;
12+extern proc sqrt(x: F64): F64;
13+extern proc getenv(name: ^U8): ^U8;
14+extern proc setenv(name, value: ^U8; overwrite: I32): I32;
15+extern var environ: ^^U8;
16+extern var optind: I32;
17+
18+var calls: I64;
19+
20+proc cmp(a, b: ^I64): I32;
21+begin
22+ INC(calls);
23+ if a^ < b^ then return -1; elsif a^ > b^ then return 1; end;
24+ return 0;
25+end;
26+
27+proc main*;
28+var
29+ a: [6]I64; i: I64; buf: [64]U8; n: I32;
30+ len: proc(s: ^U8): U64; e: ^^U8;
31+begin
32+ Out.int(I64(strlen("hello"))); Out.ln;
33+ len := strlen;
34+ Out.int(I64(len("hi there"))); Out.ln;
35+ Out.int(I64(abs(-7)) + I64(atoi("35"))); Out.ln;
36+ Out.int(I64(sqrt(2.0) * 1000.0)); Out.ln;
37+
38+ a := [5, -3, 9, 0, 12, 1];
39+ qsort(^U8(ADR(a)), 6, 8, cmp);
40+ for i := 0 to 5 do Out.int(a[i]); Out.char(' '); end;
41+ Out.ln;
42+ if calls > 0 then Out.str("cmp called\n"); end;
43+
44+ (* nine arguments after the format: some go on the stack *)
45+ n := snprintf(ADR(buf[0]), 64, "%d %d %d %d %d %d %d %s|%.3f %g",
46+ 1, 2, 3, 4, 5, 6, 7, "eight", 3.14159, 0.5);
47+ Out.str(buf[0..I64(n)]); Out.ln;
48+
49+ setenv("RAZ_TEST", "yes", 1);
50+ Out.int(I64(strlen(getenv("RAZ_TEST")))); Out.ln;
51+ e := environ;
52+ i := 0;
53+ while e^ # nil do INC(i); e := e + 1; end;
54+ if i > 0 then Out.str("environ has entries\n"); end;
55+ Out.int(I64(optind)); Out.ln;
56+ optind := 5;
57+ Out.int(I64(optind)); Out.ln;
58+
59+ Out.flush;
60+ C.printf("printf %d %s %.1f\n", -42, "too", 2.5);
61+ C.fflush(C.stdout);
62+ Out.str("done\n");
63+end;
64+
65+end Extern.

test/run/Generic.jed deleted +0 -30

@@ -1,30 +0,0 @@
1-module Generic;
2-import Fmt, Buf, Str, Heap, Stack, Ints := List(I64), More := List(I64), Strs := List([]U8);
3-
4-proc twice(x: I64): I64; begin return x * 2; end;
5-
6-proc main*;
7-var l: Strs.List; v: I64; s: []U8; ok: BOOL; b: Buf.Buf; n: ^Ints.Node;
8-begin
9- ok := Ints.push(ADR(Stack.s), 7);
10- ok := More.push(ADR(Stack.s), 8);
11- Fmt.print("{} {} {}\n", [Fmt.int(Stack.top()), Fmt.int(Stack.s.len), Fmt.bool(ok)]);
12- n := Stack.s.head;
13- v, ok := Ints.pop(ADR(Stack.s));
14- Fmt.print("{} {}\n", [Fmt.int(v), Fmt.int(Stack.s.len)]);
15- Strs.init(ADR(l), Heap.heap);
16- ok := Strs.push(ADR(l), "b");
17- ok := Strs.push(ADR(l), "a");
18- s, ok := Strs.pop(ADR(l));
19- Fmt.print("{}{}{}\n", [Fmt.str(s), Fmt.str(l.head^.val), Fmt.bool(ok)]);
20- s, ok := Strs.pop(ADR(l));
21- s, ok := Strs.pop(ADR(l));
22- Fmt.print("[{}] {}\n", [Fmt.str(s), Fmt.bool(ok)]);
23- Buf.init(ADR(b), Heap.heap);
24- for v := 1 to 40 do Fmt.write(ADR(b), "{},", [Fmt.int(v * v)]); end;
25- Fmt.print("{} {} {}\n", [Fmt.int(b.len), Fmt.int(Str.find(Buf.bytes(ADR(b)), "1600")), Fmt.int(Str.cmp("ab", "b"))]);
26- Buf.done(ADR(b));
27- Fmt.print("{{ {} }} {}{}\n", [Fmt.hex(48879), Fmt.char('x'), Fmt.uint(0FFFFFFFFFFFFFFFFH)]);
28-end;
29-
30-end Generic.

test/run/Generic.raz added +30 -0

@@ -0,0 +1,30 @@
1+module Generic;
2+import Fmt, Buf, Str, Heap, Stack, Ints := List(I64), More := List(I64), Strs := List([]U8);
3+
4+proc twice(x: I64): I64; begin return x * 2; end;
5+
6+proc main*;
7+var l: Strs.List; v: I64; s: []U8; ok: BOOL; b: Buf.Buf; n: ^Ints.Node;
8+begin
9+ ok := Ints.push(ADR(Stack.s), 7);
10+ ok := More.push(ADR(Stack.s), 8);
11+ Fmt.print("{} {} {}\n", [Fmt.int(Stack.top()), Fmt.int(Stack.s.len), Fmt.bool(ok)]);
12+ n := Stack.s.head;
13+ v, ok := Ints.pop(ADR(Stack.s));
14+ Fmt.print("{} {}\n", [Fmt.int(v), Fmt.int(Stack.s.len)]);
15+ Strs.init(ADR(l), Heap.heap);
16+ ok := Strs.push(ADR(l), "b");
17+ ok := Strs.push(ADR(l), "a");
18+ s, ok := Strs.pop(ADR(l));
19+ Fmt.print("{}{}{}\n", [Fmt.str(s), Fmt.str(l.head^.val), Fmt.bool(ok)]);
20+ s, ok := Strs.pop(ADR(l));
21+ s, ok := Strs.pop(ADR(l));
22+ Fmt.print("[{}] {}\n", [Fmt.str(s), Fmt.bool(ok)]);
23+ Buf.init(ADR(b), Heap.heap);
24+ for v := 1 to 40 do Fmt.write(ADR(b), "{},", [Fmt.int(v * v)]); end;
25+ Fmt.print("{} {} {}\n", [Fmt.int(b.len), Fmt.int(Str.find(Buf.bytes(ADR(b)), "1600")), Fmt.int(Str.cmp("ab", "b"))]);
26+ Buf.done(ADR(b));
27+ Fmt.print("{{ {} }} {}{}\n", [Fmt.hex(48879), Fmt.char('x'), Fmt.uint(0FFFFFFFFFFFFFFFFH)]);
28+end;
29+
30+end Generic.

test/run/HeapCheck.jed deleted +0 -34

@@ -1,34 +0,0 @@
1-(* The heap refuses bad sizes and alignments, and stops the program
2- when a block is freed twice. *)
3-module HeapCheck;
4-import Out, Heap, Mem;
5-
6-proc show(p: ^U8);
7-begin
8- if p = nil then Out.str("nil\n"); else Out.str("a block\n"); end;
9-end;
10-
11-proc main*;
12-var p, q: ^U8;
13-begin
14- show(Mem.alloc(Heap.heap, -1, 8));
15- show(Mem.alloc(Heap.heap, 1 shl 60, 8));
16- show(Mem.alloc(Heap.heap, 7FFFFFFFFFFFFFF0H, 8));
17- show(Mem.alloc(Heap.heap, 10, 3));
18- show(Mem.alloc(Heap.heap, 10, 0));
19- show(Mem.alloc(Heap.heap, 10, 8192));
20- p := Mem.alloc(Heap.heap, 10, 64);
21- show(p);
22- if I64(p) mod 64 = 0 then Out.str("aligned\n"); end;
23- Mem.free(Heap.heap, p);
24- q := Mem.alloc(Heap.heap, 100000, 8);
25- show(q);
26- Mem.free(Heap.heap, q);
27- p := Mem.alloc(Heap.heap, 24, 8);
28- Mem.free(Heap.heap, p);
29- Out.str("freeing it again\n");
30- Mem.free(Heap.heap, p);
31- Out.str("not reached\n");
32-end;
33-
34-end HeapCheck.

test/run/HeapCheck.raz (history) added +34 -0

@@ -0,0 +1,34 @@
1+(* The heap refuses bad sizes and alignments, and stops the program
2+ when a block is freed twice. *)
3+module HeapCheck;
4+import Out, Heap, Mem;
5+
6+proc show(p: ^U8);
7+begin
8+ if p = nil then Out.str("nil\n"); else Out.str("a block\n"); end;
9+end;
10+
11+proc main*;
12+var p, q: ^U8;
13+begin
14+ show(Mem.alloc(Heap.heap, -1, 8));
15+ show(Mem.alloc(Heap.heap, 1 shl 60, 8));
16+ show(Mem.alloc(Heap.heap, 7FFFFFFFFFFFFFF0H, 8));
17+ show(Mem.alloc(Heap.heap, 10, 3));
18+ show(Mem.alloc(Heap.heap, 10, 0));
19+ show(Mem.alloc(Heap.heap, 10, 8192));
20+ p := Mem.alloc(Heap.heap, 10, 64);
21+ show(p);
22+ if I64(p) mod 64 = 0 then Out.str("aligned\n"); end;
23+ Mem.free(Heap.heap, p);
24+ q := Mem.alloc(Heap.heap, 100000, 8);
25+ show(q);
26+ Mem.free(Heap.heap, q);
27+ p := Mem.alloc(Heap.heap, 24, 8);
28+ Mem.free(Heap.heap, p);
29+ Out.str("freeing it again\n");
30+ Mem.free(Heap.heap, p);
31+ Out.str("not reached\n");
32+end;
33+
34+end HeapCheck.

test/run/HeapStray.jed deleted +0 -14

@@ -1,14 +0,0 @@
1-(* Freeing what the heap never gave out stops the program. *)
2-module HeapStray;
3-import Out, Heap, Mem;
4-
5-var a: [4]I64;
6-
7-proc main*;
8-begin
9- Out.str("freeing a stray pointer\n");
10- Mem.free(Heap.heap, ^U8(ADR(a[2])));
11- Out.str("not reached\n");
12-end;
13-
14-end HeapStray.

test/run/HeapStray.raz (history) added +14 -0

@@ -0,0 +1,14 @@
1+(* Freeing what the heap never gave out stops the program. *)
2+module HeapStray;
3+import Out, Heap, Mem;
4+
5+var a: [4]I64;
6+
7+proc main*;
8+begin
9+ Out.str("freeing a stray pointer\n");
10+ Mem.free(Heap.heap, ^U8(ADR(a[2])));
11+ Out.str("not reached\n");
12+end;
13+
14+end HeapStray.

test/run/Kinds.jed deleted +0 -95

@@ -1,95 +0,0 @@
1-module Kinds;
2-import Out;
3-
4-type
5- Color* = (red, green, blue, black);
6- Colors* = set of Color;
7- Cell = record ch: U8; attr: U8; fg: Color; end;
8- Point = record x, y: I64; name: []U8; end;
9- Line = record a, b: Point; end;
10-
11-var log: [8]U8; nlog: I64;
12-
13-proc note(c: U8);
14-begin
15- log[nlog] := c;
16- INC(nlog);
17-end;
18-
19-proc show(s: Colors);
20-var c: Color;
21-begin
22- for c := red to black do
23- if c in s then Out.int(I64(c)); end;
24- end;
25- Out.str(" ");
26-end;
27-
28-proc name(c: Color): []U8;
29-begin
30- match c of
31- | red: return "red";
32- | green: return "green";
33- | else: return "other";
34- end;
35-end;
36-
37-proc deferred(n: I64): I64;
38-var i: I64;
39-begin
40- defer note('A');
41- defer note('B');
42- for i := 1 to 3 do
43- defer note('L');
44- if i = 2 then break; end;
45- end;
46- if n > 0 then
47- defer note('C');
48- return n * 10;
49- end;
50- note('D');
51- return -1;
52-end;
53-
54-proc mid(a, b: Point): Point;
55-begin
56- return {x: (a.x + b.x) div 2, y: (a.y + b.y) div 2, name: "mid"};
57-end;
58-
59-proc main*;
60-var s, t: Colors; c: Color; cell: Cell; p: Point; l: Line; r: I64; one: Colors;
61-begin
62- s := {red, blue};
63- t := {blue, black};
64- show(s + t); show(s * t); show(s - t); show({});
65- if red in s then Out.str("in "); end;
66- if not (green in s) then Out.str("out "); end;
67- if s * t <= t then Out.str("sub "); end;
68- if s + t >= s then Out.str("sup "); end;
69- if s # t then Out.str("ne "); end;
70- if s = {blue, red} then Out.str("eq"); end;
71- Out.ln;
72- c := green;
73- one := {c, black};
74- show(one);
75- Out.int(I64(U8(one))); Out.str(" ");
76- Out.int(SIZE(Colors)); Out.str(" ");
77- Out.int(I64(Color(2))); Out.str(" ");
78- if c < blue then Out.str("lt "); end;
79- Out.str(name(c)); Out.str(" "); Out.str(name(black)); Out.ln;
80- cell := {ch: 'x', fg: blue};
81- Out.int(I64(cell.ch)); Out.str(" "); Out.int(I64(cell.attr)); Out.str(" "); Out.int(I64(cell.fg)); Out.ln;
82- p := mid({x: 2, y: 4}, {y: 10, x: 6});
83- Out.int(p.x); Out.int(p.y); Out.str(p.name); Out.ln;
84- l := {a: {x: 1, y: 2}, b: p};
85- Out.int(l.a.y); Out.int(l.b.x); Out.ln;
86- r := deferred(5);
87- Out.int(r); Out.str(" "); Out.str(log[0..nlog]); Out.ln;
88- nlog := 0;
89- r := deferred(0);
90- Out.int(r); Out.str(" "); Out.str(log[0..nlog]); Out.ln;
91- Out.int(I64(Color(I64(c) + 2)));
92- c := Color(nlog);
93-end;
94-
95-end Kinds.

test/run/Kinds.raz added +95 -0

@@ -0,0 +1,95 @@
1+module Kinds;
2+import Out;
3+
4+type
5+ Color* = (red, green, blue, black);
6+ Colors* = set of Color;
7+ Cell = record ch: U8; attr: U8; fg: Color; end;
8+ Point = record x, y: I64; name: []U8; end;
9+ Line = record a, b: Point; end;
10+
11+var log: [8]U8; nlog: I64;
12+
13+proc note(c: U8);
14+begin
15+ log[nlog] := c;
16+ INC(nlog);
17+end;
18+
19+proc show(s: Colors);
20+var c: Color;
21+begin
22+ for c := red to black do
23+ if c in s then Out.int(I64(c)); end;
24+ end;
25+ Out.str(" ");
26+end;
27+
28+proc name(c: Color): []U8;
29+begin
30+ match c of
31+ | red: return "red";
32+ | green: return "green";
33+ | else: return "other";
34+ end;
35+end;
36+
37+proc deferred(n: I64): I64;
38+var i: I64;
39+begin
40+ defer note('A');
41+ defer note('B');
42+ for i := 1 to 3 do
43+ defer note('L');
44+ if i = 2 then break; end;
45+ end;
46+ if n > 0 then
47+ defer note('C');
48+ return n * 10;
49+ end;
50+ note('D');
51+ return -1;
52+end;
53+
54+proc mid(a, b: Point): Point;
55+begin
56+ return {x: (a.x + b.x) div 2, y: (a.y + b.y) div 2, name: "mid"};
57+end;
58+
59+proc main*;
60+var s, t: Colors; c: Color; cell: Cell; p: Point; l: Line; r: I64; one: Colors;
61+begin
62+ s := {red, blue};
63+ t := {blue, black};
64+ show(s + t); show(s * t); show(s - t); show({});
65+ if red in s then Out.str("in "); end;
66+ if not (green in s) then Out.str("out "); end;
67+ if s * t <= t then Out.str("sub "); end;
68+ if s + t >= s then Out.str("sup "); end;
69+ if s # t then Out.str("ne "); end;
70+ if s = {blue, red} then Out.str("eq"); end;
71+ Out.ln;
72+ c := green;
73+ one := {c, black};
74+ show(one);
75+ Out.int(I64(U8(one))); Out.str(" ");
76+ Out.int(SIZE(Colors)); Out.str(" ");
77+ Out.int(I64(Color(2))); Out.str(" ");
78+ if c < blue then Out.str("lt "); end;
79+ Out.str(name(c)); Out.str(" "); Out.str(name(black)); Out.ln;
80+ cell := {ch: 'x', fg: blue};
81+ Out.int(I64(cell.ch)); Out.str(" "); Out.int(I64(cell.attr)); Out.str(" "); Out.int(I64(cell.fg)); Out.ln;
82+ p := mid({x: 2, y: 4}, {y: 10, x: 6});
83+ Out.int(p.x); Out.int(p.y); Out.str(p.name); Out.ln;
84+ l := {a: {x: 1, y: 2}, b: p};
85+ Out.int(l.a.y); Out.int(l.b.x); Out.ln;
86+ r := deferred(5);
87+ Out.int(r); Out.str(" "); Out.str(log[0..nlog]); Out.ln;
88+ nlog := 0;
89+ r := deferred(0);
90+ Out.int(r); Out.str(" "); Out.str(log[0..nlog]); Out.ln;
91+ Out.int(I64(Color(I64(c) + 2)));
92+ c := Color(nlog);
93+end;
94+
95+end Kinds.

test/run/Procs.jed deleted +0 -117

@@ -1,117 +0,0 @@
1-module Procs;
2-import Out;
3-
4-type
5- Pair = record x, y: I64; end;
6- Op = proc(a, b: I64): I64;
7- Big = record a: [10]I64; end;
8-
9-proc even(n: I64): BOOL; forward;
10-
11-proc odd(n: I64): BOOL;
12-begin
13- if n = 0 then return false; end;
14- return even(n - 1);
15-end;
16-
17-proc even(n: I64): BOOL;
18-begin
19- if n = 0 then return true; end;
20- return odd(n - 1);
21-end;
22-
23-proc swap(var a, b: I64);
24-var t: I64;
25-begin
26- t := a; a := b; b := t;
27-end;
28-
29-proc bump(p: Pair): Pair;
30-begin
31- p.x := p.x + 1;
32- p.y := p.y + 1;
33- return p;
34-end;
35-
36-proc add(a, b: I64): I64; begin return a + b; end;
37-proc mul(a, b: I64): I64; begin return a * b; end;
38-
39-proc apply(f: Op; a, b: I64): I64;
40-begin
41- return f(a, b);
42-end;
43-
44-proc many(a, b, c, d, e, f, g, h: I64; x: F64; i: I64; y: F64): I64;
45-begin
46- return a + 2 * b + 3 * c + 4 * d + 5 * e + 6 * f + 7 * g + 8 * h + I64(x) * 100 + 9 * i + I64(y) * 1000;
47-end;
48-
49-proc fact(n: I64): I64;
50-begin
51- if n <= 1 then return 1; end;
52- return n * fact(n - 1);
53-end;
54-
55-proc fill(var b: Big; v: I64);
56-var i: I64;
57-begin
58- for i := 0 to 9 do b.a[i] := v + i; end;
59-end;
60-
61-proc total(b: Big): I64;
62-var i, s: I64;
63-begin
64- s := 0;
65- for i := 0 to 9 do s := s + b.a[i]; end;
66- b.a[0] := 1000;
67- return s;
68-end;
69-
70-proc noresult(n: I64): I64;
71-begin
72- if n > 100 then return 1; end;
73-end;
74-
75-proc mk(n: I64): Big;
76-var b: Big;
77-begin
78- fill(b, n);
79- return b;
80-end;
81-
82-proc mkzero(n: I64): Big;
83-begin
84-end;
85-
86-proc fsum(a, b: F64): F64;
87-begin
88- return a + b;
89-end;
90-
91-proc main*: I64;
92-var a, b: I64; p, q: Pair; f: Op; bg: Big;
93-begin
94- if even(10) and odd(7) and not even(3) then Out.str("parity ok"); Out.ln; end;
95- a := 1; b := 2;
96- swap(a, b);
97- Out.int(a); Out.int(b); Out.ln;
98- p.x := 10; p.y := 20;
99- q := bump(p);
100- Out.int(p.x); Out.str(" "); Out.int(q.x); Out.str(" "); Out.int(q.y); Out.ln;
101- Out.int(bump(bump(p)).y); Out.ln;
102- f := add;
103- Out.int(apply(f, 3, 4)); Out.str(" "); Out.int(apply(mul, 3, 4)); Out.ln;
104- if f = add then Out.str("same"); Out.ln; end;
105- f := nil;
106- if f = nil then Out.str("nil"); Out.ln; end;
107- Out.int(many(1, 1, 1, 1, 1, 1, 1, 1, 2.5, 1, 3.9)); Out.ln;
108- Out.int(fact(20)); Out.ln;
109- fill(bg, 5);
110- Out.int(total(bg)); Out.str(" "); Out.int(bg.a[0]); Out.ln;
111- Out.int(noresult(5)); Out.ln;
112- Out.int(mk(7).a[9]); Out.str(" "); Out.int(mkzero(1).a[3]); Out.ln;
113- Out.int(I64(fsum(1.25, 2.5) * 4.0)); Out.ln;
114- return 7;
115-end;
116-
117-end Procs.

test/run/Procs.raz added +117 -0

@@ -0,0 +1,117 @@
1+module Procs;
2+import Out;
3+
4+type
5+ Pair = record x, y: I64; end;
6+ Op = proc(a, b: I64): I64;
7+ Big = record a: [10]I64; end;
8+
9+proc even(n: I64): BOOL; forward;
10+
11+proc odd(n: I64): BOOL;
12+begin
13+ if n = 0 then return false; end;
14+ return even(n - 1);
15+end;
16+
17+proc even(n: I64): BOOL;
18+begin
19+ if n = 0 then return true; end;
20+ return odd(n - 1);
21+end;
22+
23+proc swap(var a, b: I64);
24+var t: I64;
25+begin
26+ t := a; a := b; b := t;
27+end;
28+
29+proc bump(p: Pair): Pair;
30+begin
31+ p.x := p.x + 1;
32+ p.y := p.y + 1;
33+ return p;
34+end;
35+
36+proc add(a, b: I64): I64; begin return a + b; end;
37+proc mul(a, b: I64): I64; begin return a * b; end;
38+
39+proc apply(f: Op; a, b: I64): I64;
40+begin
41+ return f(a, b);
42+end;
43+
44+proc many(a, b, c, d, e, f, g, h: I64; x: F64; i: I64; y: F64): I64;
45+begin
46+ return a + 2 * b + 3 * c + 4 * d + 5 * e + 6 * f + 7 * g + 8 * h + I64(x) * 100 + 9 * i + I64(y) * 1000;
47+end;
48+
49+proc fact(n: I64): I64;
50+begin
51+ if n <= 1 then return 1; end;
52+ return n * fact(n - 1);
53+end;
54+
55+proc fill(var b: Big; v: I64);
56+var i: I64;
57+begin
58+ for i := 0 to 9 do b.a[i] := v + i; end;
59+end;
60+
61+proc total(b: Big): I64;
62+var i, s: I64;
63+begin
64+ s := 0;
65+ for i := 0 to 9 do s := s + b.a[i]; end;
66+ b.a[0] := 1000;
67+ return s;
68+end;
69+
70+proc noresult(n: I64): I64;
71+begin
72+ if n > 100 then return 1; end;
73+end;
74+
75+proc mk(n: I64): Big;
76+var b: Big;
77+begin
78+ fill(b, n);
79+ return b;
80+end;
81+
82+proc mkzero(n: I64): Big;
83+begin
84+end;
85+
86+proc fsum(a, b: F64): F64;
87+begin
88+ return a + b;
89+end;
90+
91+proc main*: I64;
92+var a, b: I64; p, q: Pair; f: Op; bg: Big;
93+begin
94+ if even(10) and odd(7) and not even(3) then Out.str("parity ok"); Out.ln; end;
95+ a := 1; b := 2;
96+ swap(a, b);
97+ Out.int(a); Out.int(b); Out.ln;
98+ p.x := 10; p.y := 20;
99+ q := bump(p);
100+ Out.int(p.x); Out.str(" "); Out.int(q.x); Out.str(" "); Out.int(q.y); Out.ln;
101+ Out.int(bump(bump(p)).y); Out.ln;
102+ f := add;
103+ Out.int(apply(f, 3, 4)); Out.str(" "); Out.int(apply(mul, 3, 4)); Out.ln;
104+ if f = add then Out.str("same"); Out.ln; end;
105+ f := nil;
106+ if f = nil then Out.str("nil"); Out.ln; end;
107+ Out.int(many(1, 1, 1, 1, 1, 1, 1, 1, 2.5, 1, 3.9)); Out.ln;
108+ Out.int(fact(20)); Out.ln;
109+ fill(bg, 5);
110+ Out.int(total(bg)); Out.str(" "); Out.int(bg.a[0]); Out.ln;
111+ Out.int(noresult(5)); Out.ln;
112+ Out.int(mk(7).a[9]); Out.str(" "); Out.int(mkzero(1).a[3]); Out.ln;
113+ Out.int(I64(fsum(1.25, 2.5) * 4.0)); Out.ln;
114+ return 7;
115+end;
116+
117+end Procs.

test/run/Results.jed deleted +0 -79

@@ -1,79 +0,0 @@
1-module Results;
2-import Out;
3-
4-const
5- NotFound*: ERROR = "not found";
6- Empty: ERROR = "empty";
7- Other: ERROR = "not found";
8-
9-type Pair = record a, b: I64; end;
10-
11-var table: [4]I64; g: Pair;
12-
13-proc divmod(a, b: I64): (I64, I64);
14-begin
15- return a div b, a mod b;
16-end;
17-
18-proc find(key: I64): (I64, ERROR);
19-var i: I64;
20-begin
21- for i := 0 to 3 do
22- if table[i] = key then return i, nil; end;
23- end;
24- return -1, NotFound;
25-end;
26-
27-proc mixed(x: F64): (F64, []U8, Pair, BOOL);
28-var p: Pair;
29-begin
30- p.a := 1; p.b := 2;
31- return x * 2.0, "two", p, true;
32-end;
33-
34-proc minmax(a, b: I64): (I64, I64);
35-code 48H, 89H, 0F8H, (* mov rax, rdi *)
36- 48H, 89H, 0F2H, (* mov rdx, rsi *)
37- 48H, 39H, 0F7H, (* cmp rdi, rsi *)
38- 7EH, 06H, (* jle +6 *)
39- 48H, 89H, 0F0H, (* mov rax, rsi *)
40- 48H, 89H, 0FAH, (* mov rdx, rdi *)
41- 0C3H;
42-
43-proc nothing: (I64, ERROR);
44-begin
45-end;
46-
47-proc main*;
48-var q, r, i: I64; e: ERROR; x: F64; s: []U8; p: Pair; ok: BOOL; a: [3]I64; u: U8;
49-begin
50- q, r := divmod(17, 5);
51- Out.int(q); Out.str(" "); Out.int(r); Out.ln;
52- table := [10, 20, 30, 40];
53- i, e := find(30);
54- Out.int(i); if e = nil then Out.str(" nil"); end; Out.ln;
55- i, e := find(7);
56- Out.int(i); Out.str(" "); Out.str(MSG(e));
57- if e = NotFound then Out.str(" is NotFound"); end;
58- if e # Other then Out.str(", not Other"); end;
59- if e # Empty then Out.str(", not Empty"); end;
60- Out.ln;
61- Out.str("["); Out.str(MSG(nil)); Out.str("]"); Out.ln;
62- x, s, p, ok := mixed(1.5);
63- Out.int(I64(x * 10.0)); Out.str(" "); Out.str(s); Out.str(" "); Out.int(p.b);
64- if ok then Out.str(" ok"); end; Out.ln;
65- a[1], g.b := divmod(9, 4);
66- Out.int(a[1]); Out.str(" "); Out.int(g.b); Out.ln;
67- q, r := minmax(9, 3);
68- Out.int(q); Out.int(r); Out.ln;
69- divmod(1, 1);
70- i, e := nothing();
71- Out.int(i); if e = nil then Out.str(" zero"); end; Out.ln;
72- i := 5;
73- INC(i); INC(i, 10); DEC(i, 2);
74- a[2] := 7; DEC(a[2]);
75- u := 255; INC(u);
76- Out.int(i); Out.str(" "); Out.int(a[2]); Out.str(" "); Out.int(I64(u)); Out.ln;
77-end;
78-
79-end Results.

test/run/Results.raz (history) added +79 -0

@@ -0,0 +1,79 @@
1+module Results;
2+import Out;
3+
4+const
5+ NotFound*: ERROR = "not found";
6+ Empty: ERROR = "empty";
7+ Other: ERROR = "not found";
8+
9+type Pair = record a, b: I64; end;
10+
11+var table: [4]I64; g: Pair;
12+
13+proc divmod(a, b: I64): (I64, I64);
14+begin
15+ return a div b, a mod b;
16+end;
17+
18+proc find(key: I64): (I64, ERROR);
19+var i: I64;
20+begin
21+ for i := 0 to 3 do
22+ if table[i] = key then return i, nil; end;
23+ end;
24+ return -1, NotFound;
25+end;
26+
27+proc mixed(x: F64): (F64, []U8, Pair, BOOL);
28+var p: Pair;
29+begin
30+ p.a := 1; p.b := 2;
31+ return x * 2.0, "two", p, true;
32+end;
33+
34+proc minmax(a, b: I64): (I64, I64);
35+code 48H, 89H, 0F8H, (* mov rax, rdi *)
36+ 48H, 89H, 0F2H, (* mov rdx, rsi *)
37+ 48H, 39H, 0F7H, (* cmp rdi, rsi *)
38+ 7EH, 06H, (* jle +6 *)
39+ 48H, 89H, 0F0H, (* mov rax, rsi *)
40+ 48H, 89H, 0FAH, (* mov rdx, rdi *)
41+ 0C3H;
42+
43+proc nothing: (I64, ERROR);
44+begin
45+end;
46+
47+proc main*;
48+var q, r, i: I64; e: ERROR; x: F64; s: []U8; p: Pair; ok: BOOL; a: [3]I64; u: U8;
49+begin
50+ q, r := divmod(17, 5);
51+ Out.int(q); Out.str(" "); Out.int(r); Out.ln;
52+ table := [10, 20, 30, 40];
53+ i, e := find(30);
54+ Out.int(i); if e = nil then Out.str(" nil"); end; Out.ln;
55+ i, e := find(7);
56+ Out.int(i); Out.str(" "); Out.str(MSG(e));
57+ if e = NotFound then Out.str(" is NotFound"); end;
58+ if e # Other then Out.str(", not Other"); end;
59+ if e # Empty then Out.str(", not Empty"); end;
60+ Out.ln;
61+ Out.str("["); Out.str(MSG(nil)); Out.str("]"); Out.ln;
62+ x, s, p, ok := mixed(1.5);
63+ Out.int(I64(x * 10.0)); Out.str(" "); Out.str(s); Out.str(" "); Out.int(p.b);
64+ if ok then Out.str(" ok"); end; Out.ln;
65+ a[1], g.b := divmod(9, 4);
66+ Out.int(a[1]); Out.str(" "); Out.int(g.b); Out.ln;
67+ q, r := minmax(9, 3);
68+ Out.int(q); Out.int(r); Out.ln;
69+ divmod(1, 1);
70+ i, e := nothing();
71+ Out.int(i); if e = nil then Out.str(" zero"); end; Out.ln;
72+ i := 5;
73+ INC(i); INC(i, 10); DEC(i, 2);
74+ a[2] := 7; DEC(a[2]);
75+ u := 255; INC(u);
76+ Out.int(i); Out.str(" "); Out.int(a[2]); Out.str(" "); Out.int(I64(u)); Out.ln;
77+end;
78+
79+end Results.

test/run/Shapes.jed deleted +0 -63

@@ -1,63 +0,0 @@
1-module Shapes;
2-import Out;
3-
4-type
5- Shape* = variant
6- circle(r: F64);
7- rect(w, h: F64);
8- label(text: []U8; size: I64);
9- dot;
10- end;
11-
12-proc area(s: Shape): I64;
13-var a: F64;
14-begin
15- match s of
16- | circle(r): a := 3.0 * r * r;
17- | rect(w, h): a := w * h;
18- | label: a := 0.0;
19- | dot: a := 1.0;
20- end;
21- return I64(a);
22-end;
23-
24-proc grow(var s: Shape);
25-begin
26- match s of
27- | rect(w, h): w := w * 2.0;
28- | else:
29- end;
30-end;
31-
32-proc main*;
33-var s, t: Shape; shapes: [4]Shape; i: I64; z: Shape;
34-begin
35- s := circle(2.0);
36- Out.int(area(s)); Out.ln;
37- s := rect(3.0, 4.0);
38- Out.int(area(s)); Out.ln;
39- grow(s);
40- Out.int(area(s)); Out.ln;
41- t := s;
42- s := dot;
43- Out.int(area(s)); Out.str(" "); Out.int(area(t)); Out.ln;
44- shapes[0] := circle(1.0);
45- shapes[1] := label("hi", 12);
46- shapes[2] := dot;
47- shapes[3] := rect(1.5, 2.0);
48- for i := 0 to 3 do
49- match shapes[i] of
50- | label(text, size): Out.str(text); Out.int(size);
51- | else: Out.int(area(shapes[i]));
52- end;
53- Out.str(" ");
54- end;
55- Out.ln;
56- match z of
57- | circle(r): Out.str("zero is a circle of "); Out.int(I64(r)); Out.ln;
58- | else: Out.str("?");
59- end;
60- Out.int(SIZE(Shape)); Out.ln;
61-end;
62-
63-end Shapes.

test/run/Shapes.raz (history) added +63 -0

@@ -0,0 +1,63 @@
1+module Shapes;
2+import Out;
3+
4+type
5+ Shape* = variant
6+ circle(r: F64);
7+ rect(w, h: F64);
8+ label(text: []U8; size: I64);
9+ dot;
10+ end;
11+
12+proc area(s: Shape): I64;
13+var a: F64;
14+begin
15+ match s of
16+ | circle(r): a := 3.0 * r * r;
17+ | rect(w, h): a := w * h;
18+ | label: a := 0.0;
19+ | dot: a := 1.0;
20+ end;
21+ return I64(a);
22+end;
23+
24+proc grow(var s: Shape);
25+begin
26+ match s of
27+ | rect(w, h): w := w * 2.0;
28+ | else:
29+ end;
30+end;
31+
32+proc main*;
33+var s, t: Shape; shapes: [4]Shape; i: I64; z: Shape;
34+begin
35+ s := circle(2.0);
36+ Out.int(area(s)); Out.ln;
37+ s := rect(3.0, 4.0);
38+ Out.int(area(s)); Out.ln;
39+ grow(s);
40+ Out.int(area(s)); Out.ln;
41+ t := s;
42+ s := dot;
43+ Out.int(area(s)); Out.str(" "); Out.int(area(t)); Out.ln;
44+ shapes[0] := circle(1.0);
45+ shapes[1] := label("hi", 12);
46+ shapes[2] := dot;
47+ shapes[3] := rect(1.5, 2.0);
48+ for i := 0 to 3 do
49+ match shapes[i] of
50+ | label(text, size): Out.str(text); Out.int(size);
51+ | else: Out.int(area(shapes[i]));
52+ end;
53+ Out.str(" ");
54+ end;
55+ Out.ln;
56+ match z of
57+ | circle(r): Out.str("zero is a circle of "); Out.int(I64(r)); Out.ln;
58+ | else: Out.str("?");
59+ end;
60+ Out.int(SIZE(Shape)); Out.ln;
61+end;
62+
63+end Shapes.

test/run/Single.jed deleted +0 -81

@@ -1,81 +0,0 @@
1-(* F32: arithmetic rounded at each step, conversions, real constants
2- that take either type, calls to C and to code. *)
3-module Single;
4-import Out, C;
5-link "libm.so.6";
6-
7-const
8- third = 1.0 / 3.0; (* in double precision, then rounded once *)
9- tenth = 0.1;
10-
11-type
12- Vec = record x, y, z: F32; end;
13-
14-extern proc sqrtf(x: F32): F32;
15-extern proc fabsf(x: F32): F32;
16-extern proc sqrt(x: F64): F64;
17-
18-(* addss xmm0, xmm0; ret *)
19-proc twice(x: F32): F32;
20-code 0F3H, 0FH, 58H, 0C0H, 0C3H;
21-
22-proc dot(a, b: Vec): F32;
23-begin
24- return a.x * b.x + a.y * b.y + a.z * b.z;
25-end;
26-
27-proc mix(a: F32; n: I64; b: F64; c: F32): F64;
28-begin
29- return F64(a) + F64(n) + b + F64(c);
30-end;
31-
32-proc show(name: ^U8; x: F64);
33-begin
34- Out.flush;
35- C.printf("%s %.9g\n", name, x);
36- C.fflush(C.stdout);
37-end;
38-
39-proc main*;
40-var
41- a, b, s: F32; d: F64; v, w: Vec; i: I64; big: U64; arr: [4]F32;
42-begin
43- Out.int(SIZE(F32)); Out.char(' '); Out.int(SIZE(Vec)); Out.ln;
44- a := tenth;
45- b := 0.2;
46- show("a+b", F64(a + b));
47- d := tenth;
48- show("d+0.2", d + 0.2);
49- a := third;
50- show("third", F64(a));
51- a := 1.0;
52- b := 3.0;
53- show("1/3", F64(a / b));
54- s := 0.0;
55- for i := 1 to 10 do s := s + tenth; end;
56- show("ten tenths", F64(s));
57- if s # 1.0 then Out.str("not one\n"); end;
58- if (s > 0.9) and (s <= 1.1) and not (s < 0.0) then Out.str("near one\n"); end;
59- a := -a;
60- show("negated", F64(a));
61- show("I64(-2.75)", F64(I64(F32(-2.75))));
62- Out.int(I64(F32(1.0E10))); Out.ln;
63- big := 0FFFFFFFFFFFFFFFFH;
64- show("U64 max", F64(F32(big)));
65- show("I32 big", F64(F32(I32(16777217))));
66- show("F32(1E40)", F64(F32(d * 1.0E41)));
67- show("F32(1/3)", F64(F32(1.0 / 3.0)));
68- v := {x: 1.0, y: 2.0, z: 3.0};
69- w := {x: 0.5, y: 0.25, z: 2.0};
70- show("dot", F64(dot(v, w)));
71- show("sqrtf", F64(sqrtf(2.0)));
72- show("fabsf", F64(fabsf(-1.5)));
73- show("twice", F64(twice(1.25)));
74- show("mix", mix(1.5, 2, 0.25, 0.125));
75- for i := 0 to 3 do arr[i] := F32(i) * 0.5; end;
76- show("arr", F64(arr[3]));
77- C.printf("%f %f\n", F64(arr[1]), 0.5);
78- C.fflush(C.stdout);
79-end;
80-
81-end Single.

test/run/Single.raz (history) added +81 -0

@@ -0,0 +1,81 @@
1+(* F32: arithmetic rounded at each step, conversions, real constants
2+ that take either type, calls to C and to code. *)
3+module Single;
4+import Out, C;
5+link "libm.so.6";
6+
7+const
8+ third = 1.0 / 3.0; (* in double precision, then rounded once *)
9+ tenth = 0.1;
10+
11+type
12+ Vec = record x, y, z: F32; end;
13+
14+extern proc sqrtf(x: F32): F32;
15+extern proc fabsf(x: F32): F32;
16+extern proc sqrt(x: F64): F64;
17+
18+(* addss xmm0, xmm0; ret *)
19+proc twice(x: F32): F32;
20+code 0F3H, 0FH, 58H, 0C0H, 0C3H;
21+
22+proc dot(a, b: Vec): F32;
23+begin
24+ return a.x * b.x + a.y * b.y + a.z * b.z;
25+end;
26+
27+proc mix(a: F32; n: I64; b: F64; c: F32): F64;
28+begin
29+ return F64(a) + F64(n) + b + F64(c);
30+end;
31+
32+proc show(name: ^U8; x: F64);
33+begin
34+ Out.flush;
35+ C.printf("%s %.9g\n", name, x);
36+ C.fflush(C.stdout);
37+end;
38+
39+proc main*;
40+var
41+ a, b, s: F32; d: F64; v, w: Vec; i: I64; big: U64; arr: [4]F32;
42+begin
43+ Out.int(SIZE(F32)); Out.char(' '); Out.int(SIZE(Vec)); Out.ln;
44+ a := tenth;
45+ b := 0.2;
46+ show("a+b", F64(a + b));
47+ d := tenth;
48+ show("d+0.2", d + 0.2);
49+ a := third;
50+ show("third", F64(a));
51+ a := 1.0;
52+ b := 3.0;
53+ show("1/3", F64(a / b));
54+ s := 0.0;
55+ for i := 1 to 10 do s := s + tenth; end;
56+ show("ten tenths", F64(s));
57+ if s # 1.0 then Out.str("not one\n"); end;
58+ if (s > 0.9) and (s <= 1.1) and not (s < 0.0) then Out.str("near one\n"); end;
59+ a := -a;
60+ show("negated", F64(a));
61+ show("I64(-2.75)", F64(I64(F32(-2.75))));
62+ Out.int(I64(F32(1.0E10))); Out.ln;
63+ big := 0FFFFFFFFFFFFFFFFH;
64+ show("U64 max", F64(F32(big)));
65+ show("I32 big", F64(F32(I32(16777217))));
66+ show("F32(1E40)", F64(F32(d * 1.0E41)));
67+ show("F32(1/3)", F64(F32(1.0 / 3.0)));
68+ v := {x: 1.0, y: 2.0, z: 3.0};
69+ w := {x: 0.5, y: 0.25, z: 2.0};
70+ show("dot", F64(dot(v, w)));
71+ show("sqrtf", F64(sqrtf(2.0)));
72+ show("fabsf", F64(fabsf(-1.5)));
73+ show("twice", F64(twice(1.25)));
74+ show("mix", mix(1.5, 2, 0.25, 0.125));
75+ for i := 0 to 3 do arr[i] := F32(i) * 0.5; end;
76+ show("arr", F64(arr[3]));
77+ C.printf("%f %f\n", F64(arr[1]), 0.5);
78+ C.fflush(C.stdout);
79+end;
80+
81+end Single.

test/run/Spawn.jed deleted +0 -50

@@ -1,50 +0,0 @@
1-(* Native threads: a counter under a Mutex, the heap and Out used from
2- every thread at once, and join. *)
3-module Spawn;
4-import Out, Thread, Heap, Mem;
5-
6-const
7- Workers = 8;
8- Rounds = 20000;
9-
10-type Node = record next: ^Node; n: I64; end;
11-
12-var
13- m: Thread.Mutex;
14- count, atomic: I64;
15-
16-proc work(arg: ^U8);
17-var i: I64; p, list: ^Node;
18-begin
19- list := nil;
20- for i := 1 to Rounds do
21- Thread.lock(ADR(m));
22- INC(count);
23- Thread.unlock(ADR(m));
24- XADD(ADR(atomic), 1);
25- NEW(p, Heap.heap);
26- p^.next := list;
27- list := p;
28- if i mod 4 = 0 then
29- while list # nil do
30- p := list^.next;
31- Mem.free(Heap.heap, ^U8(list));
32- list := p;
33- end;
34- end;
35- end;
36- for i := 1 to 25 do Out.str("the same line from every thread\n"); end;
37-end;
38-
39-proc main*;
40-var t: [Workers]^Thread.Thread; i: I64; err: ERROR;
41-begin
42- for i := 0 to Workers - 1 do
43- t[i], err := Thread.spawn(work, nil);
44- if err # nil then Out.str(MSG(err)); Out.ln; return; end;
45- end;
46- for i := 0 to Workers - 1 do Thread.join(t[i]); end;
47- Out.int(count); Out.char(' '); Out.int(atomic); Out.ln;
48-end;
49-
50-end Spawn.

test/run/Spawn.raz (history) added +50 -0

@@ -0,0 +1,50 @@
1+(* Native threads: a counter under a Mutex, the heap and Out used from
2+ every thread at once, and join. *)
3+module Spawn;
4+import Out, Thread, Heap, Mem;
5+
6+const
7+ Workers = 8;
8+ Rounds = 20000;
9+
10+type Node = record next: ^Node; n: I64; end;
11+
12+var
13+ m: Thread.Mutex;
14+ count, atomic: I64;
15+
16+proc work(arg: ^U8);
17+var i: I64; p, list: ^Node;
18+begin
19+ list := nil;
20+ for i := 1 to Rounds do
21+ Thread.lock(ADR(m));
22+ INC(count);
23+ Thread.unlock(ADR(m));
24+ XADD(ADR(atomic), 1);
25+ NEW(p, Heap.heap);
26+ p^.next := list;
27+ list := p;
28+ if i mod 4 = 0 then
29+ while list # nil do
30+ p := list^.next;
31+ Mem.free(Heap.heap, ^U8(list));
32+ list := p;
33+ end;
34+ end;
35+ end;
36+ for i := 1 to 25 do Out.str("the same line from every thread\n"); end;
37+end;
38+
39+proc main*;
40+var t: [Workers]^Thread.Thread; i: I64; err: ERROR;
41+begin
42+ for i := 0 to Workers - 1 do
43+ t[i], err := Thread.spawn(work, nil);
44+ if err # nil then Out.str(MSG(err)); Out.ln; return; end;
45+ end;
46+ for i := 0 to Workers - 1 do Thread.join(t[i]); end;
47+ Out.int(count); Out.char(' '); Out.int(atomic); Out.ln;
48+end;
49+
50+end Spawn.

test/run/Strings.jed deleted +0 -39

@@ -1,39 +0,0 @@
1-module Strings;
2-import Out;
3-
4-const greeting = "hello";
5-
6-var buf: [8]U8;
7-
8-proc count(xs: []I64): I64;
9-var i, s: I64;
10-begin
11- s := 0;
12- for i := 0 to LEN(xs) - 1 do s := s + xs[i]; end;
13- return s;
14-end;
15-
16-proc main*;
17-var a: []U8; b: [5]U8; c: [3]I64; d: [][]U8;
18-begin
19- a := "hello";
20- if a = greeting then Out.str("eq "); end;
21- if a # "help" then Out.str("ne "); end;
22- if "abc" = "abc" then Out.str("lit "); end;
23- b := "hello";
24- if b = a then Out.str("arr "); end;
25- buf := "hi";
26- if buf[0..2] = "hi" then Out.str("buf "); end;
27- Out.int(I64(buf[5])); Out.str(" ");
28- Out.int(LEN(greeting)); Out.str(" ");
29- Out.int(LEN(a[1..3])); Out.ln;
30- c := [1, 2, 3];
31- Out.int(count(c)); Out.str(" ");
32- Out.int(count([10, 20, 30, 40])); Out.str(" ");
33- Out.int(count([])); Out.ln;
34- d := ["one", "two", "three"];
35- Out.str(d[2]); Out.str(d[0]); Out.ln;
36- Out.str("é\u{263A}\x41\n");
37-end;
38-
39-end Strings.

test/run/Strings.raz added +39 -0

@@ -0,0 +1,39 @@
1+module Strings;
2+import Out;
3+
4+const greeting = "hello";
5+
6+var buf: [8]U8;
7+
8+proc count(xs: []I64): I64;
9+var i, s: I64;
10+begin
11+ s := 0;
12+ for i := 0 to LEN(xs) - 1 do s := s + xs[i]; end;
13+ return s;
14+end;
15+
16+proc main*;
17+var a: []U8; b: [5]U8; c: [3]I64; d: [][]U8;
18+begin
19+ a := "hello";
20+ if a = greeting then Out.str("eq "); end;
21+ if a # "help" then Out.str("ne "); end;
22+ if "abc" = "abc" then Out.str("lit "); end;
23+ b := "hello";
24+ if b = a then Out.str("arr "); end;
25+ buf := "hi";
26+ if buf[0..2] = "hi" then Out.str("buf "); end;
27+ Out.int(I64(buf[5])); Out.str(" ");
28+ Out.int(LEN(greeting)); Out.str(" ");
29+ Out.int(LEN(a[1..3])); Out.ln;
30+ c := [1, 2, 3];
31+ Out.int(count(c)); Out.str(" ");
32+ Out.int(count([10, 20, 30, 40])); Out.str(" ");
33+ Out.int(count([])); Out.ln;
34+ d := ["one", "two", "three"];
35+ Out.str(d[2]); Out.str(d[0]); Out.ln;
36+ Out.str("é\u{263A}\x41\n");
37+end;
38+
39+end Strings.

test/run/Target.jed deleted +0 -11

@@ -1,11 +0,0 @@
1-module Target;
2-import Out, Plat;
3-
4-proc main*;
5-var i: Plat.Info;
6-begin
7- i.kind := 41;
8- Out.str(Plat.name); Out.int(Plat.id(i.kind)); Out.ln;
9-end;
10-
11-end Target.

test/run/Target.raz (history) added +11 -0

@@ -0,0 +1,11 @@
1+module Target;
2+import Out, Plat;
3+
4+proc main*;
5+var i: Plat.Info;
6+begin
7+ i.kind := 41;
8+ Out.str(Plat.name); Out.int(Plat.id(i.kind)); Out.ln;
9+end;
10+
11+end Target.

test/run/mods/First.jed deleted +0 -14

@@ -1,14 +0,0 @@
1-module First;
2-import Out;
3-
4-var count*: I64;
5-
6-proc main*;
7-begin
8- Out.str("First.main must not run");
9-end;
10-
11-begin
12- count := 1;
13- Out.str("First ");
14-end First.

test/run/mods/First.raz added +14 -0

@@ -0,0 +1,14 @@
1+module First;
2+import Out;
3+
4+var count*: I64;
5+
6+proc main*;
7+begin
8+ Out.str("First.main must not run");
9+end;
10+
11+begin
12+ count := 1;
13+ Out.str("First ");
14+end First.

test/run/mods/Plat.linux-x86_64.jed deleted +0 -5

@@ -1,5 +0,0 @@
1-module Plat;
2-const name* = "linux";
3-type Info* = record kind*: I64; extra: I64; end;
4-proc id*(x: I64): I64; begin return x + 1; end;
5-end Plat.

test/run/mods/Plat.linux-x86_64.raz (history) added +5 -0

@@ -0,0 +1,5 @@
1+module Plat;
2+const name* = "linux";
3+type Info* = record kind*: I64; extra: I64; end;
4+proc id*(x: I64): I64; begin return x + 1; end;
5+end Plat.

test/run/mods/Plat.macos-aarch64.jed deleted +0 -5

@@ -1,5 +0,0 @@
1-module Plat;
2-const name* = "macos";
3-type Info* = record kind*: I64; other: U8; end;
4-proc id*(x: I64): I64; begin return SOMETHING_UNKNOWN_HERE(x); end;
5-end Plat.

test/run/mods/Plat.macos-aarch64.raz (history) added +5 -0

@@ -0,0 +1,5 @@
1+module Plat;
2+const name* = "macos";
3+type Info* = record kind*: I64; other: U8; end;
4+proc id*(x: I64): I64; begin return SOMETHING_UNKNOWN_HERE(x); end;
5+end Plat.

test/run/mods/Second.jed deleted +0 -11

@@ -1,11 +0,0 @@
1-module Second;
2-import Out, First;
3-
4-var count*: I64;
5-
6-begin
7- count := First.count + 1;
8- Out.str("Second ");
9- if count = 2 then return; end;
10- Out.str("not reached");
11-end Second.

test/run/mods/Second.raz added +11 -0

@@ -0,0 +1,11 @@
1+module Second;
2+import Out, First;
3+
4+var count*: I64;
5+
6+begin
7+ count := First.count + 1;
8+ Out.str("Second ");
9+ if count = 2 then return; end;
10+ Out.str("not reached");
11+end Second.

test/run/mods/Stack.jed deleted +0 -13

@@ -1,13 +0,0 @@
1-module Stack;
2-import Ints := List(I64), Heap;
3-
4-var s*: Ints.List;
5-
6-proc top*(): I64;
7-begin
8- return s.head^.val;
9-end;
10-
11-begin
12- Ints.init(ADR(s), Heap.heap);
13-end Stack.

test/run/mods/Stack.raz added +13 -0

@@ -0,0 +1,13 @@
1+module Stack;
2+import Ints := List(I64), Heap;
3+
4+var s*: Ints.List;
5+
6+proc top*(): I64;
7+begin
8+ return s.head^.val;
9+end;
10+
11+begin
12+ Ints.init(ADR(s), Heap.heap);
13+end Stack.

tools/Doc.jed deleted +0 -309

@@ -1,309 +0,0 @@
1-(* Doc: what a module offers, from its source.
2-
3- Doc Module.jed
4- prints the module's own comment, the one just before module, then
5- each exported declaration as it is written, with the comment just
6- before it.
7-
8- Doc examples report.md dir
9- writes each example of the report that is a whole module, from
10- module to end, with no ... left out, to dir/Name.jed, and prints
11- the names, one a line. *)
12-module Doc;
13-import Out, Rt, Str, Buf, Heap, Scan, Files;
14-
15-var
16- sc: Scan.Scanner; (* the text being read, at the current symbol *)
17- src: []U8;
18- docStart, docEnd: I64; (* the comment just before it, or -1 *)
19-
20-(* On to the next symbol that isn't a comment, keeping where the last
21- comment that starts a line was: one after code on its line belongs
22- to that code. *)
23-proc next;
24-var newLine: BOOL;
25-begin
26- docStart := -1;
27- newLine := false;
28- repeat
29- Scan.next(ADR(sc));
30- newLine := newLine or sc.lineBreak;
31- if (sc.kind = Scan.comment) and newLine then
32- docStart := sc.start; docEnd := sc.stop;
33- end;
34- until sc.kind # Scan.comment;
35-end;
36-
37-proc text: []U8;
38-begin
39- return Scan.text(ADR(sc));
40-end;
41-
42-proc is(s: []U8): BOOL;
43-begin
44- return text() = s;
45-end;
46-
47-(* Whether the current word starts a declaration, a section or the end. *)
48-proc reserved: BOOL;
49-begin
50- return is("const") or is("type") or is("var") or is("proc") or is("extern")
51- or is("import") or is("link") or is("begin") or is("end");
52-end;
53-
54-(* On to the ; that ends what starts here, past anything bracketed and
55- any record or variant; returns where it ends. *)
56-proc toSemicolon: I64;
57-var depth: I64;
58-begin
59- depth := 0;
60- while sc.kind # Scan.eof do
61- if is("(") or is("[") or is("{") or is("record") or is("variant") then INC(depth);
62- elsif is(")") or is("]") or is("}") or is("end") then DEC(depth);
63- elsif is(";") and (depth <= 0) then return sc.stop;
64- end;
65- next;
66- end;
67- return sc.pos;
68-end;
69-
70-(* stop, or the end of a comment that follows it on its line. *)
71-proc trailing(stop: I64): I64;
72-var t: Scan.Scanner;
73-begin
74- while (stop < LEN(src)) and ((src[stop] = ' ') or (src[stop] = 9)) do INC(stop); end;
75- t := sc;
76- t.pos := stop;
77- Scan.next(ADR(t));
78- if (t.kind = Scan.comment) and (t.start = stop) then return t.stop; end;
79- return stop;
80-end;
81-
82-(* Where the line holding p starts. *)
83-proc lineStart(p: I64): I64;
84-begin
85- while (p > 0) and (src[p - 1] # 10) do DEC(p); end;
86- return p;
87-end;
88-
89-(* src[start..stop] as written, each line after the first moved left as
90- far as the first one's column. *)
91-proc block(start, stop: I64);
92-var col, i, n: I64;
93-begin
94- col := start - lineStart(start);
95- i := start;
96- while i < stop do
97- Out.char(src[i]);
98- if src[i] = 10 then
99- n := 0;
100- while (n < col) and (i + 1 < stop) and (src[i + 1] = ' ') do INC(i); INC(n); end;
101- end;
102- INC(i);
103- end;
104- Out.ln;
105-end;
106-
107-(* The comment from start to stop, without its brackets, each line
108- indented by four. *)
109-proc comment(start, stop: I64);
110-var i, j: I64; atLine: BOOL;
111-begin
112- if start < 0 then return; end;
113- i := start + 2;
114- j := stop - 2;
115- while (i < j) and Scan.isSpace(src[i]) do INC(i); end;
116- while (j > i) and Scan.isSpace(src[j - 1]) do DEC(j); end;
117- atLine := true;
118- while i < j do
119- if atLine then Out.str(" "); atLine := false; end;
120- Out.char(src[i]);
121- if src[i] = 10 then
122- atLine := true;
123- while (i + 1 < j) and (src[i + 1] = ' ') do INC(i); end;
124- end;
125- INC(i);
126- end;
127- Out.ln;
128-end;
129-
130-(* One declaration, from its first token, the comment before it kept. *)
131-proc declaration(prefix: []U8; exported: BOOL; start, ds, de, stop: I64);
132-begin
133- if not exported then return; end;
134- Out.ln;
135- Out.str(prefix);
136- block(start, trailing(stop));
137- comment(ds, de);
138-end;
139-
140-(* name, and whether a * follows it; leaves the token after them. *)
141-proc name: BOOL;
142-begin
143- next;
144- next;
145- if is("*") then next; return true; end;
146- return false;
147-end;
148-
149-(* A procedure's body: to the end that closes its begin, the procedure
150- name after it and its ;. *)
151-proc skipBody;
152-var depth: I64; sawBegin: BOOL;
153-begin
154- depth := 0;
155- sawBegin := false;
156- while sc.kind # Scan.eof do
157- if is("begin") then
158- if depth = 0 then sawBegin := true; end;
159- INC(depth);
160- elsif is("if") or is("while") or is("for") or is("match") or is("record") or is("variant") then
161- INC(depth);
162- elsif is("end") then
163- DEC(depth);
164- if (depth = 0) and sawBegin then
165- next;
166- if sc.kind = Scan.word then next; end;
167- return;
168- end;
169- end;
170- next;
171- end;
172-end;
173-
174-proc procedure;
175-var start, ds, de, stop: I64; exp: BOOL;
176-begin
177- start := sc.start; ds := docStart; de := docEnd;
178- exp := name();
179- stop := toSemicolon();
180- next;
181- if is("forward") or is("code") then toSemicolon();
182- else skipBody;
183- end;
184- declaration("", exp, start, ds, de, stop);
185- next;
186-end;
187-
188-proc section;
189-var word: []U8; start, ds, de, stop: I64; exp: BOOL;
190-begin
191- word := text();
192- next;
193- while (sc.kind = Scan.word) and not reserved() do
194- start := sc.start; ds := docStart; de := docEnd;
195- sc.pos := sc.start; (* name reads the name again *)
196- exp := name();
197- stop := toSemicolon();
198- if exp then
199- Out.ln;
200- Out.str(word); Out.str(" ");
201- block(start, trailing(stop));
202- comment(ds, de);
203- end;
204- next;
205- end;
206-end;
207-
208-proc external;
209-var start, ds, de, stop: I64; exp: BOOL;
210-begin
211- start := sc.start; ds := docStart; de := docEnd;
212- next;
213- exp := name();
214- stop := toSemicolon();
215- declaration("", exp, start, ds, de, stop);
216- next;
217-end;
218-
219-proc document(path: []U8);
220-var b: Buf.Buf; start, ds, de: I64;
221-begin
222- Buf.init(ADR(b), Heap.heap);
223- if not Files.read(path, ADR(b)) then Rt.stop("Doc: can't read the file"); end;
224- src := Buf.bytes(ADR(b));
225- Scan.init(ADR(sc), src);
226- next;
227- while (sc.kind # Scan.eof) and not is("module") do next; end;
228- if sc.kind = Scan.eof then Rt.stop("Doc: no module"); end;
229- start := sc.start;
230- ds := docStart; de := docEnd;
231- block(start, toSemicolon());
232- comment(ds, de);
233- next;
234- while (sc.kind # Scan.eof) and not is("begin") and not is("end") do
235- if is("const") or is("type") or is("var") then section;
236- elsif is("proc") then procedure;
237- elsif is("extern") then external;
238- elsif is("import") or is("link") then toSemicolon(); next;
239- else next;
240- end;
241- end;
242-end;
243-
244-(* line, without the spaces at its ends *)
245-proc trim(line: []U8): []U8;
246-var i, j: I64;
247-begin
248- i := 0;
249- j := LEN(line);
250- while (i < j) and Scan.isSpace(line[i]) do INC(i); end;
251- while (j > i) and Scan.isSpace(line[j - 1]) do DEC(j); end;
252- return line[i..j];
253-end;
254-
255-(* The report's examples that are whole modules, each to dir. *)
256-proc examples(path, dir: []U8);
257-var
258- b, out: Buf.Buf; s, line, first, last, name: []U8; i, start, k, n: I64;
259- inBlock, whole: BOOL;
260-begin
261- Buf.init(ADR(b), Heap.heap);
262- Buf.init(ADR(out), Heap.heap);
263- if not Files.read(path, ADR(b)) then Rt.stop("Doc: can't read the report"); end;
264- s := Buf.bytes(ADR(b));
265- inBlock := false;
266- start := 0;
267- i := 0;
268- while i < LEN(s) do
269- k := i;
270- while (k < LEN(s)) and (s[k] # 10) do INC(k); end;
271- line := s[i..k];
272- if trim(line) = "```" then
273- if inBlock and whole and Str.hasPrefix(first, "module ") and Str.hasPrefix(last, "end ") then
274- name := first[7..LEN(first)];
275- n := 0;
276- while (n < LEN(name)) and Scan.isWord(name[n]) do INC(n); end;
277- name := name[0..n];
278- Buf.reset(ADR(out));
279- Buf.str(ADR(out), dir); Buf.str(ADR(out), "/"); Buf.str(ADR(out), name);
280- Buf.str(ADR(out), ".jed");
281- if not Files.write(Buf.bytes(ADR(out)), s[start..i]) then
282- Rt.stop("Doc: can't write an example");
283- end;
284- Out.str(name); Out.ln;
285- end;
286- inBlock := not inBlock;
287- start := k + 1;
288- first := ""; last := "";
289- whole := true;
290- elsif inBlock then
291- if trim(line) = "..." then whole := false; end;
292- if LEN(trim(line)) > 0 then
293- if LEN(first) = 0 then first := trim(line); end;
294- last := trim(line);
295- end;
296- end;
297- i := k + 1;
298- end;
299-end;
300-
301-proc main*;
302-begin
303- if (ARGC() = 4) and (Files.arg(1) = "examples") then examples(Files.arg(2), Files.arg(3));
304- elsif ARGC() = 2 then document(Files.arg(1));
305- else Rt.stop("usage: Doc Module.jed, or Doc examples report.md dir");
306- end;
307-end;
308-
309-end Doc.

tools/Doc.raz (history) added +309 -0

@@ -0,0 +1,309 @@
1+(* Doc: what a module offers, from its source.
2+
3+ Doc Module.raz
4+ prints the module's own comment, the one just before module, then
5+ each exported declaration as it is written, with the comment just
6+ before it.
7+
8+ Doc examples report.md dir
9+ writes each example of the report that is a whole module, from
10+ module to end, with no ... left out, to dir/Name.raz, and prints
11+ the names, one a line. *)
12+module Doc;
13+import Out, Rt, Str, Buf, Heap, Scan, Files;
14+
15+var
16+ sc: Scan.Scanner; (* the text being read, at the current symbol *)
17+ src: []U8;
18+ docStart, docEnd: I64; (* the comment just before it, or -1 *)
19+
20+(* On to the next symbol that isn't a comment, keeping where the last
21+ comment that starts a line was: one after code on its line belongs
22+ to that code. *)
23+proc next;
24+var newLine: BOOL;
25+begin
26+ docStart := -1;
27+ newLine := false;
28+ repeat
29+ Scan.next(ADR(sc));
30+ newLine := newLine or sc.lineBreak;
31+ if (sc.kind = Scan.comment) and newLine then
32+ docStart := sc.start; docEnd := sc.stop;
33+ end;
34+ until sc.kind # Scan.comment;
35+end;
36+
37+proc text: []U8;
38+begin
39+ return Scan.text(ADR(sc));
40+end;
41+
42+proc is(s: []U8): BOOL;
43+begin
44+ return text() = s;
45+end;
46+
47+(* Whether the current word starts a declaration, a section or the end. *)
48+proc reserved: BOOL;
49+begin
50+ return is("const") or is("type") or is("var") or is("proc") or is("extern")
51+ or is("import") or is("link") or is("begin") or is("end");
52+end;
53+
54+(* On to the ; that ends what starts here, past anything bracketed and
55+ any record or variant; returns where it ends. *)
56+proc toSemicolon: I64;
57+var depth: I64;
58+begin
59+ depth := 0;
60+ while sc.kind # Scan.eof do
61+ if is("(") or is("[") or is("{") or is("record") or is("variant") then INC(depth);
62+ elsif is(")") or is("]") or is("}") or is("end") then DEC(depth);
63+ elsif is(";") and (depth <= 0) then return sc.stop;
64+ end;
65+ next;
66+ end;
67+ return sc.pos;
68+end;
69+
70+(* stop, or the end of a comment that follows it on its line. *)
71+proc trailing(stop: I64): I64;
72+var t: Scan.Scanner;
73+begin
74+ while (stop < LEN(src)) and ((src[stop] = ' ') or (src[stop] = 9)) do INC(stop); end;
75+ t := sc;
76+ t.pos := stop;
77+ Scan.next(ADR(t));
78+ if (t.kind = Scan.comment) and (t.start = stop) then return t.stop; end;
79+ return stop;
80+end;
81+
82+(* Where the line holding p starts. *)
83+proc lineStart(p: I64): I64;
84+begin
85+ while (p > 0) and (src[p - 1] # 10) do DEC(p); end;
86+ return p;
87+end;
88+
89+(* src[start..stop] as written, each line after the first moved left as
90+ far as the first one's column. *)
91+proc block(start, stop: I64);
92+var col, i, n: I64;
93+begin
94+ col := start - lineStart(start);
95+ i := start;
96+ while i < stop do
97+ Out.char(src[i]);
98+ if src[i] = 10 then
99+ n := 0;
100+ while (n < col) and (i + 1 < stop) and (src[i + 1] = ' ') do INC(i); INC(n); end;
101+ end;
102+ INC(i);
103+ end;
104+ Out.ln;
105+end;
106+
107+(* The comment from start to stop, without its brackets, each line
108+ indented by four. *)
109+proc comment(start, stop: I64);
110+var i, j: I64; atLine: BOOL;
111+begin
112+ if start < 0 then return; end;
113+ i := start + 2;
114+ j := stop - 2;
115+ while (i < j) and Scan.isSpace(src[i]) do INC(i); end;
116+ while (j > i) and Scan.isSpace(src[j - 1]) do DEC(j); end;
117+ atLine := true;
118+ while i < j do
119+ if atLine then Out.str(" "); atLine := false; end;
120+ Out.char(src[i]);
121+ if src[i] = 10 then
122+ atLine := true;
123+ while (i + 1 < j) and (src[i + 1] = ' ') do INC(i); end;
124+ end;
125+ INC(i);
126+ end;
127+ Out.ln;
128+end;
129+
130+(* One declaration, from its first token, the comment before it kept. *)
131+proc declaration(prefix: []U8; exported: BOOL; start, ds, de, stop: I64);
132+begin
133+ if not exported then return; end;
134+ Out.ln;
135+ Out.str(prefix);
136+ block(start, trailing(stop));
137+ comment(ds, de);
138+end;
139+
140+(* name, and whether a * follows it; leaves the token after them. *)
141+proc name: BOOL;
142+begin
143+ next;
144+ next;
145+ if is("*") then next; return true; end;
146+ return false;
147+end;
148+
149+(* A procedure's body: to the end that closes its begin, the procedure
150+ name after it and its ;. *)
151+proc skipBody;
152+var depth: I64; sawBegin: BOOL;
153+begin
154+ depth := 0;
155+ sawBegin := false;
156+ while sc.kind # Scan.eof do
157+ if is("begin") then
158+ if depth = 0 then sawBegin := true; end;
159+ INC(depth);
160+ elsif is("if") or is("while") or is("for") or is("match") or is("record") or is("variant") then
161+ INC(depth);
162+ elsif is("end") then
163+ DEC(depth);
164+ if (depth = 0) and sawBegin then
165+ next;
166+ if sc.kind = Scan.word then next; end;
167+ return;
168+ end;
169+ end;
170+ next;
171+ end;
172+end;
173+
174+proc procedure;
175+var start, ds, de, stop: I64; exp: BOOL;
176+begin
177+ start := sc.start; ds := docStart; de := docEnd;
178+ exp := name();
179+ stop := toSemicolon();
180+ next;
181+ if is("forward") or is("code") then toSemicolon();
182+ else skipBody;
183+ end;
184+ declaration("", exp, start, ds, de, stop);
185+ next;
186+end;
187+
188+proc section;
189+var word: []U8; start, ds, de, stop: I64; exp: BOOL;
190+begin
191+ word := text();
192+ next;
193+ while (sc.kind = Scan.word) and not reserved() do
194+ start := sc.start; ds := docStart; de := docEnd;
195+ sc.pos := sc.start; (* name reads the name again *)
196+ exp := name();
197+ stop := toSemicolon();
198+ if exp then
199+ Out.ln;
200+ Out.str(word); Out.str(" ");
201+ block(start, trailing(stop));
202+ comment(ds, de);
203+ end;
204+ next;
205+ end;
206+end;
207+
208+proc external;
209+var start, ds, de, stop: I64; exp: BOOL;
210+begin
211+ start := sc.start; ds := docStart; de := docEnd;
212+ next;
213+ exp := name();
214+ stop := toSemicolon();
215+ declaration("", exp, start, ds, de, stop);
216+ next;
217+end;
218+
219+proc document(path: []U8);
220+var b: Buf.Buf; start, ds, de: I64;
221+begin
222+ Buf.init(ADR(b), Heap.heap);
223+ if not Files.read(path, ADR(b)) then Rt.stop("Doc: can't read the file"); end;
224+ src := Buf.bytes(ADR(b));
225+ Scan.init(ADR(sc), src);
226+ next;
227+ while (sc.kind # Scan.eof) and not is("module") do next; end;
228+ if sc.kind = Scan.eof then Rt.stop("Doc: no module"); end;
229+ start := sc.start;
230+ ds := docStart; de := docEnd;
231+ block(start, toSemicolon());
232+ comment(ds, de);
233+ next;
234+ while (sc.kind # Scan.eof) and not is("begin") and not is("end") do
235+ if is("const") or is("type") or is("var") then section;
236+ elsif is("proc") then procedure;
237+ elsif is("extern") then external;
238+ elsif is("import") or is("link") then toSemicolon(); next;
239+ else next;
240+ end;
241+ end;
242+end;
243+
244+(* line, without the spaces at its ends *)
245+proc trim(line: []U8): []U8;
246+var i, j: I64;
247+begin
248+ i := 0;
249+ j := LEN(line);
250+ while (i < j) and Scan.isSpace(line[i]) do INC(i); end;
251+ while (j > i) and Scan.isSpace(line[j - 1]) do DEC(j); end;
252+ return line[i..j];
253+end;
254+
255+(* The report's examples that are whole modules, each to dir. *)
256+proc examples(path, dir: []U8);
257+var
258+ b, out: Buf.Buf; s, line, first, last, name: []U8; i, start, k, n: I64;
259+ inBlock, whole: BOOL;
260+begin
261+ Buf.init(ADR(b), Heap.heap);
262+ Buf.init(ADR(out), Heap.heap);
263+ if not Files.read(path, ADR(b)) then Rt.stop("Doc: can't read the report"); end;
264+ s := Buf.bytes(ADR(b));
265+ inBlock := false;
266+ start := 0;
267+ i := 0;
268+ while i < LEN(s) do
269+ k := i;
270+ while (k < LEN(s)) and (s[k] # 10) do INC(k); end;
271+ line := s[i..k];
272+ if trim(line) = "```" then
273+ if inBlock and whole and Str.hasPrefix(first, "module ") and Str.hasPrefix(last, "end ") then
274+ name := first[7..LEN(first)];
275+ n := 0;
276+ while (n < LEN(name)) and Scan.isWord(name[n]) do INC(n); end;
277+ name := name[0..n];
278+ Buf.reset(ADR(out));
279+ Buf.str(ADR(out), dir); Buf.str(ADR(out), "/"); Buf.str(ADR(out), name);
280+ Buf.str(ADR(out), ".raz");
281+ if not Files.write(Buf.bytes(ADR(out)), s[start..i]) then
282+ Rt.stop("Doc: can't write an example");
283+ end;
284+ Out.str(name); Out.ln;
285+ end;
286+ inBlock := not inBlock;
287+ start := k + 1;
288+ first := ""; last := "";
289+ whole := true;
290+ elsif inBlock then
291+ if trim(line) = "..." then whole := false; end;
292+ if LEN(trim(line)) > 0 then
293+ if LEN(first) = 0 then first := trim(line); end;
294+ last := trim(line);
295+ end;
296+ end;
297+ i := k + 1;
298+ end;
299+end;
300+
301+proc main*;
302+begin
303+ if (ARGC() = 4) and (Files.arg(1) = "examples") then examples(Files.arg(2), Files.arg(3));
304+ elsif ARGC() = 2 then document(Files.arg(1));
305+ else Rt.stop("usage: Doc Module.raz, or Doc examples report.md dir");
306+ end;
307+end;
308+
309+end Doc.

tools/Files.jed deleted +0 -46

@@ -1,46 +0,0 @@
1-(* Files: what the tools need of the command line and of files: an
2- argument as a string, and a whole file read or written. *)
3-module Files;
4-import Sys, Buf;
5-
6-(* Argument i, a C string, as a slice. *)
7-proc arg*(i: I64): []U8;
8-var s: ^U8; n: I64;
9-begin
10- s := ARGV()[i];
11- n := 0;
12- while s[n] # 0 do INC(n); end;
13- return s[0..n];
14-end;
15-
16-(* Adds the file at path to b; false if it can't be read. *)
17-proc read*(path: []U8; b: ^Buf.Buf): BOOL;
18-var fd, n: I64; chunk: [4096]U8;
19-begin
20- fd := Sys.openRead(path);
21- if fd < 0 then return false; end;
22- repeat
23- n := Sys.read(fd, chunk);
24- if n > 0 then Buf.str(b, chunk[0..n]); end;
25- until n <= 0;
26- Sys.close(fd);
27- return n = 0;
28-end;
29-
30-(* Makes the file at path hold data; false if it can't be written. *)
31-proc write*(path, data: []U8): BOOL;
32-var fd, n, at: I64;
33-begin
34- fd := Sys.create(path);
35- if fd < 0 then return false; end;
36- at := 0;
37- while at < LEN(data) do
38- n := Sys.write(fd, data[at..LEN(data)]);
39- if n <= 0 then Sys.close(fd); return false; end;
40- at := at + n;
41- end;
42- Sys.close(fd);
43- return true;
44-end;
45-
46-end Files.

tools/Files.raz added +46 -0

@@ -0,0 +1,46 @@
1+(* Files: what the tools need of the command line and of files: an
2+ argument as a string, and a whole file read or written. *)
3+module Files;
4+import Sys, Buf;
5+
6+(* Argument i, a C string, as a slice. *)
7+proc arg*(i: I64): []U8;
8+var s: ^U8; n: I64;
9+begin
10+ s := ARGV()[i];
11+ n := 0;
12+ while s[n] # 0 do INC(n); end;
13+ return s[0..n];
14+end;
15+
16+(* Adds the file at path to b; false if it can't be read. *)
17+proc read*(path: []U8; b: ^Buf.Buf): BOOL;
18+var fd, n: I64; chunk: [4096]U8;
19+begin
20+ fd := Sys.openRead(path);
21+ if fd < 0 then return false; end;
22+ repeat
23+ n := Sys.read(fd, chunk);
24+ if n > 0 then Buf.str(b, chunk[0..n]); end;
25+ until n <= 0;
26+ Sys.close(fd);
27+ return n = 0;
28+end;
29+
30+(* Makes the file at path hold data; false if it can't be written. *)
31+proc write*(path, data: []U8): BOOL;
32+var fd, n, at: I64;
33+begin
34+ fd := Sys.create(path);
35+ if fd < 0 then return false; end;
36+ at := 0;
37+ while at < LEN(data) do
38+ n := Sys.write(fd, data[at..LEN(data)]);
39+ if n <= 0 then Sys.close(fd); return false; end;
40+ at := at + n;
41+ end;
42+ Sys.close(fd);
43+ return true;
44+end;
45+
46+end Files.

tools/Pretty.jed deleted +0 -339

@@ -1,339 +0,0 @@
1-(* Pretty: jed source laid out the one way.
2-
3- Pretty Module.jed
4- prints the module, formatted.
5-
6- Pretty -w File.jed...
7- rewrites each file that isn't formatted already.
8-
9- Every line break and comment stays where it is. A line is indented
10- 4 spaces for each block it stands in: the statements of if, while,
11- for, repeat and begin, the fields of a record or variant, the
12- declarations of const, type and var. end, until, else, elsif and a
13- match's arms stand at the level of the statement that opened them;
14- module, import, proc, the sections and begin at the margin, with the
15- comment just before them. A line that goes on with the expression of
16- the line before keeps its indent, moved as far as the statement's
17- first line moved; so does the text of a comment.
18-
19- Within a line, a binary operator has one space on each side, a unary
20- minus none after it, and , and ; none before them and one after. A
21- comment after code keeps its column. Other spaces stay as written,
22- so that lined-up match arms stay lined up. No line ends in spaces. *)
23-module Pretty;
24-import Out, Rt, Buf, Heap, Scan, Files;
25-
26-const
27- width = 4; (* the spaces of a level *)
28- openers = "if while for match record variant begin repeat";
29- declarations = "module import link extern proc const type var begin code";
30- binaryWords = "div mod and or xor shl shr in";
31- binarySymbols = "+ - * / = # < <= > >= :=";
32-
33-var
34- sc: Scan.Scanner; (* the source, at the symbol being written *)
35- src: []U8;
36- out: Buf.Buf;
37- lineAt: I64; (* where the line being written starts in out *)
38- lineDelta: I64; (* how far this line's indent moved *)
39-
40- (* the blocks open, each with the indent of the statement that
41- opened it *)
42- bases: [100]I64;
43- depth: I64;
44- brackets: I64; (* brackets open *)
45- inSection: BOOL; (* among the declarations of const, type or var *)
46- stmtIndent: I64; (* the indent of the current statement's first line *)
47- stmtDelta: I64; (* and how far that moved *)
48-
49- (* the last symbol that wasn't a comment, and the one before it *)
50- prev, prev2: Scan.Scanner;
51- prevBinary, prevUnary: BOOL;
52- afterComment: BOOL; (* the last symbol written was a comment *)
53- last: I64; (* where the last symbol written ends in src *)
54-
55-proc spaces(n: I64);
56-begin
57- while n > 0 do Buf.add(ADR(out), ' '); DEC(n); end;
58-end;
59-
60-(* Drops the spaces at the end of the line in out. *)
61-proc trim;
62-var s: []U8;
63-begin
64- s := Buf.bytes(ADR(out));
65- while (out.len > lineAt) and ((s[out.len - 1] = ' ') or (s[out.len - 1] = '\t')) do
66- DEC(out.len);
67- end;
68-end;
69-
70-proc newLine;
71-begin
72- trim;
73- Buf.add(ADR(out), '\n');
74- lineAt := out.len;
75-end;
76-
77-(* Where the line holding p starts in src. *)
78-proc lineStart(p: I64): I64;
79-begin
80- while (p > 0) and (src[p - 1] # '\n') do DEC(p); end;
81- return p;
82-end;
83-
84-(* The column src[p] is at, a tab going on to the next multiple of 8. *)
85-proc column(p: I64): I64;
86-var i, col: I64;
87-begin
88- col := 0;
89- for i := lineStart(p) to p - 1 do
90- if src[i] = '\t' then col := (col div 8 + 1) * 8; else INC(col); end;
91- end;
92- return col;
93-end;
94-
95-(* Whether s ends an operand, so that a - after it subtracts. *)
96-proc endsOperand(s: ^Scan.Scanner): BOOL;
97-begin
98- if s^.kind = Scan.word then return not Scan.reserved(Scan.text(s)); end;
99- return (s^.kind = Scan.number) or (s^.kind = Scan.literal)
100- or Scan.is(s, ")") or Scan.is(s, "]") or Scan.is(s, "}") or Scan.is(s, "^");
101-end;
102-
103-(* The symbol after the current one that isn't a comment. *)
104-proc following: Scan.Scanner;
105-var s: Scan.Scanner;
106-begin
107- s := sc;
108- repeat Scan.next(ADR(s)); until s.kind # Scan.comment;
109- return s;
110-end;
111-
112-(* Whether the current symbol is a binary operator. A * after a name
113- and before ; , : = ) or a procedure's parameters exports the name. *)
114-proc binary: BOOL;
115-var n: Scan.Scanner;
116-begin
117- if sc.kind = Scan.word then return Scan.among(Scan.text(ADR(sc)), binaryWords); end;
118- if (sc.kind # Scan.symbol) or not Scan.among(Scan.text(ADR(sc)), binarySymbols) then
119- return false;
120- end;
121- if Scan.is(ADR(sc), "-") or Scan.is(ADR(sc), "+") then return endsOperand(ADR(prev)); end;
122- if Scan.is(ADR(sc), "*") and (prev.kind = Scan.word) then
123- n := following();
124- if Scan.among(Scan.text(ADR(n)), "; , : = )") then return false; end;
125- if Scan.is(ADR(n), "(") and Scan.is(ADR(prev2), "proc") then return false; end;
126- end;
127- return true;
128-end;
129-
130-(* Whether the current symbol, first on its line, goes on with the
131- expression of the line before. *)
132-proc continues: BOOL;
133-var t: []U8;
134-begin
135- if (brackets > 0) or prevBinary or Scan.is(ADR(prev), ",") then return true; end;
136- t := Scan.text(ADR(sc));
137- if sc.kind = Scan.word then return Scan.among(t, binaryWords) or Scan.among(t, "then do of"); end;
138- return (sc.kind = Scan.symbol) and Scan.among(t, binarySymbols);
139-end;
140-
141-(* Whether s starts a declaration at the margin: proc( starts a
142- procedure type. *)
143-proc declaration(s: Scan.Scanner): BOOL;
144-begin
145- if (s.kind # Scan.word) or not Scan.among(Scan.text(ADR(s)), declarations) then return false; end;
146- if not Scan.is(ADR(s), "proc") then return true; end;
147- Scan.next(ADR(s));
148- return not Scan.is(ADR(s), "(");
149-end;
150-
151-(* The indent of the block's own lines, or of its end. *)
152-proc inner: I64;
153-begin
154- if depth > 0 then return bases[depth - 1] + width; end;
155- if inSection then return width; end;
156- return 0;
157-end;
158-
159-proc outer: I64;
160-begin
161- if depth > 0 then return bases[depth - 1]; end;
162- return 0;
163-end;
164-
165-(* The indent of the line the current symbol starts, which was at old. *)
166-proc indent(old: I64): I64;
167-var n: Scan.Scanner;
168-begin
169- if continues() then
170- if old + stmtDelta < 0 then return 0; end;
171- return old + stmtDelta;
172- end;
173- if sc.kind = Scan.comment then
174- n := following();
175- if n.lineBreak and declaration(n) then return 0; end;
176- return inner();
177- end;
178- if declaration(sc) then
179- depth := 0;
180- inSection := Scan.among(Scan.text(ADR(sc)), "const type var");
181- return 0;
182- end;
183- if Scan.among(Scan.text(ADR(sc)), "end until else elsif |") then
184- return outer();
185- end;
186- return inner();
187-end;
188-
189-(* Starts the line of the current symbol, at its indent. *)
190-proc startLine;
191-var old, new: I64;
192-begin
193- old := column(sc.start);
194- new := indent(old);
195- lineDelta := new - old;
196- if (sc.kind # Scan.comment) and not continues() then
197- stmtIndent := new;
198- stmtDelta := lineDelta;
199- end;
200- spaces(new);
201-end;
202-
203-(* The spaces between the last symbol written and the current one, on
204- the same line. *)
205-proc gap(binaryNow: BOOL);
206-var n: I64;
207-begin
208- if sc.kind = Scan.comment then
209- n := column(sc.start) + lineDelta - (out.len - lineAt);
210- if (n < 1) and (sc.start > last) then n := 1; end;
211- spaces(n);
212- elsif afterComment then
213- Buf.str(ADR(out), src[last..sc.start]);
214- elsif Scan.is(ADR(sc), ",") or Scan.is(ADR(sc), ";") then
215- elsif Scan.is(ADR(prev), ",") or Scan.is(ADR(prev), ";") or binaryNow or prevBinary then
216- if not prevUnary then spaces(1); end;
217- elsif not prevUnary then
218- Buf.str(ADR(out), src[last..sc.start]);
219- end;
220-end;
221-
222-(* The current symbol as written; each line of a comment after its
223- first is moved as far as the line the comment starts on. *)
224-proc write;
225-var i, k: I64;
226-begin
227- i := sc.start;
228- while i < sc.stop do
229- if src[i] = '\n' then
230- newLine;
231- k := i + 1;
232- while (k < sc.stop) and (src[k] = ' ') do INC(k); end;
233- if (k < sc.stop) and (src[k] # '\n') then spaces(k - (i + 1) + lineDelta); end;
234- i := k;
235- else
236- Buf.add(ADR(out), src[i]);
237- INC(i);
238- end;
239- end;
240-end;
241-
242-(* After a symbol that isn't a comment: the blocks and brackets it opens
243- or closes. *)
244-proc track(binaryNow: BOOL);
245-var t: []U8;
246-begin
247- t := Scan.text(ADR(sc));
248- if sc.kind = Scan.word then
249- if Scan.among(t, openers) then
250- if depth = LEN(bases) then Rt.stop("Pretty: blocks nested too deep"); end;
251- bases[depth] := stmtIndent;
252- INC(depth);
253- elsif ((t = "end") or (t = "until")) and (depth > 0) then
254- DEC(depth);
255- end;
256- elsif sc.kind = Scan.symbol then
257- if Scan.among(t, "( [ {") then INC(brackets);
258- elsif Scan.among(t, ") ] }") and (brackets > 0) then DEC(brackets);
259- end;
260- end;
261- prevUnary := (Scan.is(ADR(sc), "-") or Scan.is(ADR(sc), "+")) and not binaryNow;
262- prevBinary := binaryNow;
263- prev2 := prev;
264- prev := sc;
265-end;
266-
267-(* The line breaks in src[from..upto]. *)
268-proc lineBreaks(from, upto: I64);
269-var i: I64;
270-begin
271- for i := from to upto - 1 do
272- if src[i] = '\n' then newLine; end;
273- end;
274-end;
275-
276-(* src, formatted, into out. *)
277-proc format(text: []U8);
278-var b: BOOL;
279-begin
280- src := text;
281- Buf.reset(ADR(out));
282- lineAt := 0;
283- depth := 0;
284- brackets := 0;
285- inSection := false;
286- stmtIndent := 0;
287- stmtDelta := 0;
288- Scan.init(ADR(sc), src);
289- prev := sc;
290- prev2 := sc;
291- prevBinary := false;
292- prevUnary := false;
293- afterComment := false;
294- last := 0;
295- Scan.next(ADR(sc));
296- while sc.kind # Scan.eof do
297- b := (sc.kind # Scan.comment) and binary();
298- if sc.lineBreak then
299- lineBreaks(last, sc.start);
300- startLine;
301- else
302- gap(b);
303- end;
304- write;
305- afterComment := sc.kind = Scan.comment;
306- if not afterComment then track(b); end;
307- last := sc.stop;
308- Scan.next(ADR(sc));
309- end;
310- lineBreaks(last, LEN(src));
311- trim;
312-end;
313-
314-proc main*;
315-var b: Buf.Buf; i: I64; path: []U8;
316-begin
317- Buf.init(ADR(b), Heap.heap);
318- Buf.init(ADR(out), Heap.heap);
319- if (ARGC() >= 3) and (Files.arg(1) = "-w") then
320- for i := 2 to ARGC() - 1 do
321- path := Files.arg(i);
322- Buf.reset(ADR(b));
323- if not Files.read(path, ADR(b)) then Rt.stop("Pretty: can't read a file"); end;
324- format(Buf.bytes(ADR(b)));
325- if Buf.bytes(ADR(out)) # Buf.bytes(ADR(b)) then
326- if not Files.write(path, Buf.bytes(ADR(out))) then Rt.stop("Pretty: can't write a file"); end;
327- Out.str(path); Out.ln;
328- end;
329- end;
330- elsif ARGC() = 2 then
331- if not Files.read(Files.arg(1), ADR(b)) then Rt.stop("Pretty: can't read the file"); end;
332- format(Buf.bytes(ADR(b)));
333- Out.str(Buf.bytes(ADR(out)));
334- else
335- Rt.stop("usage: Pretty Module.jed, or Pretty -w File.jed...");
336- end;
337-end;
338-
339-end Pretty.

tools/Pretty.raz (history) added +339 -0

@@ -0,0 +1,339 @@
1+(* Pretty: raz source laid out the one way.
2+
3+ Pretty Module.raz
4+ prints the module, formatted.
5+
6+ Pretty -w File.raz...
7+ rewrites each file that isn't formatted already.
8+
9+ Every line break and comment stays where it is. A line is indented
10+ 4 spaces for each block it stands in: the statements of if, while,
11+ for, repeat and begin, the fields of a record or variant, the
12+ declarations of const, type and var. end, until, else, elsif and a
13+ match's arms stand at the level of the statement that opened them;
14+ module, import, proc, the sections and begin at the margin, with the
15+ comment just before them. A line that goes on with the expression of
16+ the line before keeps its indent, moved as far as the statement's
17+ first line moved; so does the text of a comment.
18+
19+ Within a line, a binary operator has one space on each side, a unary
20+ minus none after it, and , and ; none before them and one after. A
21+ comment after code keeps its column. Other spaces stay as written,
22+ so that lined-up match arms stay lined up. No line ends in spaces. *)
23+module Pretty;
24+import Out, Rt, Buf, Heap, Scan, Files;
25+
26+const
27+ width = 4; (* the spaces of a level *)
28+ openers = "if while for match record variant begin repeat";
29+ declarations = "module import link extern proc const type var begin code";
30+ binaryWords = "div mod and or xor shl shr in";
31+ binarySymbols = "+ - * / = # < <= > >= :=";
32+
33+var
34+ sc: Scan.Scanner; (* the source, at the symbol being written *)
35+ src: []U8;
36+ out: Buf.Buf;
37+ lineAt: I64; (* where the line being written starts in out *)
38+ lineDelta: I64; (* how far this line's indent moved *)
39+
40+ (* the blocks open, each with the indent of the statement that
41+ opened it *)
42+ bases: [100]I64;
43+ depth: I64;
44+ brackets: I64; (* brackets open *)
45+ inSection: BOOL; (* among the declarations of const, type or var *)
46+ stmtIndent: I64; (* the indent of the current statement's first line *)
47+ stmtDelta: I64; (* and how far that moved *)
48+
49+ (* the last symbol that wasn't a comment, and the one before it *)
50+ prev, prev2: Scan.Scanner;
51+ prevBinary, prevUnary: BOOL;
52+ afterComment: BOOL; (* the last symbol written was a comment *)
53+ last: I64; (* where the last symbol written ends in src *)
54+
55+proc spaces(n: I64);
56+begin
57+ while n > 0 do Buf.add(ADR(out), ' '); DEC(n); end;
58+end;
59+
60+(* Drops the spaces at the end of the line in out. *)
61+proc trim;
62+var s: []U8;
63+begin
64+ s := Buf.bytes(ADR(out));
65+ while (out.len > lineAt) and ((s[out.len - 1] = ' ') or (s[out.len - 1] = '\t')) do
66+ DEC(out.len);
67+ end;
68+end;
69+
70+proc newLine;
71+begin
72+ trim;
73+ Buf.add(ADR(out), '\n');
74+ lineAt := out.len;
75+end;
76+
77+(* Where the line holding p starts in src. *)
78+proc lineStart(p: I64): I64;
79+begin
80+ while (p > 0) and (src[p - 1] # '\n') do DEC(p); end;
81+ return p;
82+end;
83+
84+(* The column src[p] is at, a tab going on to the next multiple of 8. *)
85+proc column(p: I64): I64;
86+var i, col: I64;
87+begin
88+ col := 0;
89+ for i := lineStart(p) to p - 1 do
90+ if src[i] = '\t' then col := (col div 8 + 1) * 8; else INC(col); end;
91+ end;
92+ return col;
93+end;
94+
95+(* Whether s ends an operand, so that a - after it subtracts. *)
96+proc endsOperand(s: ^Scan.Scanner): BOOL;
97+begin
98+ if s^.kind = Scan.word then return not Scan.reserved(Scan.text(s)); end;
99+ return (s^.kind = Scan.number) or (s^.kind = Scan.literal)
100+ or Scan.is(s, ")") or Scan.is(s, "]") or Scan.is(s, "}") or Scan.is(s, "^");
101+end;
102+
103+(* The symbol after the current one that isn't a comment. *)
104+proc following: Scan.Scanner;
105+var s: Scan.Scanner;
106+begin
107+ s := sc;
108+ repeat Scan.next(ADR(s)); until s.kind # Scan.comment;
109+ return s;
110+end;
111+
112+(* Whether the current symbol is a binary operator. A * after a name
113+ and before ; , : = ) or a procedure's parameters exports the name. *)
114+proc binary: BOOL;
115+var n: Scan.Scanner;
116+begin
117+ if sc.kind = Scan.word then return Scan.among(Scan.text(ADR(sc)), binaryWords); end;
118+ if (sc.kind # Scan.symbol) or not Scan.among(Scan.text(ADR(sc)), binarySymbols) then
119+ return false;
120+ end;
121+ if Scan.is(ADR(sc), "-") or Scan.is(ADR(sc), "+") then return endsOperand(ADR(prev)); end;
122+ if Scan.is(ADR(sc), "*") and (prev.kind = Scan.word) then
123+ n := following();
124+ if Scan.among(Scan.text(ADR(n)), "; , : = )") then return false; end;
125+ if Scan.is(ADR(n), "(") and Scan.is(ADR(prev2), "proc") then return false; end;
126+ end;
127+ return true;
128+end;
129+
130+(* Whether the current symbol, first on its line, goes on with the
131+ expression of the line before. *)
132+proc continues: BOOL;
133+var t: []U8;
134+begin
135+ if (brackets > 0) or prevBinary or Scan.is(ADR(prev), ",") then return true; end;
136+ t := Scan.text(ADR(sc));
137+ if sc.kind = Scan.word then return Scan.among(t, binaryWords) or Scan.among(t, "then do of"); end;
138+ return (sc.kind = Scan.symbol) and Scan.among(t, binarySymbols);
139+end;
140+
141+(* Whether s starts a declaration at the margin: proc( starts a
142+ procedure type. *)
143+proc declaration(s: Scan.Scanner): BOOL;
144+begin
145+ if (s.kind # Scan.word) or not Scan.among(Scan.text(ADR(s)), declarations) then return false; end;
146+ if not Scan.is(ADR(s), "proc") then return true; end;
147+ Scan.next(ADR(s));
148+ return not Scan.is(ADR(s), "(");
149+end;
150+
151+(* The indent of the block's own lines, or of its end. *)
152+proc inner: I64;
153+begin
154+ if depth > 0 then return bases[depth - 1] + width; end;
155+ if inSection then return width; end;
156+ return 0;
157+end;
158+
159+proc outer: I64;
160+begin
161+ if depth > 0 then return bases[depth - 1]; end;
162+ return 0;
163+end;
164+
165+(* The indent of the line the current symbol starts, which was at old. *)
166+proc indent(old: I64): I64;
167+var n: Scan.Scanner;
168+begin
169+ if continues() then
170+ if old + stmtDelta < 0 then return 0; end;
171+ return old + stmtDelta;
172+ end;
173+ if sc.kind = Scan.comment then
174+ n := following();
175+ if n.lineBreak and declaration(n) then return 0; end;
176+ return inner();
177+ end;
178+ if declaration(sc) then
179+ depth := 0;
180+ inSection := Scan.among(Scan.text(ADR(sc)), "const type var");
181+ return 0;
182+ end;
183+ if Scan.among(Scan.text(ADR(sc)), "end until else elsif |") then
184+ return outer();
185+ end;
186+ return inner();
187+end;
188+
189+(* Starts the line of the current symbol, at its indent. *)
190+proc startLine;
191+var old, new: I64;
192+begin
193+ old := column(sc.start);
194+ new := indent(old);
195+ lineDelta := new - old;
196+ if (sc.kind # Scan.comment) and not continues() then
197+ stmtIndent := new;
198+ stmtDelta := lineDelta;
199+ end;
200+ spaces(new);
201+end;
202+
203+(* The spaces between the last symbol written and the current one, on
204+ the same line. *)
205+proc gap(binaryNow: BOOL);
206+var n: I64;
207+begin
208+ if sc.kind = Scan.comment then
209+ n := column(sc.start) + lineDelta - (out.len - lineAt);
210+ if (n < 1) and (sc.start > last) then n := 1; end;
211+ spaces(n);
212+ elsif afterComment then
213+ Buf.str(ADR(out), src[last..sc.start]);
214+ elsif Scan.is(ADR(sc), ",") or Scan.is(ADR(sc), ";") then
215+ elsif Scan.is(ADR(prev), ",") or Scan.is(ADR(prev), ";") or binaryNow or prevBinary then
216+ if not prevUnary then spaces(1); end;
217+ elsif not prevUnary then
218+ Buf.str(ADR(out), src[last..sc.start]);
219+ end;
220+end;
221+
222+(* The current symbol as written; each line of a comment after its
223+ first is moved as far as the line the comment starts on. *)
224+proc write;
225+var i, k: I64;
226+begin
227+ i := sc.start;
228+ while i < sc.stop do
229+ if src[i] = '\n' then
230+ newLine;
231+ k := i + 1;
232+ while (k < sc.stop) and (src[k] = ' ') do INC(k); end;
233+ if (k < sc.stop) and (src[k] # '\n') then spaces(k - (i + 1) + lineDelta); end;
234+ i := k;
235+ else
236+ Buf.add(ADR(out), src[i]);
237+ INC(i);
238+ end;
239+ end;
240+end;
241+
242+(* After a symbol that isn't a comment: the blocks and brackets it opens
243+ or closes. *)
244+proc track(binaryNow: BOOL);
245+var t: []U8;
246+begin
247+ t := Scan.text(ADR(sc));
248+ if sc.kind = Scan.word then
249+ if Scan.among(t, openers) then
250+ if depth = LEN(bases) then Rt.stop("Pretty: blocks nested too deep"); end;
251+ bases[depth] := stmtIndent;
252+ INC(depth);
253+ elsif ((t = "end") or (t = "until")) and (depth > 0) then
254+ DEC(depth);
255+ end;
256+ elsif sc.kind = Scan.symbol then
257+ if Scan.among(t, "( [ {") then INC(brackets);
258+ elsif Scan.among(t, ") ] }") and (brackets > 0) then DEC(brackets);
259+ end;
260+ end;
261+ prevUnary := (Scan.is(ADR(sc), "-") or Scan.is(ADR(sc), "+")) and not binaryNow;
262+ prevBinary := binaryNow;
263+ prev2 := prev;
264+ prev := sc;
265+end;
266+
267+(* The line breaks in src[from..upto]. *)
268+proc lineBreaks(from, upto: I64);
269+var i: I64;
270+begin
271+ for i := from to upto - 1 do
272+ if src[i] = '\n' then newLine; end;
273+ end;
274+end;
275+
276+(* src, formatted, into out. *)
277+proc format(text: []U8);
278+var b: BOOL;
279+begin
280+ src := text;
281+ Buf.reset(ADR(out));
282+ lineAt := 0;
283+ depth := 0;
284+ brackets := 0;
285+ inSection := false;
286+ stmtIndent := 0;
287+ stmtDelta := 0;
288+ Scan.init(ADR(sc), src);
289+ prev := sc;
290+ prev2 := sc;
291+ prevBinary := false;
292+ prevUnary := false;
293+ afterComment := false;
294+ last := 0;
295+ Scan.next(ADR(sc));
296+ while sc.kind # Scan.eof do
297+ b := (sc.kind # Scan.comment) and binary();
298+ if sc.lineBreak then
299+ lineBreaks(last, sc.start);
300+ startLine;
301+ else
302+ gap(b);
303+ end;
304+ write;
305+ afterComment := sc.kind = Scan.comment;
306+ if not afterComment then track(b); end;
307+ last := sc.stop;
308+ Scan.next(ADR(sc));
309+ end;
310+ lineBreaks(last, LEN(src));
311+ trim;
312+end;
313+
314+proc main*;
315+var b: Buf.Buf; i: I64; path: []U8;
316+begin
317+ Buf.init(ADR(b), Heap.heap);
318+ Buf.init(ADR(out), Heap.heap);
319+ if (ARGC() >= 3) and (Files.arg(1) = "-w") then
320+ for i := 2 to ARGC() - 1 do
321+ path := Files.arg(i);
322+ Buf.reset(ADR(b));
323+ if not Files.read(path, ADR(b)) then Rt.stop("Pretty: can't read a file"); end;
324+ format(Buf.bytes(ADR(b)));
325+ if Buf.bytes(ADR(out)) # Buf.bytes(ADR(b)) then
326+ if not Files.write(path, Buf.bytes(ADR(out))) then Rt.stop("Pretty: can't write a file"); end;
327+ Out.str(path); Out.ln;
328+ end;
329+ end;
330+ elsif ARGC() = 2 then
331+ if not Files.read(Files.arg(1), ADR(b)) then Rt.stop("Pretty: can't read the file"); end;
332+ format(Buf.bytes(ADR(b)));
333+ Out.str(Buf.bytes(ADR(out)));
334+ else
335+ Rt.stop("usage: Pretty Module.raz, or Pretty -w File.raz...");
336+ end;
337+end;
338+
339+end Pretty.

tools/Scan.jed deleted +0 -171

@@ -1,171 +0,0 @@
1-(* Scan: the symbols of jed source, for the tools. Unlike the
2- compiler's scanner it keeps comments, as symbols of their own, and
3- says where each symbol is in the text and whether a line break comes
4- before it. It doesn't check what it reads: a malformed number is
5- read as far as it goes, and a string, character or comment left open
6- ends with its line or the text. *)
7-module Scan;
8-
9-type
10- Kind* = (word, number, literal, symbol, comment, eof);
11-
12- (* word is an identifier or a reserved word; literal a string or a
13- character; symbol an operator or delimiter. *)
14- Scanner* = record
15- src*: []U8;
16- pos*: I64; (* where the next symbol is looked for *)
17- kind*: Kind; (* the current symbol *)
18- start*, stop*: I64; (* its text: src[start..stop] *)
19- lineBreak*: BOOL; (* a line break comes before it, or it is the first *)
20- end;
21-
22-const
23- words = "and begin break by code const defer div do else elsif end extern for forward if import in link match mod module not of or packed proc record repeat return set shl shr then to type until var variant VOLATILE while xor";
24-
25-proc isSpace*(c: U8): BOOL;
26-begin
27- return (c = ' ') or (c = '\t') or (c = '\n') or (c = '\r');
28-end;
29-
30-proc isWord*(c: U8): BOOL;
31-begin
32- return (c >= 'a') and (c <= 'z') or (c >= 'A') and (c <= 'Z')
33- or (c >= '0') and (c <= '9') or (c = '_');
34-end;
35-
36-proc isDigit(c: U8): BOOL;
37-begin
38- return (c >= '0') and (c <= '9');
39-end;
40-
41-(* Whether w is one of the words of list, which are separated by
42- single spaces. *)
43-proc among*(w, list: []U8): BOOL;
44-var i, j: I64;
45-begin
46- i := 0;
47- while i < LEN(list) do
48- j := i;
49- while (j < LEN(list)) and (list[j] # ' ') do INC(j); end;
50- if list[i..j] = w then return true; end;
51- i := j + 1;
52- end;
53- return false;
54-end;
55-
56-(* Whether w is one of the report's reserved words. *)
57-proc reserved*(w: []U8): BOOL;
58-begin
59- return among(w, words);
60-end;
61-
62-(* The scanner at the start of src; next gives the first symbol. *)
63-proc init*(s: ^Scanner; src: []U8);
64-begin
65- s^ := {src: src, kind: eof};
66-end;
67-
68-(* Past the comment that starts at p, its nested comments with it. *)
69-proc pastComment(src: []U8; p: I64): I64;
70-var depth: I64;
71-begin
72- depth := 0;
73- repeat
74- if (src[p] = '(') and (p + 1 < LEN(src)) and (src[p + 1] = '*') then
75- INC(depth); INC(p, 2);
76- elsif (src[p] = '*') and (p + 1 < LEN(src)) and (src[p + 1] = ')') then
77- DEC(depth); INC(p, 2);
78- else
79- INC(p);
80- end;
81- until (depth = 0) or (p >= LEN(src));
82- return p;
83-end;
84-
85-(* Past the number that starts at p: digits and letters, then a real's
86- point, digits and exponent, as in 0FFH and 2.0E-3. *)
87-proc pastNumber(src: []U8; p: I64): I64;
88-begin
89- while (p < LEN(src)) and isWord(src[p]) do INC(p); end;
90- if (p + 1 < LEN(src)) and (src[p] = '.') and isDigit(src[p + 1]) then
91- INC(p);
92- while (p < LEN(src)) and isWord(src[p]) do INC(p); end;
93- if (src[p - 1] = 'E') and (p < LEN(src)) and ((src[p] = '-') or (src[p] = '+')) then
94- INC(p);
95- while (p < LEN(src)) and isWord(src[p]) do INC(p); end;
96- end;
97- end;
98- return p;
99-end;
100-
101-(* Past the string or character that starts at p, or to its line's end. *)
102-proc pastLiteral(src: []U8; p: I64): I64;
103-var q: U8;
104-begin
105- q := src[p];
106- INC(p);
107- while (p < LEN(src)) and (src[p] # q) and (src[p] # '\n') do
108- if (src[p] = '\\') and (p + 1 < LEN(src)) then INC(p); end;
109- INC(p);
110- end;
111- if (p < LEN(src)) and (src[p] = q) then INC(p); end;
112- return p;
113-end;
114-
115-(* Whether src[p..] starts with the symbol t. *)
116-proc at(src: []U8; p: I64; t: []U8): BOOL;
117-begin
118- return (p + LEN(t) <= LEN(src)) and (src[p..p + LEN(t)] = t);
119-end;
120-
121-(* On to the next symbol. *)
122-proc next*(s: ^Scanner);
123-var src: []U8; p: I64; c: U8;
124-begin
125- src := s^.src;
126- p := s^.pos;
127- s^.lineBreak := p = 0;
128- while (p < LEN(src)) and isSpace(src[p]) do
129- if src[p] = '\n' then s^.lineBreak := true; end;
130- INC(p);
131- end;
132- s^.start := p;
133- if p >= LEN(src) then
134- s^.kind := eof;
135- else
136- c := src[p];
137- if at(src, p, "(*") then
138- s^.kind := comment; p := pastComment(src, p);
139- elsif isDigit(c) then
140- s^.kind := number; p := pastNumber(src, p);
141- elsif isWord(c) then
142- s^.kind := word;
143- while (p < LEN(src)) and isWord(src[p]) do INC(p); end;
144- elsif (c = '"') or (c = '\'') then
145- s^.kind := literal; p := pastLiteral(src, p);
146- else
147- s^.kind := symbol;
148- if at(src, p, "...") then INC(p, 3);
149- elsif at(src, p, ":=") or at(src, p, "<=") or at(src, p, ">=") or at(src, p, "..") then
150- INC(p, 2);
151- else
152- INC(p);
153- end;
154- end;
155- end;
156- s^.stop := p;
157- s^.pos := p;
158-end;
159-
160-proc text*(s: ^Scanner): []U8;
161-begin
162- return s^.src[s^.start..s^.stop];
163-end;
164-
165-(* Whether the current symbol is t. *)
166-proc is*(s: ^Scanner; t: []U8): BOOL;
167-begin
168- return text(s) = t;
169-end;
170-
171-end Scan.

tools/Scan.raz (history) added +171 -0

@@ -0,0 +1,171 @@
1+(* Scan: the symbols of raz source, for the tools. Unlike the
2+ compiler's scanner it keeps comments, as symbols of their own, and
3+ says where each symbol is in the text and whether a line break comes
4+ before it. It doesn't check what it reads: a malformed number is
5+ read as far as it goes, and a string, character or comment left open
6+ ends with its line or the text. *)
7+module Scan;
8+
9+type
10+ Kind* = (word, number, literal, symbol, comment, eof);
11+
12+ (* word is an identifier or a reserved word; literal a string or a
13+ character; symbol an operator or delimiter. *)
14+ Scanner* = record
15+ src*: []U8;
16+ pos*: I64; (* where the next symbol is looked for *)
17+ kind*: Kind; (* the current symbol *)
18+ start*, stop*: I64; (* its text: src[start..stop] *)
19+ lineBreak*: BOOL; (* a line break comes before it, or it is the first *)
20+ end;
21+
22+const
23+ words = "and begin break by code const defer div do else elsif end extern for forward if import in link match mod module not of or packed proc record repeat return set shl shr then to type until var variant VOLATILE while xor";
24+
25+proc isSpace*(c: U8): BOOL;
26+begin
27+ return (c = ' ') or (c = '\t') or (c = '\n') or (c = '\r');
28+end;
29+
30+proc isWord*(c: U8): BOOL;
31+begin
32+ return (c >= 'a') and (c <= 'z') or (c >= 'A') and (c <= 'Z')
33+ or (c >= '0') and (c <= '9') or (c = '_');
34+end;
35+
36+proc isDigit(c: U8): BOOL;
37+begin
38+ return (c >= '0') and (c <= '9');
39+end;
40+
41+(* Whether w is one of the words of list, which are separated by
42+ single spaces. *)
43+proc among*(w, list: []U8): BOOL;
44+var i, j: I64;
45+begin
46+ i := 0;
47+ while i < LEN(list) do
48+ j := i;
49+ while (j < LEN(list)) and (list[j] # ' ') do INC(j); end;
50+ if list[i..j] = w then return true; end;
51+ i := j + 1;
52+ end;
53+ return false;
54+end;
55+
56+(* Whether w is one of the report's reserved words. *)
57+proc reserved*(w: []U8): BOOL;
58+begin
59+ return among(w, words);
60+end;
61+
62+(* The scanner at the start of src; next gives the first symbol. *)
63+proc init*(s: ^Scanner; src: []U8);
64+begin
65+ s^ := {src: src, kind: eof};
66+end;
67+
68+(* Past the comment that starts at p, its nested comments with it. *)
69+proc pastComment(src: []U8; p: I64): I64;
70+var depth: I64;
71+begin
72+ depth := 0;
73+ repeat
74+ if (src[p] = '(') and (p + 1 < LEN(src)) and (src[p + 1] = '*') then
75+ INC(depth); INC(p, 2);
76+ elsif (src[p] = '*') and (p + 1 < LEN(src)) and (src[p + 1] = ')') then
77+ DEC(depth); INC(p, 2);
78+ else
79+ INC(p);
80+ end;
81+ until (depth = 0) or (p >= LEN(src));
82+ return p;
83+end;
84+
85+(* Past the number that starts at p: digits and letters, then a real's
86+ point, digits and exponent, as in 0FFH and 2.0E-3. *)
87+proc pastNumber(src: []U8; p: I64): I64;
88+begin
89+ while (p < LEN(src)) and isWord(src[p]) do INC(p); end;
90+ if (p + 1 < LEN(src)) and (src[p] = '.') and isDigit(src[p + 1]) then
91+ INC(p);
92+ while (p < LEN(src)) and isWord(src[p]) do INC(p); end;
93+ if (src[p - 1] = 'E') and (p < LEN(src)) and ((src[p] = '-') or (src[p] = '+')) then
94+ INC(p);
95+ while (p < LEN(src)) and isWord(src[p]) do INC(p); end;
96+ end;
97+ end;
98+ return p;
99+end;
100+
101+(* Past the string or character that starts at p, or to its line's end. *)
102+proc pastLiteral(src: []U8; p: I64): I64;
103+var q: U8;
104+begin
105+ q := src[p];
106+ INC(p);
107+ while (p < LEN(src)) and (src[p] # q) and (src[p] # '\n') do
108+ if (src[p] = '\\') and (p + 1 < LEN(src)) then INC(p); end;
109+ INC(p);
110+ end;
111+ if (p < LEN(src)) and (src[p] = q) then INC(p); end;
112+ return p;
113+end;
114+
115+(* Whether src[p..] starts with the symbol t. *)
116+proc at(src: []U8; p: I64; t: []U8): BOOL;
117+begin
118+ return (p + LEN(t) <= LEN(src)) and (src[p..p + LEN(t)] = t);
119+end;
120+
121+(* On to the next symbol. *)
122+proc next*(s: ^Scanner);
123+var src: []U8; p: I64; c: U8;
124+begin
125+ src := s^.src;
126+ p := s^.pos;
127+ s^.lineBreak := p = 0;
128+ while (p < LEN(src)) and isSpace(src[p]) do
129+ if src[p] = '\n' then s^.lineBreak := true; end;
130+ INC(p);
131+ end;
132+ s^.start := p;
133+ if p >= LEN(src) then
134+ s^.kind := eof;
135+ else
136+ c := src[p];
137+ if at(src, p, "(*") then
138+ s^.kind := comment; p := pastComment(src, p);
139+ elsif isDigit(c) then
140+ s^.kind := number; p := pastNumber(src, p);
141+ elsif isWord(c) then
142+ s^.kind := word;
143+ while (p < LEN(src)) and isWord(src[p]) do INC(p); end;
144+ elsif (c = '"') or (c = '\'') then
145+ s^.kind := literal; p := pastLiteral(src, p);
146+ else
147+ s^.kind := symbol;
148+ if at(src, p, "...") then INC(p, 3);
149+ elsif at(src, p, ":=") or at(src, p, "<=") or at(src, p, ">=") or at(src, p, "..") then
150+ INC(p, 2);
151+ else
152+ INC(p);
153+ end;
154+ end;
155+ end;
156+ s^.stop := p;
157+ s^.pos := p;
158+end;
159+
160+proc text*(s: ^Scanner): []U8;
161+begin
162+ return s^.src[s^.start..s^.stop];
163+end;
164+
165+(* Whether the current symbol is t. *)
166+proc is*(s: ^Scanner; t: []U8): BOOL;
167+begin
168+ return text(s) = t;
169+end;
170+
171+end Scan.