From ba7f6657325a8a39efeb71af7b40a2591c4d41b9 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:00:58 +0100 Subject: [PATCH] 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. --- diff --git a/.gitignore b/.gitignore index 96b025b..58695dd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ build/ -/jed +/raz diff --git a/CLAUDE.md b/CLAUDE.md index d62e4ac..ecf0c81 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,13 +1,13 @@ -# Working on jed +# Working on raz -Read `PLAN.md` (the plan, ground rules, steps) and `doc/jed.md` (the +Read `PLAN.md` (the plan, ground rules, steps) and `doc/raz.md` (the language report) first. The report defines the language; where the plan disagrees, the report wins and the plan is fixed. ## Setup and checks apt-get install -y fp-compiler # Free Pascal 3.2.2, if fpc is missing - make jed # the compiler, ./jed; its library is lib/ + make raz # the compiler, ./raz; its library is lib/ make check # every example and test against its expected output make bench # must report at least 400,000 lines a second make loc # lines of the compiler; the code column is the budget @@ -16,16 +16,16 @@ make stress # 40,000 native threads; make check runs a small version make fmt # lib/, examples/ and tools/ are formatted -`make check` also runs `tools/Doc.jed` and `tools/Pretty.jed`, the +`make check` also runs `tools/Doc.raz` and `tools/Pretty.raz`, the report's whole examples, each library module's own `main` (its test), and the vim and emacs support headless where they are installed (`apt-get install -y vim emacs-nox`): each example must indent back exactly as written. -`make check` must pass before every commit. Tests: `test/run/X.jed` +`make check` must pass before every commit. Tests: `test/run/X.raz` with `X.expect` (stdout), optional `X.status` and `X.args`; modules they -import in `test/run/mods`. `test/err/X.jed` must fail to compile with -the text in `X.err`. `test/pretty/X.jed` must format to `X.expect`. +import in `test/run/mods`. `test/err/X.raz` must fail to compile with +the text in `X.err`. `test/pretty/X.raz` must format to `X.expect`. Examples in `examples/` work the same way. ## How we work @@ -34,21 +34,22 @@ go-ahead; within it, one commit per step, pushed as it is done, then stop for review. Never start a stage, or change the report's language, without being asked. -- Language changes go into `doc/jed.md` first, for the owner to review, +- Language changes go into `doc/raz.md` first, for the owner to review, before any code. -- Commits: author `Luis <42945842+ldiaz94@users.noreply.github.com>`, unsigned +- Commits: author + `Luis <42945842+ldiaz94@users.noreply.github.com>`, unsigned (`--no-gpg-sign`), no attribution trailer. Push to `main`. No pull requests unless asked. - Budget: about 5,000 lines of code (blank and comment lines not - counted), within 10%; at least 400,000 lines of jed a second. + counted), within 10%; at least 400,000 lines of raz a second. - Style: clarity over cleverness; each unit opens with what it is, what it depends on and what it leaves out; comments say why. Match the report's plain, short prose in documentation. ## Where things stand -Steps 1-18 are done: the language, the tools (`tools/Doc.jed`, and -the formatter, `tools/Pretty.jed`, over the shared `tools/Scan.jed`), +Steps 1-18 are done: the language, the tools (`tools/Doc.raz`, and +the formatter, `tools/Pretty.raz`, over the shared `tools/Scan.raz`), `README.md` and the guide to the compiler, `doc/compiler.md`. Nothing further is planned; new work starts only on the owner's word. Keep `doc/compiler.md`'s table of lines and its routine names true when the @@ -56,9 +57,9 @@ for later at the owner's word: tagging versions, and a rewrite of var parameters. -`test/libc` runs its programs over `lib/Sys.jed`, the C one, through +`test/libc` runs its programs over `lib/Sys.raz`, the C one, through a link in its `mods`. A test or example without `.expect` is only -compiled (`examples/Window.jed` needs a display). +compiled (`examples/Window.raz` needs a display). ## Readings of the report already taken diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7209c14 --- /dev/null +++ b/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2026 Luis Díaz + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/Makefile b/Makefile index e8ed72b..41a1c61 100644 --- a/Makefile +++ b/Makefile @@ -1,11 +1,11 @@ -# Builds the compiler, jed, from src/ into the repository's root; the +# Builds the compiler, raz, from src/ into the repository's root; the # library it needs is lib/, beside it. FPC = fpc FPCFLAGS = -O2 -Mobjfpc -Sh- -vew -FUbuild -jed: src/*.pas | build - $(FPC) $(FPCFLAGS) -FE. -ojed src/jed.pas +raz: src/*.pas | build + $(FPC) $(FPCFLAGS) -FE. -oraz src/raz.pas units: src/*.pas | build for u in scan sym x64 link elf; do $(FPC) $(FPCFLAGS) src/$$u.pas || exit 1; done @@ -21,23 +21,23 @@ mkdir -p build clean: - rm -rf build jed + rm -rf build raz # every example and test, against what it should print -check: jed +check: raz test/check.sh # line numbers: gdb stops at a line and names it -gdb: jed +gdb: raz test/gdb.sh # the compiler's speed, on a generated program of about 350,000 lines, # the best of three runs; fails below 400,000 lines a second -bench: jed | build - python3 test/genbench.py 12000 > build/Bench.jed - @lines=$$(wc -l < build/Bench.jed); best=0; \ +bench: raz | build + python3 test/genbench.py 12000 > build/Bench.raz + @lines=$$(wc -l < build/Bench.raz); best=0; \ for i in 1 2 3; do \ - start=$$(date +%s%N); ./jed build/Bench.jed || exit 1; end=$$(date +%s%N); \ + start=$$(date +%s%N); ./raz build/Bench.raz || exit 1; end=$$(date +%s%N); \ t=$$((end - start)); if [ $$best = 0 ] || [ $$t -lt $$best ]; then best=$$t; fi; \ done; \ rate=$$((lines * 1000000000 / best)); \ @@ -47,16 +47,16 @@ # native threads under load: 40,000 spawned and joined, 200 alive at a # time, all waiting on one Mutex; then, with little memory, spawn must # fail with Thread.Failed. make check runs a small version. -stress: jed | build - ./jed -o build/Stress lib/Thread.linux-x86_64.jed +stress: raz | build + ./raz -o build/Stress lib/Thread.linux-x86_64.raz build/Stress 40000 200 (ulimit -v 60000; build/Stress fail) -# the formatter, tools/Pretty.jed: the library, examples and tools are +# the formatter, tools/Pretty.raz: the library, examples and tools are # formatted already -fmt: jed | build - ./jed -o build/Pretty tools/Pretty.jed - @fail=0; for f in lib/*.jed examples/*.jed tools/*.jed; do \ +fmt: raz | build + ./raz -o build/Pretty tools/Pretty.raz + @fail=0; for f in lib/*.raz examples/*.raz tools/*.raz; do \ build/Pretty $$f | cmp -s - $$f || { echo "not formatted: $$f"; fail=1; }; \ done; test $$fail = 0 diff --git a/PLAN.md b/PLAN.md index 3bd4e37..b3b1fa1 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1,12 +1,12 @@ -# jed: the plan +# raz: the plan -jed (Polish *jeden*, one) is a small systems language in Wirth's +raz (Polish for *one*, as in counting) is a small systems language in Wirth's tradition: full control of memory, volatile access, atomics, calls into C, generic modules. Its compiler is meant to be read in a long weekend: under 5,000 lines of Free Pascal, one pass, no IR, no optimizer, writing x86-64 machine code and the ELF file itself. -The language is defined by `doc/jed.md`. Where this plan and the report +The language is defined by `doc/raz.md`. Where this plan and the report disagree, the report wins and this plan is fixed. ## Ground rules @@ -16,14 +16,15 @@ arrays or SysUtils. - The compiler stays near 5,000 lines of code (not counting blank and comment lines), within 10%, and compiles at least 400,000 lines of - jed a second, from reading the sources to writing the executable. + raz a second, from reading the sources to writing the executable. `make loc` and `make bench` measure them, and a step that breaks either limit isn't done. - Clarity over cleverness. Every unit opens with a header comment: what it is, what it depends on, what it leaves out. Comments say why, and what wherever a layout or encoding isn't obvious. -- One commit per step, as `Luis <42945842+ldiaz94@users.noreply.github.com>`, unsigned, with - no attribution trailer. +- One commit per step, as + `Luis <42945842+ldiaz94@users.noreply.github.com>`, unsigned, + with no attribution trailer. - Work stops after every stage for review. A stage starts only on an explicit go-ahead; within it, each step is committed and pushed as it is done. @@ -32,7 +33,7 @@ ## Decisions -1. Source files end in `.jed`, one module per file, named after it. +1. Source files end in `.raz`, one module per file, named after it. 2. "Not equal" is `#`. 3. Every statement ends in `;`, including `end;` and `until x;`. Every match arm starts with `|`, the `else` arm too. @@ -48,7 +49,7 @@ per distinct list of arguments, its types and its procedures. 8. Tree shaking: the linker keeps only the procedures, variables and literals reachable from the entry point. -9. Variadic arguments exist only to call C. jed code gets the same +9. Variadic arguments exist only to call C. raz code gets the same effect from a slice of a variant (`Fmt.print`). 10. Strings are `[]U8`. The language compares them with `=`; the rest is a library. @@ -67,14 +68,14 @@ | `src/parse.pas` | 1,816 | 1,685 | Declarations, statements, expressions, built-ins | | `src/link.pas` | 131 | 95 | Tree shaking, layout, patching | | `src/elf.pas` | 424 | 350 | Static and dynamic ELF, symbol table, line numbers | -| `src/jed.pas` | 183 | 145 | The command line, the entry points | +| `src/raz.pas` | 183 | 145 | The command line, the entry points | | total | 5,704 | 4,954 | | ## Steps Stage 1: the core -- [x] 1. Language report, `doc/jed.md`. Reviewed and approved before +- [x] 1. Language report, `doc/raz.md`. Reviewed and approved before any more code. - [x] 2. Scanner and symbol table, `scan.pas` and `sym.pas`, written against the report; they compile. @@ -86,40 +87,40 @@ enumerations and sets, record literals, `defer`, `NEW`, generic modules and `extern`. Module bodies, per-target modules and their interface check, and code procedures are in. -- [x] 6. `lib/Rt.jed`, `lib/Sys.linux-x86_64.jed`, `lib/Out.jed`; +- [x] 6. `lib/Rt.raz`, `lib/Sys.linux-x86_64.raz`, `lib/Out.raz`; examples (hello, args, variants and slices, volatile, a code procedure); `make check` runs them against expected output; - `make bench` times the compiler on generated jed. + `make bench` times the compiler on generated raz. Stage 2: the rest of the language - [x] 7. Multiple results and errors; `INC` and `DEC`. - [x] 8. Enumerations and sets, record literals, `defer`; examples. -- [x] 9. `NEW`; `lib/Mem.jed`, `lib/Arena.jed`, `lib/Heap.jed`. +- [x] 9. `NEW`; `lib/Mem.raz`, `lib/Arena.raz`, `lib/Heap.raz`. - [x] 10. Generic modules, with type and procedure arguments; - `lib/Str.jed`, `lib/Buf.jed`, `lib/Fmt.jed`; examples. + `lib/Str.raz`, `lib/Buf.raz`, `lib/Fmt.raz`; examples. Stage 3: calling C, and what comes with it - [x] 11. `extern proc`, `extern var` and `link`; dynamic ELF, start - through `__libc_start_main`. A plain `lib/Sys.jed` over the C + through `__libc_start_main`. A plain `lib/Sys.raz` over the C library, the default for targets with no file of their own. Examples with `printf` to `stdout`, and an X11 window, reading `XEvent` as an array of words through pointer conversions. Ending a program: the entry point calls `Rt.exit(status)`, which runs the procedures registered with `Rt.atExit`, then ends it; - `Rt.fail` runs them too. A buffered `lib/Out.jed`: 4 KB, flushed + `Rt.fail` runs them too. A buffered `lib/Out.raz`: 4 KB, flushed at each newline when standard output is a terminal, when full, by `Out.flush`, and at exit. The report says how to mix `Out` with C's `stdio`: flush one before using the other. - [x] 12. `F32`: arithmetic, conversions, calls; real literals become untyped constants that take `F32` or `F64`. -- [x] 13. A thread-safe `lib/Heap.jed`: its bad sizes refused, and a +- [x] 13. A thread-safe `lib/Heap.raz`: its bad sizes refused, and a marker in each block's header so that freeing a block twice, or one it never gave out, stops the program; `Out` locks its buffer. An example with threads from `pthread_create`. Native threads for programs without C, in - `lib/Thread.linux-x86_64.jed`: `spawn` on an `mmap`ed stack with + `lib/Thread.linux-x86_64.raz`: `spawn` on an `mmap`ed stack with a guard page, through `clone` and a small code procedure; `join` and a `Mutex` through `futex`. `link static;` marks a module that needs a program without C; the compiler refuses a program that @@ -131,22 +132,22 @@ - [x] 15. Versions first: the report says its version, by date (`2026-10.0`, then `.1` for the next change that month), and - ends with what each version changed; `jed --version` prints its - own and the report's, `jed 0.3.0, report 2026-10.0`. Each + ends with what each version changed; `raz --version` prints its + own and the report's, `raz 0.3.0, report 2026-10.0`. Each finished stage is tagged, `v0.3.0` for stage 3. Then - `tools/Doc.jed`, a jed program: prints a module's own + `tools/Doc.raz`, a raz program: prints a module's own comment, the one before `module`, then its exported declarations, each with the comment just before it; and pulls - out the examples of `doc/jed.md` that are whole modules. + out the examples of `doc/raz.md` that are whole modules. `make check` also compiles those examples, running the ones with a `main`, and runs each library module's `main` as its test. The test runner stays in the Makefile: it must work when the compiler doesn't. (Tagging is left for later, at the owner's word.) -- [x] 16. Editor support: `editor/vim` (`syntax/jed.vim`, `indent/jed.vim` - by `shiftwidth()`, and `ftdetect/jed.vim`, which sets 4 spaces) - and `editor/emacs/jed-mode.el` (indenting by `jed-indent-offset`, +- [x] 16. Editor support: `editor/vim` (`syntax/raz.vim`, `indent/raz.vim` + by `shiftwidth()`, and `ftdetect/raz.vim`, which sets 4 spaces) + and `editor/emacs/raz-mode.el` (indenting by `raz-indent-offset`, 4 unless set). Both colour reserved words, basic types, built-in procedures, numbers, characters, strings and nested comments. `make check` loads each, headless, on the examples. And a stress @@ -163,10 +164,10 @@ Later -- [x] 18. `tools/Pretty.jed`, a formatter that keeps every line break +- [x] 18. `tools/Pretty.raz`, a formatter that keeps every line break and comment where it is: it fixes indentation (4 spaces a level) and the spaces around operators and after `,` and `;`, and - leaves formatted code as it is. It shares with `Doc.jed` a - scanner that keeps comments, `tools/Scan.jed`. `make fmt` checks + leaves formatted code as it is. It shares with `Doc.raz` a + scanner that keeps comments, `tools/Scan.raz`. `make fmt` checks that `lib/`, `examples/` and `tools/` come through unchanged, and `make check` does too, with the cases in `test/pretty`. diff --git a/README.md b/README.md index 9d2c4a7..ec633c1 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ -# jed +# raz -jed (Polish *jeden*, one) is a small systems language in Wirth's -tradition, for x86-64 Linux. A jed program can lay a record over a +raz (Polish for *one*, as in counting) is a small systems language in Wirth's +tradition, for x86-64 Linux. A raz program can lay a record over a device's registers, read and write memory exactly as written, take part in lock-free algorithms, make system calls and call C libraries. It has no garbage collector and no hidden run time: what the program does is @@ -20,7 +20,7 @@ ``` $ make - $ ./jed examples/Hello.jed + $ ./raz examples/Hello.raz $ examples/Hello hello, world @@ -33,13 +33,13 @@ | Path | What | |---|---| -| `doc/jed.md` | The language report: the definition of jed | +| `doc/raz.md` | The language report: the definition of raz | | `doc/compiler.md` | A guide to reading the compiler, file by file | | `src/` | The compiler, in Free Pascal | -| `lib/` | The library, in jed; the compiler finds it beside itself | +| `lib/` | The library, in raz; the compiler finds it beside itself | | `examples/` | Small programs, each with the output it should give | -| `tools/Doc.jed` | Prints what a module exports, with its comments | -| `tools/Pretty.jed` | The formatter: fixes indentation and spacing | +| `tools/Doc.raz` | Prints what a module exports, with its comments | +| `tools/Pretty.raz` | The formatter: fixes indentation and spacing | | `editor/` | Support for vim and emacs | | `test/` | Tests, and the scripts that run them | | `PLAN.md` | How the compiler was built, step by step | @@ -49,7 +49,7 @@ The compiler needs Free Pascal 3.2.2 (`apt-get install fp-compiler`) and builds into the repository's root: - make # ./jed + make # ./raz The tests need a shell and Python 3; the editor checks run if vim or emacs is installed. @@ -57,25 +57,25 @@ make check # every example and test, against what it should give make bench # the compiler's speed on a program of 350,000 lines make stress # 40,000 threads, started and joined - make gdb # gdb stops at a line of jed and names it + make gdb # gdb stops at a line of raz and names it make fmt # the library, examples and tools are formatted make loc # the compiler's lines make tests # tests of the scanner, encoder and linker on their own ## Using it - jed [-I dir]... [-o file] Main.jed - jed run [-I dir]... Main.jed [arg]... - jed --version + raz [-I dir]... [-o file] Main.raz + raz run [-I dir]... Main.raz [arg]... + raz --version -`jed Main.jed` compiles module `Main` and every module it imports, and -writes the executable `Main`. A module `Name` lives in `Name.jed`, found +`raz Main.raz` compiles module `Main` and every module it imports, and +writes the executable `Main`. A module `Name` lives in `Name.raz`, found in the main module's directory, then in each `-I` directory, then in `lib`. A module whose code depends on the system comes in one file per -target, `Name.linux-x86_64.jed` before `Name.jed`; the compiler checks +target, `Name.linux-x86_64.raz` before `Name.raz`; the compiler checks that all of them export the same things. -`jed run Main.jed a b` compiles the same way, then runs the program +`raz run Main.raz a b` compiles the same way, then runs the program with the arguments `a b`, writing no file: its output and exit status are the command's. @@ -102,40 +102,40 @@ - `extern` procedures and variables from C; code procedures written as bytes of machine code; `SYSCALL`. -The report, `doc/jed.md`, says all of it in about 900 lines. +The report, `doc/raz.md`, says all of it in about 900 lines. ## The library `Rt` (ending the program, checks), `Sys` (system calls), `Out` (buffered output), `C`, `Lock`, `Thread` (threads without C), `Mem`, `Heap`, `Arena`, `Str`, `Buf`, `Fmt`, `List(T)` and `Map(K, V; hash, -eq)`. `tools/Doc.jed` prints any of them: +eq)`. `tools/Doc.raz` prints any of them: - $ ./jed -o Doc tools/Doc.jed && ./Doc lib/Str.jed + $ ./raz -o Doc tools/Doc.raz && ./Doc lib/Str.raz Each library module's `main` is its test, which `make check` runs. ## Editors `editor/vim` holds a syntax file, an indent file and file type -detection: add it to `runtimepath`. `editor/emacs/jed-mode.el` is a -major mode: put it on `load-path` and `(require 'jed-mode)`. Both +detection: add it to `runtimepath`. `editor/emacs/raz-mode.el` is a +major mode: put it on `load-path` and `(require 'raz-mode)`. Both colour the language and indent it as the examples are indented. -`tools/Pretty.jed` formats a whole file the same way: it fixes the +`tools/Pretty.raz` formats a whole file the same way: it fixes the indentation, 4 spaces a level, and the spaces around operators and after `,` and `;`, and keeps every line break and comment where it is. - $ ./jed -o Pretty tools/Pretty.jed - $ ./Pretty Module.jed # prints it, formatted - $ ./Pretty -w *.jed # rewrites those that aren't, and names them + $ ./raz -o Pretty tools/Pretty.raz + $ ./Pretty Module.raz # prints it, formatted + $ ./Pretty -w *.raz # rewrites those that aren't, and names them ## Versions The compiler says which version of the report it follows: - $ ./jed --version - jed 0.3.0, report 2026-10.0 + $ ./raz --version + raz 0.3.0, report 2026-10.0 A version of the report is named by its month and a count; the report's last section says what each version changed. @@ -145,3 +145,7 @@ Other systems and processors (Mach-O, PE, aarch64), an optimizer, separate compilation, records passed to C by value, thread-local variables, and type information for debuggers. + +## License + +ISC; see `LICENSE`. diff --git a/doc/compiler.md b/doc/compiler.md index 4822447..9aa57d0 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -1,9 +1,9 @@ -# Reading the jed compiler +# Reading the raz compiler The compiler is eight files of Free Pascal, under 5,000 lines of code. This guide walks through them in the order they are best read: from the characters of a source file to the bytes of an executable. It assumes -you know the language from `doc/jed.md`, and enough x86-64 to read a +you know the language from `doc/raz.md`, and enough x86-64 to read a disassembly. | File | Lines | Code | What | @@ -15,7 +15,7 @@ | `src/parse.pas` | 1,816 | 1,685 | Declarations, statements, expressions, built-ins | | `src/link.pas` | 131 | 95 | Tree shaking, layout, patching | | `src/elf.pas` | 425 | 351 | Static and dynamic ELF, symbol table, line numbers | -| `src/jed.pas` | 214 | 169 | The command line, the entry points | +| `src/raz.pas` | 214 | 169 | The command line, the entry points | Every file opens with a comment that says what it is, what it depends on and what it leaves out. Read those first; they are the map. @@ -47,20 +47,20 @@ ## Following one program -`jed Hello.jed` does this: +`raz Hello.raz` does this: -1. `jed.pas` reads the command line and calls `CompileMain` +1. `raz.pas` reads the command line and calls `CompileMain` (`parse.pas`). 2. `CompileMain` imports `Rt` first, since every program needs it, and - then compiles `Hello.jed` with `CompileFile`. + then compiles `Hello.raz` with `CompileFile`. 3. `CompileFile` opens the file in the scanner and parses the module. - At `import Out;` it calls `ImportModule`, which finds `Out.jed` and + At `import Out;` it calls `ImportModule`, which finds `Out.raz` and compiles it there and then, saving and restoring the scanner and the scopes around it. So modules are finished in an order where each comes after those it imports; that is the order their bodies run. 4. Each procedure becomes a chunk of code; `Out.str("hello, world\n")` becomes a string chunk, a call, and a fixup to `Out.str`'s chunk. -5. Back in `jed.pas`, `Use` marks the modules the program uses; the +5. Back in `raz.pas`, `Use` marks the modules the program uses; the entry point, `_start`, is written as one more chunk: save `argc` and `argv`, call every used module's body, call `main`, call `Rt.exit`. 6. `WriteElf` (`elf.pas`) has `link.pas` mark what `_start` reaches, @@ -325,9 +325,9 @@ compile unit gdb needs to find it. There are no types or variables in it; gdb can stop at a line and show where it is, not print a variable. -## jed.pas: the command line +## raz.pas: the command line -`jed.pas` parses the arguments, calls `CompileMain`, and works out what +`raz.pas` parses the arguments, calls `CompileMain`, and works out what the program uses: `Use` marks the modules imported from the main module and `Rt`; `UsesC` decides whether the program is dynamic, refusing one that both uses C and has a module saying `link static`. Then it writes @@ -336,9 +336,9 @@ start-up does, which sets C up and calls back a `main` that runs the module bodies and the program's `main`. -`jed run` writes the executable to a memfd, a file only in memory, and -executes it through `/proc/self/fd` in jed's own place, handing it the -rest of jed's `argv`. Nothing is left on disk, and the program's +`raz run` writes the executable to a memfd, a file only in memory, and +executes it through `/proc/self/fd` in raz's own place, handing it the +rest of raz's `argv`. Nothing is left on disk, and the program's status is the command's. ## Where to start changing it @@ -351,6 +351,6 @@ in the same order), a case in `Statement`, and a routine beside the others. - **A check that fails:** `Check` in `gen.pas`, and the message in - `lib/Rt.jed`'s `fail`. + `lib/Rt.raz`'s `fail`. After any change: `make check`, `make bench`, `make loc`. diff --git a/doc/jed.md b/doc/jed.md deleted file mode 100644 index f915ad5..0000000 --- a/doc/jed.md +++ /dev/null @@ -1,907 +0,0 @@ -# The programming language jed - -jed is a small systems language for x86-64 Linux. A jed program can lay -a record over a device's registers, read and write memory exactly as -written, take part in lock-free algorithms, make system calls and call -C libraries. It has no garbage collector and no hidden run time: what -the program does is what its text says. - -This report defines the language. It is short on purpose. Whatever it -doesn't allow, jed doesn't have. - -This is version 2026-10.0 of the report; section 12 says what each -version changed. - -## 1. A first look - -``` -module Hello; -import Out; - -proc main*; -begin - Out.str("hello, world\n"); -end; - -end Hello. -``` - -A program is a set of modules. The one named on the command line is -the main module, and it exports a procedure `main`; the program starts -there, once every module's body has run (section 3). Saved as -`Hello.jed`, it is compiled with `jed Hello.jed`, which writes the -executable `Hello`. - -## 2. Words and symbols - -A program is written in UTF-8. The compiler rejects a file that isn't -valid UTF-8: a malformed or overlong sequence, a surrogate, or a code -point beyond 10FFFFH. Everything outside strings, characters and -comments is ASCII. Spaces, tabs and line breaks separate symbols and -are otherwise ignored. - -**Identifiers** are an ASCII letter or `_` followed by letters, digits -and `_`, up to 63 characters. Case matters: `count` and `Count` are different -names. - -**Reserved words** are lowercase, except `VOLATILE`: - -``` -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 -``` - -**Numbers.** `123` is decimal. `0FFH` is hexadecimal: it starts with a -digit and ends in `H`. `1.5` and `2.0E-3` are reals; a real always has -a digit on both sides of its point. - -An integer is an untyped constant, which takes the type it is used as, -up to the largest `I64`. A hexadecimal number above that, such as -`0FFFFFFFFFFFFFFFFH`, has type `U64`: so `-1` never fits a `U64`, and -the big number goes nowhere else without a conversion. - -A real is an untyped constant too, which takes `F32` or `F64`, -whichever it is used as, rounded to the nearest value of that type; -where nothing says which, it is an `F64`. A real never becomes an -integer, nor an integer a real, without a conversion: `x := 1;` is an -error for `x: F64`, and `x := 1.0;` is right. - -**Characters.** `'a'` is the code point of one character, an integer: -`'a'` is 97 and `'é'` is 233. - -**Strings.** `"héllo\n"` is a sequence of bytes, the UTF-8 of its text: -`"é"` is the two bytes 0C3H, 0A9H. Both characters and strings take the -escapes `\n` (line feed), `\t` (tab), `\r` (carriage return), `\0` -(zero), `\\`, `\'`, `\"`, `\u{H...}` (the code point with hexadecimal -value H..., in a string its UTF-8) and, in strings only, `\xHH` (the -byte with hexadecimal value HH, which needn't make valid UTF-8). - -Error messages give the line and the column, counted in characters. - -**Comments** are `(*` ... `*)` and nest. By convention, the comment -just before an exported declaration is its documentation, and the one -before `module` is the module's. - -**Operators and delimiters:** - -``` -+ - * / = # < <= > >= := : ; , . .. ... ( ) [ ] { } ^ | -``` - -## 3. Modules - -``` -Module = "module" ident [ "(" ModParams ")" ] ";" - { Import } { Link } { Declaration } - [ "begin" Statements ] "end" ident "." . -ModParams = ident { "," ident } { ";" ident ":" "proc" Signature } . -Import = "import" ImportItem { "," ImportItem } ";" . -ImportItem = ident [ ":=" ident [ "(" Type { "," Type } ")" ] ] . -Link = "link" ( string | "static" ) ";" . -``` - -A module lives in a file of its own name: module `Out` is `Out.jed`. -The name after `end` repeats the module's name. - -**Exports.** A name declared at the top of a module with `*` after it -is exported: other modules can use it as `Module.name`. Record fields -are exported the same way. Everything else is private to the module. - -**Imports.** `import Out;` makes `Out`'s exports available as `Out.x`. -`import O := Out;` uses the name `O` instead. A module can't import -itself, directly or through others. - -**Generic modules** take types as parameters: - -``` -module List(T); -type - Node* = record next*: ^Node; val*: T; end; -... -end List. -``` - -An import gives the arguments: `import Ints := List(I64);`. Each -distinct list of arguments makes one *instance*: the module compiled -with `T` standing for `I64`. Two imports of `List(I64)`, in any modules, -share one instance. Since every instance is checked on its own, an -operation the argument type doesn't support (adding two records, say) -is reported as an error in that instance. - -What a generic module needs to do with its types, beyond moving them -about, it is given as procedures, after the types: - -``` -module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL); -``` - -``` -import Names := Map([]U8, I64, Str.hash, Str.eq); -``` - -A procedure argument names a procedure, not a variable or an -expression, and its signature, with the type arguments put in, must be -the parameter's. Inside the module, `hash(k)` calls it directly. Two -imports make the same instance only if their types and their procedures -are the same. - -**Finding modules.** The compiler looks for module `Name` in the main -module's directory, then in each directory given with `-I`, then in the -`lib` directory beside the compiler. In each directory it takes the -first of `Name.OS-ARCH.jed`, `Name.OS.jed`, `Name.ARCH.jed` and -`Name.jed` that exists, where `OS-ARCH` is the target, for now only -`linux-x86_64`. So a module whose code depends on the machine or the -system comes in one file per target, and the modules that import it -don't change. Machine code (section 8) and system calls belong in such -files. - -The compiler holds every file of such a module to the same interface. -When it takes one of `Name.*.jed`, it also reads the declarations of -the others beside it, and of `Name.jed` if there is one, and reports an -error unless they all export the same names, each the same kind of -thing: - -- a constant of the same type (its value may differ: a system call - number, say); -- a type of the same kind, and for a record or variant the same - exported fields and cases, with the same types (unexported fields, - and so the size and layout, may differ); -- a variable of the same type; -- a procedure of the same signature. - -Two types here are the same if they are built alike, a name in one file -standing for the same name in another. - -**Module bodies.** A module may end with `begin` and statements, its -body. Every module's body runs once, before the main module's `main`: -a module's body runs after the bodies of the modules it imports, in the -order of its `import`s, and once however many modules import it. Each -instance of a generic module has its body run once. Module variables -are zero before any body runs. `return;` ends a body early. - -**`link "libX11.so.6";`** names a shared library to load at run time, -for the `extern` declarations of section 9. **`link static;`** says the -module needs a program without C (section 10): it makes its own system -calls, or its own threads, which the C library wouldn't know about. - -## 4. Declarations - -``` -Declaration = "const" { IdentDef [ ":" "ERROR" ] "=" Expr ";" } - | "type" { IdentDef "=" Type ";" } - | "var" { IdentList ":" Type ";" } - | ProcDeclaration ";" - | ExternDeclaration ";" . -IdentDef = ident [ "*" ] . -IdentList = IdentDef { "," IdentDef } . -``` - -A name must be declared before it is used, with two exceptions: the -base type of a pointer may name a type declared later in the same -`type` section (so that two records can point at each other), and a -procedure may be declared `forward` and defined later (section 8). - -**Constants** are evaluated by the compiler. Their expressions use only -literals, other constants, operators, `SIZE` and the `LEN` of arrays. - -**Variables** of a module live as long as the program; variables of a -procedure live as long as its call. Both start at zero: every byte of -them is zero. So a number starts as `0` (`0.0` for `F32` and `F64`), -a `BOOL` as `false`, a pointer, procedure or `ERROR` as `nil`, a slice -as the empty slice (`ptr` is `nil`, `len` is 0), a variant as its -first case with its fields zero, a set as the empty set, and an -enumeration as its first name. No variable is ever read before it has a value. - -## 5. Types - -``` -Type = QualIdent - | "[" Expr "]" Type (* array *) - | "[" "]" Type (* slice *) - | "^" [ "VOLATILE" ] Type (* pointer *) - | [ "packed" ] "record" { IdentList ":" Type ";" } "end" - | "variant" { Case ";" } "end" - | "(" ident { "," ident } ")" (* enumeration *) - | "set" "of" QualIdent - | "proc" Signature . -Case = ident [ "(" FieldList { ";" FieldList } ")" ] . -FieldList = ident { "," ident } ":" Type . -QualIdent = [ ident "." ] ident . -``` - -### 5.1 Basic types - -| Type | Size | Values | -|---|---|---| -| `I8` `I16` `I32` `I64` | 1, 2, 4, 8 | signed integers, two's complement | -| `U8` `U16` `U32` `U64` | 1, 2, 4, 8 | unsigned integers | -| `BOOL` | 1 | `false` (0), `true` (1) | -| `F32` | 4 | IEEE 754 single precision | -| `F64` | 8 | IEEE 754 double precision | - -### 5.2 Arrays - -`[n]T` is `n` elements of type `T`, one after another. `n` is a -constant greater than zero. Arrays are values: assigning one copies it. - -### 5.3 Slices - -`[]T` is a view of elements that live elsewhere: a pointer to the first -and a count, 16 bytes in all. - -``` -Slice = record ptr: ^T; len: I64; end; (* its layout *) -``` - -A slice is made from an array (`a[2..5]`, or an array used where a -slice is wanted), from another slice, or from a pointer (`p[0..n]`). It -doesn't own what it points at. - -### 5.4 Pointers - -`^T` is the address of a `T`, 8 bytes. `nil` is the pointer to nothing. - -`^VOLATILE T` is the address of a `T` that something besides the -program may read or change: a device register, memory shared with -another process. Section 7.6 says what that promises. - -### 5.5 Records - -``` -type Cell = record ch: U8; attr: U8; end; -``` - -Fields are laid out in order as C lays them out: each at the next -multiple of its own alignment, and the whole record padded to a -multiple of its largest alignment. A record declared like a C struct -has the same layout as that struct. - -A `packed record` has no padding: each field starts at the byte after -the field before it, and the record's alignment is 1. A field of a -packed record may be misaligned. x86-64 reads and writes it anyway, but -an atomic operation on it is slow, and a volatile access to it is one -instruction that needn't be atomic. - -### 5.6 Variants - -A variant holds one of several cases, each with its own fields: - -``` -type - Shape* = variant - circle(r: F64); - rect(w, h: F64); - dot; - end; -``` - -The case names are declared in the scope around the type, so `circle` -can be used directly, and as `Shapes.circle` from another module if -`Shape` is exported. A case with fields is built by calling it like a -procedure, `circle(2.0)`; a case without fields is just `dot`. The only -way to read the fields is `match` (section 7.4). - -Layout: an `I64` tag (0 for the first case, 1 for the second, and so -on) followed by the fields of the largest case, laid out as a record. -A variant that starts at zero therefore holds its first case. - -### 5.7 Enumerations and sets - -``` -type - Color* = (red, green, blue); - Colors* = set of Color; -``` - -An enumeration is a list of names, in order. Like the cases of a -variant, the names are declared in the scope around the type. An -enumeration has at most 256 names and takes 1 byte; the first name is -0, the next 1, and so on. - -`set of E`, for an enumeration `E` of at most 64 names, holds any -choice of `E`'s names: bit `i` stands for the name at position `i`. It -takes the smallest of 1, 2, 4 and 8 bytes that has a bit for each name, -so a set can stand for a C flags word. - -### 5.8 Errors - -``` -const NotFound*: ERROR = "not found"; -``` - -`ERROR` is a basic type of 8 bytes. A value of it is made only by a -constant declared as above, and each such declaration makes an error -different from every other, whatever its message: two modules that -both declare `"not found"` have two different errors. A generic module -makes its errors once per instance. `nil` is no error. - -Errors compare with `=` and `#` only, by which declaration made them, -never by their message. `MSG(e)` is the message, a `[]U8`; `MSG(nil)` -is `""`. - -``` -proc find*(key: I64): (^Node, ERROR); -... -n, err := Table.find(7); -if err = Table.NotFound then ... end; -``` - -### 5.9 Procedure types - -``` -type Compare = proc(a, b: I64): BOOL; -``` - -A value of a procedure type is the address of a procedure with that -signature, 8 bytes, or `nil`. - -### 5.10 Same and assignable - -Two named types are the same only if they are the same declaration. -Two anonymous types are the same if they are built alike: `^I64` is -`^I64` wherever it is written. A named and an anonymous type are the -same if the named one is built like the anonymous one, so that -`p := ADR(n)` works for `p: NodePtr` with `type NodePtr = ^Node`. - -A type declared with only a name on the right, `type Count = I64;`, is -another name for that type, not a new one. - -A value of type `A` can be assigned to a variable of type `B` (and -passed to a parameter of type `B`, and returned as a `B`) if they are -the same type, or if: - -- `A` is an integer constant whose value fits in the integer type `B`; -- `A` is `nil` and `B` is a pointer, procedure or `ERROR` type; -- `A` is `^T` and `B` is `^VOLATILE T`; -- `A` is `[n]T` and `B` is `[]T`; -- `A` is a string literal and `B` is `[]U8`, `^U8` (a pointer to the - bytes followed by a zero byte, as C wants), or `[n]U8` with `n` at - least the string's length (the rest is zero); -- `A` is a procedure and `B` a procedure type with the same signature. - -Nothing else converts silently. In particular, there is no conversion -between integer types, between integers and reals, or between `F32` -and `F64`, without a written conversion (section 6.7). - -## 6. Expressions - -``` -Expr = SimpleExpr [ Relation SimpleExpr ] . -Relation = "=" | "#" | "<" | "<=" | ">" | ">=" | "in" . -SimpleExpr = [ "-" ] Term { AddOp Term } . -AddOp = "+" | "-" | "or" | "xor" . -Term = Factor { MulOp Factor } . -MulOp = "*" | "/" | "div" | "mod" | "and" | "shl" | "shr" . -Factor = number | char | string | Designator | "(" Expr ")" - | "not" Factor - | "[" [ Expr { "," Expr } ] "]" - | "{" [ Element { "," Element } ] "}" - | "^" [ "VOLATILE" ] Type "(" Expr ")" . -Element = Expr | ident ":" Expr . -Designator = QualIdent { Selector } . -Selector = "." ident | "^" | "[" Expr [ ".." Expr ] "]" - | "(" [ Expr { "," Expr } ] ")" . -``` - -The operators bind in the order of the grammar: `not` most tightly, -then the multiplying operators, then the adding ones, then the -relations. So `a + b * c = d` is `(a + (b * c)) = d`. A unary minus -applies to the first term: `-a * b` is `-(a * b)`. - -### 6.1 Integers - -Both operands of `+ - * div mod and or xor` have the same integer -type, or one is an untyped constant that takes the other's type. The -result has that type and wraps around at its width: in `U8`, -`200 + 100` is `44`. - -`div` rounds toward zero and `mod` takes the sign of the dividend, as -in C: `-7 div 2` is `-3`, `-7 mod 2` is `-1`. Dividing by zero, and -dividing the smallest `I64` by `-1`, stop the program (`SIGFPE`). - -`and`, `or`, `xor` and `not` work on every bit. `x shl n` and -`x shr n` shift by `n and 63`; `shr` brings in copies of the sign bit -for signed types and zeros for unsigned ones. - -Relations compare as signed or unsigned according to the type. - -### 6.2 Booleans - -`and` and `or` on `BOOL` evaluate their right operand only when it -decides the result. `not` negates, `xor` is "different", and `=` and -`#` compare. - -### 6.3 Reals - -`+ - * /` and the relations work on `F32` and on `F64`. Both operands -have the same type, or one is a real constant, which takes the other's -type (section 2). The result has that type: `F32` arithmetic is done in -single precision, rounded at each step as C rounds `float`. A -constant expression of reals is evaluated in double precision, then -rounded once to the type it takes. - -### 6.4 Pointers - -- `p^` is the variable `p` points at. -- `p + i` and `p - i`, with `i` an integer, move `p` by `i` elements: - by `i * SIZE(T)` bytes for `p: ^T`. -- `p - q`, with both of the same pointer type, is the number of - elements between them, an `I64`. -- `p[i]` is `(p + i)^`. `p[lo..hi]` is the slice of the `hi - lo` - elements from `p + lo`. Neither is checked. A pointer to an array - isn't indexed this way, since a step would be a whole array: its - elements are `p^[i]`. -- Pointers compare with `= # < <= > >=` as unsigned addresses. - Procedure values compare with `=` and `#` only. - -### 6.5 Arrays and slices - -`a[i]` is an element of an array or slice, and `a[lo..hi]` is the slice -of the elements from `lo` up to but not including `hi`. Both are -checked: `i` must be below the length, and `0 <= lo <= hi <= length`. -A check that fails prints the file and line to standard error and stops -the program with status 2. - -**Literals.** `[e1, e2, ...]` builds an array, and `{f: e, g: e, ...}` -a record, where the type it must have is known: assigned to a variable, -passed to a parameter, returned, compared with a value of that type, or -an element of a bigger literal. The elements must be assignable to the -element type, and an array literal for `[n]T` has exactly `n` of them. -A record literal names its fields, in any order, each at most once; the -fields it leaves out are zero. An array literal used as a slice is a -hidden variable of the procedure, and lives as long as its call. - -``` -c := {ch: 'A', attr: 7}; -Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)]); -``` - -**Strings compare.** Two operands that are each a `[]U8`, a `[n]U8` or -a string literal are `=` when they have the same length and the same -bytes, and `#` otherwise. Other arrays and slices, records and variants -can't be compared; write a loop. Ordering strings is the library's -`Str.cmp`. - -### 6.6 Enumerations and sets - -Enumerations compare with all six relations, by position, and an -enumeration can be the variable of a `for` loop and the expression of a -`match` (section 7.4). - -`{red, blue}` is a set, of the set type of its names' enumeration; -`{}` is the empty set, where the type it must have is known. On two sets -of the same type, `+` is union, `*` intersection and `-` difference; -`=` and `#` compare, and `<=` and `>=` are "is a subset of" and "is a -superset of". `x in s` is `true` if the name `x` is in the set `s`. - -### 6.7 Conversions - -A type name applied like a procedure converts: `I32(x)`, `F64(n)`, -`^Cell(addr)`. A pointer type written out uses the `^` form of the -grammar: `^VOLATILE U32(0FEE00000H)`. - -| From | To | Result | -|---|---|---| -| integer | integer | the value cut to the new width, or extended by its sign (signed) or zeros (unsigned) | -| integer | `F32`, `F64` | the nearest real | -| `F32`, `F64` | integer | rounded toward zero; a NaN, or a real out of the range of `I64`, gives the smallest `I64`, then cut | -| `F32` | `F64` | the same value | -| `F64` | `F32` | the nearest `F32`; too big a value gives an infinity | -| enumeration | integer | its position | -| integer | enumeration | the name at that position; a position out of range is a failed check (6.5) | -| set | integer | its bits | -| integer | set | the low bits, as many as the set has | -| integer | pointer, procedure | the address | -| pointer, procedure | integer | the address | -| pointer, procedure | pointer, procedure | the same address, seen as the new type | - -### 6.8 Built-in procedures - -| Call | Result | -|---|---| -| `SIZE(T)` | the size of type `T` in bytes, a constant | -| `ADR(x)` | the address of variable `x`, a `^T` | -| `LEN(a)` | the number of elements of an array (a constant) or a slice, an `I64` | -| `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 | -| `MSG(e)` | the message of the error `e`, a `[]U8` | -| `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`) | -| `INC(v)`, `INC(v, k)` | adds 1, or `k`, to the integer variable `v`; it wraps, like `+` | -| `DEC(v)`, `DEC(v, k)` | subtracts 1, or `k`, from `v` | -| `FENCE` | a full memory barrier | -| `CAS(p, old, new)` | if `p^ = old`, sets `p^ := new` and returns `true`; atomically | -| `XCHG(p, x)` | sets `p^ := x` and returns the value before, atomically | -| `XADD(p, x)` | adds `x` to `p^` and returns the value before, atomically | -| `ARGC()` | the number of command line arguments, an `I64` | -| `ARGV()` | the arguments, a `^^U8` (C strings) | - -`SYSCALL` exists only on Linux targets. Other systems have no stable -system call interface, and their modules call the C library instead -(section 9). - -`INC` and `DEC` evaluate `v` once, so `INC(a[f(i)])` calls `f` once. They -read `v` and then write it: two accesses, even through a `^VOLATILE` -pointer, and not atomic; `XADD` is the atomic one. - -For `CAS`, `XCHG` and `XADD`, `p` is a `^T` or `^VOLATILE T` where `T` -is an 8-byte integer or pointer type (an integer type for `XADD`). They -are sequentially consistent. - -## 7. Statements - -``` -Statements = { Statement ";" } . -Statement = Designator [ ":=" Expr ] - | Designator "," Designator { "," Designator } ":=" Expr - | "if" Expr "then" Statements - { "elsif" Expr "then" Statements } [ "else" Statements ] "end" - | "while" Expr "do" Statements "end" - | "repeat" Statements "until" Expr - | "for" ident ":=" Expr "to" Expr [ "by" Expr ] "do" Statements "end" - | "match" Expr "of" { "|" Arm } "end" - | "return" [ Expr { "," Expr } ] - | "break" - | "defer" Statement . -Arm = ( ident [ "(" ident { "," ident } ")" ] | "else" ) ":" Statements . -``` - -Every statement ends in `;`, including the ones that end in `end` or -`until`. - -### 7.1 Assignment and calls - -`x := e` evaluates `e` and stores it in `x`; arrays, records, slices and -variants are copied. A designator on its own is a call, and any result -it returns is dropped: `Out.ln;`, `write(fd, buf);`. - -`a, b := f(x);` assigns the results of a procedure that returns several -(section 8), in order. - -### 7.2 Conditions and loops - -`if`, `while` and `repeat` take `BOOL` expressions. `repeat` runs its -body at least once and stops when the condition is true. - -`for i := a to b by s do ... end;` sets the integer variable `i` to `a`, -`a + s`, ... while `i <= b` (or `i >= b` if the constant `s` is -negative). `s` is 1 if left out. `b` is evaluated once, before the -first round. - -`break` ends the innermost `while`, `repeat` or `for` it stands in, -and the program goes on after it. There is no `goto`. - -### 7.3 Return - -`return e;` ends the procedure with the result `e`; `return a, b;` with -several results; `return;` from a procedure without results. A -procedure with results that runs off its end returns zeros, each result -as a variable of its type starts (section 4). - -### 7.4 Match - -``` -match s of -| circle(r): area := 3.14159 * r * r; -| rect(w, h): area := w * h; -| dot: area := 0.0; -end; -``` - -`match` runs the arm of the case `s` holds. An arm may name the case's -fields, in order, all of them; the names stand for those fields of `s` -itself, so assigning to one changes `s`. An arm may also leave the -fields unnamed. Every case must have an arm, unless there is an -`| else:` arm, which must come last. - -`match` on an enumeration works the same way: each arm names one of the -enumeration's names. - -### 7.5 Order of evaluation - -Operands, arguments and the designators of an assignment are evaluated -from left to right. - -### 7.6 Volatile - -A variable reached through a `^VOLATILE T` is volatile, and so is any -field or element of it. Each read or write of a volatile variable of a -basic, enumeration, set or pointer type is exactly one memory access, -of exactly its size, and volatile accesses happen in the order the -program writes them. Copying a whole record or array through a -volatile pointer is not allowed, since it can't be one access. - -A `^VOLATILE T` doesn't convert to `^T` without a written conversion. - -`FENCE` also orders the program's ordinary accesses against those of -other processors and devices. - -### 7.7 Defer - -`defer s;` runs the statement `s` when the program leaves the statement -list the `defer` stands in: at its end, or by a `return`, or by a -`break` out of it. Statements deferred in the same list run in the -opposite order to their `defer`s, and only those whose `defer` has been -reached run. - -``` -module Head; -import Sys, Out; - -(* Prints the first line of the file at path. *) -proc head(path: []U8): BOOL; -var fd, n, i: I64; buf: [256]U8; -begin - fd := Sys.openRead(path); - if fd < 0 then return false; end; - defer Sys.close(fd); - n := Sys.read(fd, buf); - if n < 0 then return false; end; - for i := 0 to n - 1 do - if buf[i] = 10 then n := i; break; end; - end; - Out.str(buf[0..n]); - Out.ln; - return true; -end; - -proc main*; -begin - if not head("/etc/hostname") then Out.str("no hostname\n"); end; -end; - -end Head. -``` - -`return e;` evaluates `e` before the deferred statements run. A -deferred statement can't contain `return`, `break` or `defer` that -would leave it. - -## 8. Procedures - -``` -ProcDeclaration = "proc" IdentDef Signature ";" - ( "forward" | { LocalDeclaration } "begin" Statements "end" [ ident ] - | "code" Expr { "," Expr } ) . -LocalDeclaration = "const" { ident [ ":" "ERROR" ] "=" Expr ";" } - | "type" { ident "=" Type ";" } - | "var" { ident { "," ident } ":" Type ";" } . -Signature = "(" [ Params { ";" Params } [ ";" "..." ] ] ")" [ ":" Results ] - | [ ":" Results ] . -Params = [ "var" ] ident { "," ident } ":" Type . -Results = Type | "(" Type { "," Type } ")" . -``` - -A procedure without parameters may leave out the parentheses, both -where it is declared (`proc main*;`) and where it is called (`Out.ln`). -Used without parentheses in an expression, a procedure is a procedure -value, not a call. - -**Parameters.** A value parameter is a copy: the procedure may change -it, and the caller's variable stays as it was. A `var` parameter is the -caller's variable itself; its argument must be a variable of exactly -the parameter's type. - -**Results.** A procedure returns nothing, one value, or several. A call -that returns several values can only stand on the right of a multiple -assignment, or alone as a statement. - -``` -module Divide; -import Out; - -proc divmod(a, b: I64): (I64, I64); -begin - return a div b, a mod b; -end; - -proc main*; -var q, r: I64; -begin - q, r := divmod(17, 5); - Out.int(q); Out.str(" rest "); Out.int(r); Out.ln; -end; - -end Divide. -``` - -**forward.** `proc f(x: I64): I64; forward;` declares `f` so that it -can be called before its body appears; the body comes later with the -same signature. - -Procedures don't nest. - -**Code procedures.** A procedure whose body is `code` and a list of -constant bytes is machine code, written by hand: - -``` -proc rdtsc*: U64; -code 0FH, 31H, (* rdtsc *) - 48H, 0C1H, 0E2H, 20H, (* shl rdx, 32 *) - 48H, 09H, 0D0H, (* or rax, rdx *) - 0C3H; (* ret *) -``` - -It is called like any procedure, with the System V convention: integer -and pointer arguments arrive in `rdi`, `rsi`, `rdx`, `rcx`, `r8` and -`r9`, `F32` and `F64` ones in `xmm0` to `xmm7`, and the result goes in -`rax` (and `rdx` for a second) or `xmm0`. Its parameters and results -are therefore of the types C can take (section 9), at most six integer -and eight real parameters, and at most two results. The bytes are the whole -procedure, `ret` included; they must keep `rbx`, `rbp`, `rsp` and `r12` -to `r15` as they found them. The compiler doesn't look inside them. - -## 9. Calling C - -``` -ExternDeclaration = "extern" ( "proc" IdentDef Signature - | "var" IdentDef ":" Type ) . -``` - -``` -link "libX11.so.6"; -extern proc XOpenDisplay(name: ^U8): ^U8; -extern proc printf(format: ^U8; ...): I32; -extern var environ: ^^U8; -``` - -An `extern` procedure or variable is found by its name in the C -libraries the program links: the C library always, and each library -named by `link`. - -An `extern` procedure's parameters and result are integers, `BOOL`, -`F32`, `F64`, pointers or procedures; a record goes to C by pointer, -never by value. `...` accepts any number of further arguments of those -types, and is allowed only in an `extern`. C takes no `float` there, -so an `F32` given to `...` is an error: the program writes `F64(x)`. -A real constant there is an `F64`. - -An `extern` variable is C's variable itself: reading it reads C's, -assigning it writes C's. It can be of any type, declared as C declares -it, a record laid out as C lays it out (section 5.5); the compiler -can't check that it is. A C variable that is local to each thread, -such as `errno`, can't be reached this way; the C library has a -procedure for it (`__errno_location`). - -A C union has no jed type. A program reads one as an array of words, -and the member it wants through a pointer conversion: - -``` -var ev: [24]I64; (* XEvent: 192 bytes *) -... -XNextEvent(dpy, ADR(ev)); -if I32(ev[0]) = KeyPress then - key := ^XKeyEvent(ADR(ev)); - ... -end; -``` - -Every jed procedure uses the System V calling convention, so a jed -procedure whose parameters and result are of those types can be given -to C as a callback. - -## 10. Programs - -Any module may export a procedure `main`, declared `proc main*;` or -`proc main*: I64;`. The program runs the bodies of all its modules -(section 3), then the main module's `main`, if it has one, and ends -with status 0, or with the status `main` returns, by calling -`Rt.exit`. The `main` of an imported module is an ordinary procedure, -which runs only if something calls it; so a library module can carry a -`main` that tests it. -A program uses C if any of its modules has an `extern` declaration or -a `link` of a library. A program that doesn't is a static executable -with no run time besides the code it uses. One that does is linked -dynamically and starts through the C library, so that C's own set-up -and clean-up run. A program with a module that says `link static;` -must not use C, and the compiler reports an error if it does. - -**Ending.** `Rt.exit(status)` ends the program. First it runs the -procedures registered with `Rt.atExit`, the last registered first, -each at most once; then it ends the program with `status`, through -C's `exit` in a program that uses C, so that C flushes its own -buffers. A failed check (section 6.5) runs them too, after its -message, so that `Out`'s buffer is written out. `Sys.exit` ends the -program at once, and a program stopped by a signal runs none of them. - -``` -proc atExit*(p: proc): ERROR; (* Rt.Full if 32 are registered *) -proc exit*(status: I64); -``` - -Only what can be reached from `main` and the module bodies goes into -the executable: unused procedures, variables and strings are left out. -The executable names its procedures and carries line numbers, so that -gdb can stop at a line of the source and show where it is. - -**Defined behaviour.** Every variable starts at zero, integers wrap, -and indexing arrays and slices is checked, so a program's behaviour is -defined by this report, with one exception: memory reached through a -pointer. Dereferencing a stale or made-up pointer, indexing through a -pointer, a code procedure that breaks its rules, and C code can read or -write any memory, and what follows isn't defined. Dereferencing `nil`, dividing -by zero and calling a `nil` procedure stop the program with a signal. - -## 11. The library - -Modules written in jed, in the compiler's `lib` directory: - -| Module | What | -|---|---| -| `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 | -| `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 | -| `Out` | writing text and numbers to standard output, buffered; safe to call from several threads | -| `C` | the parts of the C library the others use, and `printf`, `fflush`, `stdout`, `pthread_create`; a program that imports it uses C | -| `Lock` | a lock for short sections, for C's threads and `Thread`'s alike | -| `Thread` | threads for a program without C: `spawn`, `join`, and `Mutex`; it says `link static` | -| `Mem` | `Allocator`, the interface of every allocator, and pages from the system | -| `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 | -| `Arena` | an allocator that frees everything at once; `ADR(arena.base)` is its allocator | -| `Str` | operations on `[]U8` strings | -| `Buf` | a growable byte buffer | -| `Fmt` | formatted output: `Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)])`, or into a `Buf` with `Fmt.write` | -| `List` | a generic singly linked list, `List(T)` | -| `Map` | a generic hash map, `Map(K, V; hash, eq)` | - -``` -module Mem; -type - Allocator* = record - alloc*: proc(a: ^Allocator; size, align: I64): ^U8; - free*: proc(a: ^Allocator; p: ^U8); - end; -... -end Mem. -``` - -**Out and C's stdio.** `Out` keeps a buffer of 4 KB. It writes it out -when it is full, at each line feed when standard output is a terminal, -at `Out.flush`, and when the program ends by `Rt.exit`. C's `stdio` -keeps a buffer of its own for the same standard output. A program that -writes with both flushes one before writing with the other, or the -text comes out of order: - -``` -module Both; -import Out, C; (* C: printf, fflush and C's FILE *stdout *) - -proc main*; -begin - Out.str("from jed\n"); - Out.flush; - C.printf("from C\n"); - C.fflush(C.stdout); - Out.str("from jed again\n"); -end; - -end Both. -``` - -## 12. Versions - -A version of this report is named by the month it was made in and a -count: `2026-10.0`, then `2026-10.1` for the next change that month. -`jed --version` says which version the compiler follows. - -- **2026-10.0.** The first numbered version: the language of compiler - 0.3.0. diff --git a/doc/raz.md b/doc/raz.md new file mode 100644 index 0000000..9fb4f1c --- /dev/null +++ b/doc/raz.md @@ -0,0 +1,907 @@ +# The programming language raz + +raz is a small systems language for x86-64 Linux. A raz program can lay +a record over a device's registers, read and write memory exactly as +written, take part in lock-free algorithms, make system calls and call +C libraries. It has no garbage collector and no hidden run time: what +the program does is what its text says. + +This report defines the language. It is short on purpose. Whatever it +doesn't allow, raz doesn't have. + +This is version 2026-10.0 of the report; section 12 says what each +version changed. + +## 1. A first look + +``` +module Hello; +import Out; + +proc main*; +begin + Out.str("hello, world\n"); +end; + +end Hello. +``` + +A program is a set of modules. The one named on the command line is +the main module, and it exports a procedure `main`; the program starts +there, once every module's body has run (section 3). Saved as +`Hello.raz`, it is compiled with `raz Hello.raz`, which writes the +executable `Hello`. + +## 2. Words and symbols + +A program is written in UTF-8. The compiler rejects a file that isn't +valid UTF-8: a malformed or overlong sequence, a surrogate, or a code +point beyond 10FFFFH. Everything outside strings, characters and +comments is ASCII. Spaces, tabs and line breaks separate symbols and +are otherwise ignored. + +**Identifiers** are an ASCII letter or `_` followed by letters, digits +and `_`, up to 63 characters. Case matters: `count` and `Count` are different +names. + +**Reserved words** are lowercase, except `VOLATILE`: + +``` +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 +``` + +**Numbers.** `123` is decimal. `0FFH` is hexadecimal: it starts with a +digit and ends in `H`. `1.5` and `2.0E-3` are reals; a real always has +a digit on both sides of its point. + +An integer is an untyped constant, which takes the type it is used as, +up to the largest `I64`. A hexadecimal number above that, such as +`0FFFFFFFFFFFFFFFFH`, has type `U64`: so `-1` never fits a `U64`, and +the big number goes nowhere else without a conversion. + +A real is an untyped constant too, which takes `F32` or `F64`, +whichever it is used as, rounded to the nearest value of that type; +where nothing says which, it is an `F64`. A real never becomes an +integer, nor an integer a real, without a conversion: `x := 1;` is an +error for `x: F64`, and `x := 1.0;` is right. + +**Characters.** `'a'` is the code point of one character, an integer: +`'a'` is 97 and `'é'` is 233. + +**Strings.** `"héllo\n"` is a sequence of bytes, the UTF-8 of its text: +`"é"` is the two bytes 0C3H, 0A9H. Both characters and strings take the +escapes `\n` (line feed), `\t` (tab), `\r` (carriage return), `\0` +(zero), `\\`, `\'`, `\"`, `\u{H...}` (the code point with hexadecimal +value H..., in a string its UTF-8) and, in strings only, `\xHH` (the +byte with hexadecimal value HH, which needn't make valid UTF-8). + +Error messages give the line and the column, counted in characters. + +**Comments** are `(*` ... `*)` and nest. By convention, the comment +just before an exported declaration is its documentation, and the one +before `module` is the module's. + +**Operators and delimiters:** + +``` ++ - * / = # < <= > >= := : ; , . .. ... ( ) [ ] { } ^ | +``` + +## 3. Modules + +``` +Module = "module" ident [ "(" ModParams ")" ] ";" + { Import } { Link } { Declaration } + [ "begin" Statements ] "end" ident "." . +ModParams = ident { "," ident } { ";" ident ":" "proc" Signature } . +Import = "import" ImportItem { "," ImportItem } ";" . +ImportItem = ident [ ":=" ident [ "(" Type { "," Type } ")" ] ] . +Link = "link" ( string | "static" ) ";" . +``` + +A module lives in a file of its own name: module `Out` is `Out.raz`. +The name after `end` repeats the module's name. + +**Exports.** A name declared at the top of a module with `*` after it +is exported: other modules can use it as `Module.name`. Record fields +are exported the same way. Everything else is private to the module. + +**Imports.** `import Out;` makes `Out`'s exports available as `Out.x`. +`import O := Out;` uses the name `O` instead. A module can't import +itself, directly or through others. + +**Generic modules** take types as parameters: + +``` +module List(T); +type + Node* = record next*: ^Node; val*: T; end; +... +end List. +``` + +An import gives the arguments: `import Ints := List(I64);`. Each +distinct list of arguments makes one *instance*: the module compiled +with `T` standing for `I64`. Two imports of `List(I64)`, in any modules, +share one instance. Since every instance is checked on its own, an +operation the argument type doesn't support (adding two records, say) +is reported as an error in that instance. + +What a generic module needs to do with its types, beyond moving them +about, it is given as procedures, after the types: + +``` +module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL); +``` + +``` +import Names := Map([]U8, I64, Str.hash, Str.eq); +``` + +A procedure argument names a procedure, not a variable or an +expression, and its signature, with the type arguments put in, must be +the parameter's. Inside the module, `hash(k)` calls it directly. Two +imports make the same instance only if their types and their procedures +are the same. + +**Finding modules.** The compiler looks for module `Name` in the main +module's directory, then in each directory given with `-I`, then in the +`lib` directory beside the compiler. In each directory it takes the +first of `Name.OS-ARCH.raz`, `Name.OS.raz`, `Name.ARCH.raz` and +`Name.raz` that exists, where `OS-ARCH` is the target, for now only +`linux-x86_64`. So a module whose code depends on the machine or the +system comes in one file per target, and the modules that import it +don't change. Machine code (section 8) and system calls belong in such +files. + +The compiler holds every file of such a module to the same interface. +When it takes one of `Name.*.raz`, it also reads the declarations of +the others beside it, and of `Name.raz` if there is one, and reports an +error unless they all export the same names, each the same kind of +thing: + +- a constant of the same type (its value may differ: a system call + number, say); +- a type of the same kind, and for a record or variant the same + exported fields and cases, with the same types (unexported fields, + and so the size and layout, may differ); +- a variable of the same type; +- a procedure of the same signature. + +Two types here are the same if they are built alike, a name in one file +standing for the same name in another. + +**Module bodies.** A module may end with `begin` and statements, its +body. Every module's body runs once, before the main module's `main`: +a module's body runs after the bodies of the modules it imports, in the +order of its `import`s, and once however many modules import it. Each +instance of a generic module has its body run once. Module variables +are zero before any body runs. `return;` ends a body early. + +**`link "libX11.so.6";`** names a shared library to load at run time, +for the `extern` declarations of section 9. **`link static;`** says the +module needs a program without C (section 10): it makes its own system +calls, or its own threads, which the C library wouldn't know about. + +## 4. Declarations + +``` +Declaration = "const" { IdentDef [ ":" "ERROR" ] "=" Expr ";" } + | "type" { IdentDef "=" Type ";" } + | "var" { IdentList ":" Type ";" } + | ProcDeclaration ";" + | ExternDeclaration ";" . +IdentDef = ident [ "*" ] . +IdentList = IdentDef { "," IdentDef } . +``` + +A name must be declared before it is used, with two exceptions: the +base type of a pointer may name a type declared later in the same +`type` section (so that two records can point at each other), and a +procedure may be declared `forward` and defined later (section 8). + +**Constants** are evaluated by the compiler. Their expressions use only +literals, other constants, operators, `SIZE` and the `LEN` of arrays. + +**Variables** of a module live as long as the program; variables of a +procedure live as long as its call. Both start at zero: every byte of +them is zero. So a number starts as `0` (`0.0` for `F32` and `F64`), +a `BOOL` as `false`, a pointer, procedure or `ERROR` as `nil`, a slice +as the empty slice (`ptr` is `nil`, `len` is 0), a variant as its +first case with its fields zero, a set as the empty set, and an +enumeration as its first name. No variable is ever read before it has a value. + +## 5. Types + +``` +Type = QualIdent + | "[" Expr "]" Type (* array *) + | "[" "]" Type (* slice *) + | "^" [ "VOLATILE" ] Type (* pointer *) + | [ "packed" ] "record" { IdentList ":" Type ";" } "end" + | "variant" { Case ";" } "end" + | "(" ident { "," ident } ")" (* enumeration *) + | "set" "of" QualIdent + | "proc" Signature . +Case = ident [ "(" FieldList { ";" FieldList } ")" ] . +FieldList = ident { "," ident } ":" Type . +QualIdent = [ ident "." ] ident . +``` + +### 5.1 Basic types + +| Type | Size | Values | +|---|---|---| +| `I8` `I16` `I32` `I64` | 1, 2, 4, 8 | signed integers, two's complement | +| `U8` `U16` `U32` `U64` | 1, 2, 4, 8 | unsigned integers | +| `BOOL` | 1 | `false` (0), `true` (1) | +| `F32` | 4 | IEEE 754 single precision | +| `F64` | 8 | IEEE 754 double precision | + +### 5.2 Arrays + +`[n]T` is `n` elements of type `T`, one after another. `n` is a +constant greater than zero. Arrays are values: assigning one copies it. + +### 5.3 Slices + +`[]T` is a view of elements that live elsewhere: a pointer to the first +and a count, 16 bytes in all. + +``` +Slice = record ptr: ^T; len: I64; end; (* its layout *) +``` + +A slice is made from an array (`a[2..5]`, or an array used where a +slice is wanted), from another slice, or from a pointer (`p[0..n]`). It +doesn't own what it points at. + +### 5.4 Pointers + +`^T` is the address of a `T`, 8 bytes. `nil` is the pointer to nothing. + +`^VOLATILE T` is the address of a `T` that something besides the +program may read or change: a device register, memory shared with +another process. Section 7.6 says what that promises. + +### 5.5 Records + +``` +type Cell = record ch: U8; attr: U8; end; +``` + +Fields are laid out in order as C lays them out: each at the next +multiple of its own alignment, and the whole record padded to a +multiple of its largest alignment. A record declared like a C struct +has the same layout as that struct. + +A `packed record` has no padding: each field starts at the byte after +the field before it, and the record's alignment is 1. A field of a +packed record may be misaligned. x86-64 reads and writes it anyway, but +an atomic operation on it is slow, and a volatile access to it is one +instruction that needn't be atomic. + +### 5.6 Variants + +A variant holds one of several cases, each with its own fields: + +``` +type + Shape* = variant + circle(r: F64); + rect(w, h: F64); + dot; + end; +``` + +The case names are declared in the scope around the type, so `circle` +can be used directly, and as `Shapes.circle` from another module if +`Shape` is exported. A case with fields is built by calling it like a +procedure, `circle(2.0)`; a case without fields is just `dot`. The only +way to read the fields is `match` (section 7.4). + +Layout: an `I64` tag (0 for the first case, 1 for the second, and so +on) followed by the fields of the largest case, laid out as a record. +A variant that starts at zero therefore holds its first case. + +### 5.7 Enumerations and sets + +``` +type + Color* = (red, green, blue); + Colors* = set of Color; +``` + +An enumeration is a list of names, in order. Like the cases of a +variant, the names are declared in the scope around the type. An +enumeration has at most 256 names and takes 1 byte; the first name is +0, the next 1, and so on. + +`set of E`, for an enumeration `E` of at most 64 names, holds any +choice of `E`'s names: bit `i` stands for the name at position `i`. It +takes the smallest of 1, 2, 4 and 8 bytes that has a bit for each name, +so a set can stand for a C flags word. + +### 5.8 Errors + +``` +const NotFound*: ERROR = "not found"; +``` + +`ERROR` is a basic type of 8 bytes. A value of it is made only by a +constant declared as above, and each such declaration makes an error +different from every other, whatever its message: two modules that +both declare `"not found"` have two different errors. A generic module +makes its errors once per instance. `nil` is no error. + +Errors compare with `=` and `#` only, by which declaration made them, +never by their message. `MSG(e)` is the message, a `[]U8`; `MSG(nil)` +is `""`. + +``` +proc find*(key: I64): (^Node, ERROR); +... +n, err := Table.find(7); +if err = Table.NotFound then ... end; +``` + +### 5.9 Procedure types + +``` +type Compare = proc(a, b: I64): BOOL; +``` + +A value of a procedure type is the address of a procedure with that +signature, 8 bytes, or `nil`. + +### 5.10 Same and assignable + +Two named types are the same only if they are the same declaration. +Two anonymous types are the same if they are built alike: `^I64` is +`^I64` wherever it is written. A named and an anonymous type are the +same if the named one is built like the anonymous one, so that +`p := ADR(n)` works for `p: NodePtr` with `type NodePtr = ^Node`. + +A type declared with only a name on the right, `type Count = I64;`, is +another name for that type, not a new one. + +A value of type `A` can be assigned to a variable of type `B` (and +passed to a parameter of type `B`, and returned as a `B`) if they are +the same type, or if: + +- `A` is an integer constant whose value fits in the integer type `B`; +- `A` is `nil` and `B` is a pointer, procedure or `ERROR` type; +- `A` is `^T` and `B` is `^VOLATILE T`; +- `A` is `[n]T` and `B` is `[]T`; +- `A` is a string literal and `B` is `[]U8`, `^U8` (a pointer to the + bytes followed by a zero byte, as C wants), or `[n]U8` with `n` at + least the string's length (the rest is zero); +- `A` is a procedure and `B` a procedure type with the same signature. + +Nothing else converts silently. In particular, there is no conversion +between integer types, between integers and reals, or between `F32` +and `F64`, without a written conversion (section 6.7). + +## 6. Expressions + +``` +Expr = SimpleExpr [ Relation SimpleExpr ] . +Relation = "=" | "#" | "<" | "<=" | ">" | ">=" | "in" . +SimpleExpr = [ "-" ] Term { AddOp Term } . +AddOp = "+" | "-" | "or" | "xor" . +Term = Factor { MulOp Factor } . +MulOp = "*" | "/" | "div" | "mod" | "and" | "shl" | "shr" . +Factor = number | char | string | Designator | "(" Expr ")" + | "not" Factor + | "[" [ Expr { "," Expr } ] "]" + | "{" [ Element { "," Element } ] "}" + | "^" [ "VOLATILE" ] Type "(" Expr ")" . +Element = Expr | ident ":" Expr . +Designator = QualIdent { Selector } . +Selector = "." ident | "^" | "[" Expr [ ".." Expr ] "]" + | "(" [ Expr { "," Expr } ] ")" . +``` + +The operators bind in the order of the grammar: `not` most tightly, +then the multiplying operators, then the adding ones, then the +relations. So `a + b * c = d` is `(a + (b * c)) = d`. A unary minus +applies to the first term: `-a * b` is `-(a * b)`. + +### 6.1 Integers + +Both operands of `+ - * div mod and or xor` have the same integer +type, or one is an untyped constant that takes the other's type. The +result has that type and wraps around at its width: in `U8`, +`200 + 100` is `44`. + +`div` rounds toward zero and `mod` takes the sign of the dividend, as +in C: `-7 div 2` is `-3`, `-7 mod 2` is `-1`. Dividing by zero, and +dividing the smallest `I64` by `-1`, stop the program (`SIGFPE`). + +`and`, `or`, `xor` and `not` work on every bit. `x shl n` and +`x shr n` shift by `n and 63`; `shr` brings in copies of the sign bit +for signed types and zeros for unsigned ones. + +Relations compare as signed or unsigned according to the type. + +### 6.2 Booleans + +`and` and `or` on `BOOL` evaluate their right operand only when it +decides the result. `not` negates, `xor` is "different", and `=` and +`#` compare. + +### 6.3 Reals + +`+ - * /` and the relations work on `F32` and on `F64`. Both operands +have the same type, or one is a real constant, which takes the other's +type (section 2). The result has that type: `F32` arithmetic is done in +single precision, rounded at each step as C rounds `float`. A +constant expression of reals is evaluated in double precision, then +rounded once to the type it takes. + +### 6.4 Pointers + +- `p^` is the variable `p` points at. +- `p + i` and `p - i`, with `i` an integer, move `p` by `i` elements: + by `i * SIZE(T)` bytes for `p: ^T`. +- `p - q`, with both of the same pointer type, is the number of + elements between them, an `I64`. +- `p[i]` is `(p + i)^`. `p[lo..hi]` is the slice of the `hi - lo` + elements from `p + lo`. Neither is checked. A pointer to an array + isn't indexed this way, since a step would be a whole array: its + elements are `p^[i]`. +- Pointers compare with `= # < <= > >=` as unsigned addresses. + Procedure values compare with `=` and `#` only. + +### 6.5 Arrays and slices + +`a[i]` is an element of an array or slice, and `a[lo..hi]` is the slice +of the elements from `lo` up to but not including `hi`. Both are +checked: `i` must be below the length, and `0 <= lo <= hi <= length`. +A check that fails prints the file and line to standard error and stops +the program with status 2. + +**Literals.** `[e1, e2, ...]` builds an array, and `{f: e, g: e, ...}` +a record, where the type it must have is known: assigned to a variable, +passed to a parameter, returned, compared with a value of that type, or +an element of a bigger literal. The elements must be assignable to the +element type, and an array literal for `[n]T` has exactly `n` of them. +A record literal names its fields, in any order, each at most once; the +fields it leaves out are zero. An array literal used as a slice is a +hidden variable of the procedure, and lives as long as its call. + +``` +c := {ch: 'A', attr: 7}; +Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)]); +``` + +**Strings compare.** Two operands that are each a `[]U8`, a `[n]U8` or +a string literal are `=` when they have the same length and the same +bytes, and `#` otherwise. Other arrays and slices, records and variants +can't be compared; write a loop. Ordering strings is the library's +`Str.cmp`. + +### 6.6 Enumerations and sets + +Enumerations compare with all six relations, by position, and an +enumeration can be the variable of a `for` loop and the expression of a +`match` (section 7.4). + +`{red, blue}` is a set, of the set type of its names' enumeration; +`{}` is the empty set, where the type it must have is known. On two sets +of the same type, `+` is union, `*` intersection and `-` difference; +`=` and `#` compare, and `<=` and `>=` are "is a subset of" and "is a +superset of". `x in s` is `true` if the name `x` is in the set `s`. + +### 6.7 Conversions + +A type name applied like a procedure converts: `I32(x)`, `F64(n)`, +`^Cell(addr)`. A pointer type written out uses the `^` form of the +grammar: `^VOLATILE U32(0FEE00000H)`. + +| From | To | Result | +|---|---|---| +| integer | integer | the value cut to the new width, or extended by its sign (signed) or zeros (unsigned) | +| integer | `F32`, `F64` | the nearest real | +| `F32`, `F64` | integer | rounded toward zero; a NaN, or a real out of the range of `I64`, gives the smallest `I64`, then cut | +| `F32` | `F64` | the same value | +| `F64` | `F32` | the nearest `F32`; too big a value gives an infinity | +| enumeration | integer | its position | +| integer | enumeration | the name at that position; a position out of range is a failed check (6.5) | +| set | integer | its bits | +| integer | set | the low bits, as many as the set has | +| integer | pointer, procedure | the address | +| pointer, procedure | integer | the address | +| pointer, procedure | pointer, procedure | the same address, seen as the new type | + +### 6.8 Built-in procedures + +| Call | Result | +|---|---| +| `SIZE(T)` | the size of type `T` in bytes, a constant | +| `ADR(x)` | the address of variable `x`, a `^T` | +| `LEN(a)` | the number of elements of an array (a constant) or a slice, an `I64` | +| `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 | +| `MSG(e)` | the message of the error `e`, a `[]U8` | +| `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`) | +| `INC(v)`, `INC(v, k)` | adds 1, or `k`, to the integer variable `v`; it wraps, like `+` | +| `DEC(v)`, `DEC(v, k)` | subtracts 1, or `k`, from `v` | +| `FENCE` | a full memory barrier | +| `CAS(p, old, new)` | if `p^ = old`, sets `p^ := new` and returns `true`; atomically | +| `XCHG(p, x)` | sets `p^ := x` and returns the value before, atomically | +| `XADD(p, x)` | adds `x` to `p^` and returns the value before, atomically | +| `ARGC()` | the number of command line arguments, an `I64` | +| `ARGV()` | the arguments, a `^^U8` (C strings) | + +`SYSCALL` exists only on Linux targets. Other systems have no stable +system call interface, and their modules call the C library instead +(section 9). + +`INC` and `DEC` evaluate `v` once, so `INC(a[f(i)])` calls `f` once. They +read `v` and then write it: two accesses, even through a `^VOLATILE` +pointer, and not atomic; `XADD` is the atomic one. + +For `CAS`, `XCHG` and `XADD`, `p` is a `^T` or `^VOLATILE T` where `T` +is an 8-byte integer or pointer type (an integer type for `XADD`). They +are sequentially consistent. + +## 7. Statements + +``` +Statements = { Statement ";" } . +Statement = Designator [ ":=" Expr ] + | Designator "," Designator { "," Designator } ":=" Expr + | "if" Expr "then" Statements + { "elsif" Expr "then" Statements } [ "else" Statements ] "end" + | "while" Expr "do" Statements "end" + | "repeat" Statements "until" Expr + | "for" ident ":=" Expr "to" Expr [ "by" Expr ] "do" Statements "end" + | "match" Expr "of" { "|" Arm } "end" + | "return" [ Expr { "," Expr } ] + | "break" + | "defer" Statement . +Arm = ( ident [ "(" ident { "," ident } ")" ] | "else" ) ":" Statements . +``` + +Every statement ends in `;`, including the ones that end in `end` or +`until`. + +### 7.1 Assignment and calls + +`x := e` evaluates `e` and stores it in `x`; arrays, records, slices and +variants are copied. A designator on its own is a call, and any result +it returns is dropped: `Out.ln;`, `write(fd, buf);`. + +`a, b := f(x);` assigns the results of a procedure that returns several +(section 8), in order. + +### 7.2 Conditions and loops + +`if`, `while` and `repeat` take `BOOL` expressions. `repeat` runs its +body at least once and stops when the condition is true. + +`for i := a to b by s do ... end;` sets the integer variable `i` to `a`, +`a + s`, ... while `i <= b` (or `i >= b` if the constant `s` is +negative). `s` is 1 if left out. `b` is evaluated once, before the +first round. + +`break` ends the innermost `while`, `repeat` or `for` it stands in, +and the program goes on after it. There is no `goto`. + +### 7.3 Return + +`return e;` ends the procedure with the result `e`; `return a, b;` with +several results; `return;` from a procedure without results. A +procedure with results that runs off its end returns zeros, each result +as a variable of its type starts (section 4). + +### 7.4 Match + +``` +match s of +| circle(r): area := 3.14159 * r * r; +| rect(w, h): area := w * h; +| dot: area := 0.0; +end; +``` + +`match` runs the arm of the case `s` holds. An arm may name the case's +fields, in order, all of them; the names stand for those fields of `s` +itself, so assigning to one changes `s`. An arm may also leave the +fields unnamed. Every case must have an arm, unless there is an +`| else:` arm, which must come last. + +`match` on an enumeration works the same way: each arm names one of the +enumeration's names. + +### 7.5 Order of evaluation + +Operands, arguments and the designators of an assignment are evaluated +from left to right. + +### 7.6 Volatile + +A variable reached through a `^VOLATILE T` is volatile, and so is any +field or element of it. Each read or write of a volatile variable of a +basic, enumeration, set or pointer type is exactly one memory access, +of exactly its size, and volatile accesses happen in the order the +program writes them. Copying a whole record or array through a +volatile pointer is not allowed, since it can't be one access. + +A `^VOLATILE T` doesn't convert to `^T` without a written conversion. + +`FENCE` also orders the program's ordinary accesses against those of +other processors and devices. + +### 7.7 Defer + +`defer s;` runs the statement `s` when the program leaves the statement +list the `defer` stands in: at its end, or by a `return`, or by a +`break` out of it. Statements deferred in the same list run in the +opposite order to their `defer`s, and only those whose `defer` has been +reached run. + +``` +module Head; +import Sys, Out; + +(* Prints the first line of the file at path. *) +proc head(path: []U8): BOOL; +var fd, n, i: I64; buf: [256]U8; +begin + fd := Sys.openRead(path); + if fd < 0 then return false; end; + defer Sys.close(fd); + n := Sys.read(fd, buf); + if n < 0 then return false; end; + for i := 0 to n - 1 do + if buf[i] = 10 then n := i; break; end; + end; + Out.str(buf[0..n]); + Out.ln; + return true; +end; + +proc main*; +begin + if not head("/etc/hostname") then Out.str("no hostname\n"); end; +end; + +end Head. +``` + +`return e;` evaluates `e` before the deferred statements run. A +deferred statement can't contain `return`, `break` or `defer` that +would leave it. + +## 8. Procedures + +``` +ProcDeclaration = "proc" IdentDef Signature ";" + ( "forward" | { LocalDeclaration } "begin" Statements "end" [ ident ] + | "code" Expr { "," Expr } ) . +LocalDeclaration = "const" { ident [ ":" "ERROR" ] "=" Expr ";" } + | "type" { ident "=" Type ";" } + | "var" { ident { "," ident } ":" Type ";" } . +Signature = "(" [ Params { ";" Params } [ ";" "..." ] ] ")" [ ":" Results ] + | [ ":" Results ] . +Params = [ "var" ] ident { "," ident } ":" Type . +Results = Type | "(" Type { "," Type } ")" . +``` + +A procedure without parameters may leave out the parentheses, both +where it is declared (`proc main*;`) and where it is called (`Out.ln`). +Used without parentheses in an expression, a procedure is a procedure +value, not a call. + +**Parameters.** A value parameter is a copy: the procedure may change +it, and the caller's variable stays as it was. A `var` parameter is the +caller's variable itself; its argument must be a variable of exactly +the parameter's type. + +**Results.** A procedure returns nothing, one value, or several. A call +that returns several values can only stand on the right of a multiple +assignment, or alone as a statement. + +``` +module Divide; +import Out; + +proc divmod(a, b: I64): (I64, I64); +begin + return a div b, a mod b; +end; + +proc main*; +var q, r: I64; +begin + q, r := divmod(17, 5); + Out.int(q); Out.str(" rest "); Out.int(r); Out.ln; +end; + +end Divide. +``` + +**forward.** `proc f(x: I64): I64; forward;` declares `f` so that it +can be called before its body appears; the body comes later with the +same signature. + +Procedures don't nest. + +**Code procedures.** A procedure whose body is `code` and a list of +constant bytes is machine code, written by hand: + +``` +proc rdtsc*: U64; +code 0FH, 31H, (* rdtsc *) + 48H, 0C1H, 0E2H, 20H, (* shl rdx, 32 *) + 48H, 09H, 0D0H, (* or rax, rdx *) + 0C3H; (* ret *) +``` + +It is called like any procedure, with the System V convention: integer +and pointer arguments arrive in `rdi`, `rsi`, `rdx`, `rcx`, `r8` and +`r9`, `F32` and `F64` ones in `xmm0` to `xmm7`, and the result goes in +`rax` (and `rdx` for a second) or `xmm0`. Its parameters and results +are therefore of the types C can take (section 9), at most six integer +and eight real parameters, and at most two results. The bytes are the whole +procedure, `ret` included; they must keep `rbx`, `rbp`, `rsp` and `r12` +to `r15` as they found them. The compiler doesn't look inside them. + +## 9. Calling C + +``` +ExternDeclaration = "extern" ( "proc" IdentDef Signature + | "var" IdentDef ":" Type ) . +``` + +``` +link "libX11.so.6"; +extern proc XOpenDisplay(name: ^U8): ^U8; +extern proc printf(format: ^U8; ...): I32; +extern var environ: ^^U8; +``` + +An `extern` procedure or variable is found by its name in the C +libraries the program links: the C library always, and each library +named by `link`. + +An `extern` procedure's parameters and result are integers, `BOOL`, +`F32`, `F64`, pointers or procedures; a record goes to C by pointer, +never by value. `...` accepts any number of further arguments of those +types, and is allowed only in an `extern`. C takes no `float` there, +so an `F32` given to `...` is an error: the program writes `F64(x)`. +A real constant there is an `F64`. + +An `extern` variable is C's variable itself: reading it reads C's, +assigning it writes C's. It can be of any type, declared as C declares +it, a record laid out as C lays it out (section 5.5); the compiler +can't check that it is. A C variable that is local to each thread, +such as `errno`, can't be reached this way; the C library has a +procedure for it (`__errno_location`). + +A C union has no raz type. A program reads one as an array of words, +and the member it wants through a pointer conversion: + +``` +var ev: [24]I64; (* XEvent: 192 bytes *) +... +XNextEvent(dpy, ADR(ev)); +if I32(ev[0]) = KeyPress then + key := ^XKeyEvent(ADR(ev)); + ... +end; +``` + +Every raz procedure uses the System V calling convention, so a raz +procedure whose parameters and result are of those types can be given +to C as a callback. + +## 10. Programs + +Any module may export a procedure `main`, declared `proc main*;` or +`proc main*: I64;`. The program runs the bodies of all its modules +(section 3), then the main module's `main`, if it has one, and ends +with status 0, or with the status `main` returns, by calling +`Rt.exit`. The `main` of an imported module is an ordinary procedure, +which runs only if something calls it; so a library module can carry a +`main` that tests it. +A program uses C if any of its modules has an `extern` declaration or +a `link` of a library. A program that doesn't is a static executable +with no run time besides the code it uses. One that does is linked +dynamically and starts through the C library, so that C's own set-up +and clean-up run. A program with a module that says `link static;` +must not use C, and the compiler reports an error if it does. + +**Ending.** `Rt.exit(status)` ends the program. First it runs the +procedures registered with `Rt.atExit`, the last registered first, +each at most once; then it ends the program with `status`, through +C's `exit` in a program that uses C, so that C flushes its own +buffers. A failed check (section 6.5) runs them too, after its +message, so that `Out`'s buffer is written out. `Sys.exit` ends the +program at once, and a program stopped by a signal runs none of them. + +``` +proc atExit*(p: proc): ERROR; (* Rt.Full if 32 are registered *) +proc exit*(status: I64); +``` + +Only what can be reached from `main` and the module bodies goes into +the executable: unused procedures, variables and strings are left out. +The executable names its procedures and carries line numbers, so that +gdb can stop at a line of the source and show where it is. + +**Defined behaviour.** Every variable starts at zero, integers wrap, +and indexing arrays and slices is checked, so a program's behaviour is +defined by this report, with one exception: memory reached through a +pointer. Dereferencing a stale or made-up pointer, indexing through a +pointer, a code procedure that breaks its rules, and C code can read or +write any memory, and what follows isn't defined. Dereferencing `nil`, dividing +by zero and calling a `nil` procedure stop the program with a signal. + +## 11. The library + +Modules written in raz, in the compiler's `lib` directory: + +| Module | What | +|---|---| +| `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 | +| `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 | +| `Out` | writing text and numbers to standard output, buffered; safe to call from several threads | +| `C` | the parts of the C library the others use, and `printf`, `fflush`, `stdout`, `pthread_create`; a program that imports it uses C | +| `Lock` | a lock for short sections, for C's threads and `Thread`'s alike | +| `Thread` | threads for a program without C: `spawn`, `join`, and `Mutex`; it says `link static` | +| `Mem` | `Allocator`, the interface of every allocator, and pages from the system | +| `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 | +| `Arena` | an allocator that frees everything at once; `ADR(arena.base)` is its allocator | +| `Str` | operations on `[]U8` strings | +| `Buf` | a growable byte buffer | +| `Fmt` | formatted output: `Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)])`, or into a `Buf` with `Fmt.write` | +| `List` | a generic singly linked list, `List(T)` | +| `Map` | a generic hash map, `Map(K, V; hash, eq)` | + +``` +module Mem; +type + Allocator* = record + alloc*: proc(a: ^Allocator; size, align: I64): ^U8; + free*: proc(a: ^Allocator; p: ^U8); + end; +... +end Mem. +``` + +**Out and C's stdio.** `Out` keeps a buffer of 4 KB. It writes it out +when it is full, at each line feed when standard output is a terminal, +at `Out.flush`, and when the program ends by `Rt.exit`. C's `stdio` +keeps a buffer of its own for the same standard output. A program that +writes with both flushes one before writing with the other, or the +text comes out of order: + +``` +module Both; +import Out, C; (* C: printf, fflush and C's FILE *stdout *) + +proc main*; +begin + Out.str("from raz\n"); + Out.flush; + C.printf("from C\n"); + C.fflush(C.stdout); + Out.str("from raz again\n"); +end; + +end Both. +``` + +## 12. Versions + +A version of this report is named by the month it was made in and a +count: `2026-10.0`, then `2026-10.1` for the next change that month. +`raz --version` says which version the compiler follows. + +- **2026-10.0.** The first numbered version: the language of compiler + 0.3.0. diff --git a/editor/emacs/jed-mode.el b/editor/emacs/jed-mode.el deleted file mode 100644 index 6d636a3..0000000 --- a/editor/emacs/jed-mode.el +++ /dev/null @@ -1,230 +0,0 @@ -;;; jed-mode.el --- a major mode for jed -*- lexical-binding: t -*- - -;; Colours jed's reserved words, basic types, built-in procedures, -;; numbers, characters, strings and nested comments, and indents by -;; `jed-indent-offset': a block's statements one level in from the -;; word that opens it; end, until, else and elsif at that word's -;; level; match arms at the level of match; procedures, sections -;; (const, type, var) and module bodies at the left margin. The text -;; of a comment, and a line that goes on with the expression of the -;; line before, keep the indent they have. -;; -;; (add-to-list 'load-path "/path/to/jed/editor/emacs") -;; (require 'jed-mode) - -;;; Code: - -(defgroup jed nil "The jed programming language." :group 'languages) - -(defcustom jed-indent-offset 4 - "Columns that a block's statements are indented by." - :type 'integer :group 'jed) - -(defconst jed-keywords - '("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")) - -(defconst jed-types - '("I8" "I16" "I32" "I64" "U8" "U16" "U32" "U64" "BOOL" "F32" "F64" "ERROR")) - -(defconst jed-builtins - '("SIZE" "ADR" "LEN" "NEW" "MSG" "SYSCALL" "FENCE" "CAS" "XCHG" "XADD" - "ARGC" "ARGV" "INC" "DEC")) - -(defvar jed-mode-syntax-table - (let ((st (make-syntax-table))) - ;; (* ... *), nested - (modify-syntax-entry ?\( "()1n" st) - (modify-syntax-entry ?\) ")(4n" st) - (modify-syntax-entry ?* ". 23n" st) - (modify-syntax-entry ?\" "\"" st) - (modify-syntax-entry ?\' "\"" st) - (modify-syntax-entry ?\\ "\\" st) - (modify-syntax-entry ?_ "_" st) - (dolist (c '(?+ ?- ?/ ?= ?# ?< ?> ?: ?\; ?, ?. ?^ ?|)) - (modify-syntax-entry c "." st)) - st) - "Syntax table for `jed-mode'.") - -(defvar jed-font-lock-keywords - `((,(regexp-opt jed-keywords 'symbols) . font-lock-keyword-face) - (,(regexp-opt jed-types 'symbols) . font-lock-type-face) - (,(regexp-opt jed-builtins 'symbols) . font-lock-builtin-face) - (,(regexp-opt '("true" "false" "nil") 'symbols) . font-lock-constant-face) - ;; 123, 0FFH, 1.5, 2.0E-3 - ("\\_<[0-9][0-9A-F]*H\\_>\\|\\_<[0-9]+\\(?:\\.[0-9]+\\(?:E[-+]?[0-9]+\\)?\\)?\\_>" - . font-lock-constant-face)) - "What `jed-mode' colours, besides strings and comments.") - -;;; Indenting - -(defconst jed--decl - "^[ \t]*\\(?:module\\|import\\|link\\|extern\\|proc\\|const\\|type\\|var\\|begin\\)\\_>") -(defconst jed--leading "^[ \t]*\\(?:or\\|and\\)\\_>") -(defconst jed--block-word - "\\_<\\(if\\|while\\|for\\|match\\|record\\|variant\\|begin\\|repeat\\|end\\|until\\)\\_>") - -(defun jed--line (n) - "The text of line N." - (save-excursion - (goto-char (point-min)) - (forward-line (1- n)) - (buffer-substring-no-properties (line-beginning-position) (line-end-position)))) - -(defun jed--indent-of (n) - (save-excursion (goto-char (point-min)) (forward-line (1- n)) (current-indentation))) - -(defun jed--in-comment (n) - "Whether line N starts inside a comment that began before it." - (save-excursion - (goto-char (point-min)) - (forward-line (1- n)) - (back-to-indentation) - (and (nth 4 (syntax-ppss)) - (not (looking-at "(\\*"))))) - -(defun jed--prev (n) - "The last line before N that isn't blank, or 0." - (let ((l (1- n))) - (while (and (> l 0) (string-match-p "\\`[ \t]*\\'" (jed--line l))) - (setq l (1- l))) - l)) - -(defun jed--code (n) - "Line N's code, without strings, characters and comments." - (let ((line (jed--line n))) - (when (jed--in-comment n) - (setq line (if (string-match "\\*)" line) (substring line (match-end 0)) ""))) - ;; one pattern, so that whichever comes first is taken - (setq line (replace-regexp-in-string - "\"\\(?:[^\"\\\\]\\|\\\\.\\)*\"\\|'\\(?:[^'\\\\]\\|\\\\.\\)*'\\|(\\*.*?\\*)" - (lambda (m) (if (string-prefix-p "(" m) "" "0")) line t t)) - (setq line (replace-regexp-in-string "(\\*.*\\'" "" line t t)) - (string-trim line))) - -(defun jed--count (re s) - (let ((n 0) (i 0)) - (while (string-match re s i) - (setq n (1+ n) i (match-end 0))) - n)) - -(defun jed--continues (n) - "Whether the expression on line N goes on to the next line." - (let ((code (jed--code n))) - (or (> (jed--count "[([{]" code) (jed--count "[])}]" code)) - (string-match-p "\\(?:,\\|:=\\|[-+*/=#<>]\\|\\_ l 1) (not (string-match-p "(\\*" (jed--line l)))) - (setq l (1- l))) - l)) - -(defun jed-calculate-indent () - "The column line at point should start at, or nil to leave it." - (let* ((case-fold-search nil) - (n (line-number-at-pos)) - (cur (jed--line n)) - (prev (jed--prev n))) - (catch 'done - (when (jed--in-comment n) (throw 'done nil)) - (when (and (string-match-p jed--decl cur) (not (string-match-p "^[ \t]*proc[ \t]*(" cur))) - (throw 'done 0)) - ;; a comment before a declaration goes with it, at the margin - (when (string-match-p "^[ \t]*(\\*" cur) - (let ((l n) (last (line-number-at-pos (point-max)))) - (while (and (< l last) (not (string-match-p "\\*)" (jed--line l)))) - (setq l (1+ l))) - (setq l (1+ l)) - (while (and (<= l last) (string-match-p "\\`[ \t]*\\'" (jed--line l))) - (setq l (1+ l))) - (when (and (<= l last) (string-match-p jed--decl (jed--line l))) - (throw 'done 0)))) - (when (string-match-p "^[ \t]*\\(?:end\\|until\\)\\_>" cur) - (throw 'done (or (jed--opener n) 0))) - (when (= prev 0) (throw 'done 0)) - (when (string-match-p "^[ \t]*\\(?:\\(?:else\\|elsif\\)\\_>\\||\\)" cur) - (throw 'done (or (jed--opener n) (jed--indent-of prev)))) - (when (or (jed--continues prev) (string-match-p jed--leading cur)) - (throw 'done nil)) - (when (string= (jed--code prev) "") - (throw 'done (jed--indent-of (jed--comment-start prev)))) - (let* ((start (jed--start prev)) - (ind (jed--indent-of start)) - (code (mapconcat #'jed--code (number-sequence start prev) " "))) - (cond - ((or (string-match-p "\\`\\(?:const\\|type\\|var\\)\\'" code) - (and (string-match-p "\\`else\\_>" code) (>= (jed--opens code) 0)) - (string-match-p "\\`|.*:\\'" code) - (string-match-p "\\`elsif\\_>.*\\_.*\\_ (jed--opens code) 0) (+ ind jed-indent-offset)) - (t ind)))))) - -(defun jed-indent-line () - "Indent the current line as jed's blocks say." - (interactive) - (let ((col (save-excursion (jed-calculate-indent))) - (offset (- (current-column) (current-indentation)))) - (when col - (indent-line-to col) - (when (> offset 0) (move-to-column (+ col offset)))))) - -;;;###autoload -(define-derived-mode jed-mode prog-mode "jed" - "Major mode for editing jed." - :syntax-table jed-mode-syntax-table - (setq-local font-lock-defaults '(jed-font-lock-keywords nil nil)) - (setq-local comment-start "(* ") - (setq-local comment-end " *)") - (setq-local comment-start-skip "(\\*+[ \t]*") - (setq-local indent-tabs-mode nil) - (setq-local indent-line-function #'jed-indent-line)) - -;;;###autoload -(add-to-list 'auto-mode-alist '("\\.jed\\'" . jed-mode)) - -(provide 'jed-mode) - -;;; jed-mode.el ends here diff --git a/editor/emacs/raz-mode.el b/editor/emacs/raz-mode.el new file mode 100644 index 0000000..fdda521 --- /dev/null +++ b/editor/emacs/raz-mode.el @@ -0,0 +1,230 @@ +;;; raz-mode.el --- a major mode for raz -*- lexical-binding: t -*- + +;; Colours raz's reserved words, basic types, built-in procedures, +;; numbers, characters, strings and nested comments, and indents by +;; `raz-indent-offset': a block's statements one level in from the +;; word that opens it; end, until, else and elsif at that word's +;; level; match arms at the level of match; procedures, sections +;; (const, type, var) and module bodies at the left margin. The text +;; of a comment, and a line that goes on with the expression of the +;; line before, keep the indent they have. +;; +;; (add-to-list 'load-path "/path/to/raz/editor/emacs") +;; (require 'raz-mode) + +;;; Code: + +(defgroup raz nil "The raz programming language." :group 'languages) + +(defcustom raz-indent-offset 4 + "Columns that a block's statements are indented by." + :type 'integer :group 'raz) + +(defconst raz-keywords + '("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")) + +(defconst raz-types + '("I8" "I16" "I32" "I64" "U8" "U16" "U32" "U64" "BOOL" "F32" "F64" "ERROR")) + +(defconst raz-builtins + '("SIZE" "ADR" "LEN" "NEW" "MSG" "SYSCALL" "FENCE" "CAS" "XCHG" "XADD" + "ARGC" "ARGV" "INC" "DEC")) + +(defvar raz-mode-syntax-table + (let ((st (make-syntax-table))) + ;; (* ... *), nested + (modify-syntax-entry ?\( "()1n" st) + (modify-syntax-entry ?\) ")(4n" st) + (modify-syntax-entry ?* ". 23n" st) + (modify-syntax-entry ?\" "\"" st) + (modify-syntax-entry ?\' "\"" st) + (modify-syntax-entry ?\\ "\\" st) + (modify-syntax-entry ?_ "_" st) + (dolist (c '(?+ ?- ?/ ?= ?# ?< ?> ?: ?\; ?, ?. ?^ ?|)) + (modify-syntax-entry c "." st)) + st) + "Syntax table for `raz-mode'.") + +(defvar raz-font-lock-keywords + `((,(regexp-opt raz-keywords 'symbols) . font-lock-keyword-face) + (,(regexp-opt raz-types 'symbols) . font-lock-type-face) + (,(regexp-opt raz-builtins 'symbols) . font-lock-builtin-face) + (,(regexp-opt '("true" "false" "nil") 'symbols) . font-lock-constant-face) + ;; 123, 0FFH, 1.5, 2.0E-3 + ("\\_<[0-9][0-9A-F]*H\\_>\\|\\_<[0-9]+\\(?:\\.[0-9]+\\(?:E[-+]?[0-9]+\\)?\\)?\\_>" + . font-lock-constant-face)) + "What `raz-mode' colours, besides strings and comments.") + +;;; Indenting + +(defconst raz--decl + "^[ \t]*\\(?:module\\|import\\|link\\|extern\\|proc\\|const\\|type\\|var\\|begin\\)\\_>") +(defconst raz--leading "^[ \t]*\\(?:or\\|and\\)\\_>") +(defconst raz--block-word + "\\_<\\(if\\|while\\|for\\|match\\|record\\|variant\\|begin\\|repeat\\|end\\|until\\)\\_>") + +(defun raz--line (n) + "The text of line N." + (save-excursion + (goto-char (point-min)) + (forward-line (1- n)) + (buffer-substring-no-properties (line-beginning-position) (line-end-position)))) + +(defun raz--indent-of (n) + (save-excursion (goto-char (point-min)) (forward-line (1- n)) (current-indentation))) + +(defun raz--in-comment (n) + "Whether line N starts inside a comment that began before it." + (save-excursion + (goto-char (point-min)) + (forward-line (1- n)) + (back-to-indentation) + (and (nth 4 (syntax-ppss)) + (not (looking-at "(\\*"))))) + +(defun raz--prev (n) + "The last line before N that isn't blank, or 0." + (let ((l (1- n))) + (while (and (> l 0) (string-match-p "\\`[ \t]*\\'" (raz--line l))) + (setq l (1- l))) + l)) + +(defun raz--code (n) + "Line N's code, without strings, characters and comments." + (let ((line (raz--line n))) + (when (raz--in-comment n) + (setq line (if (string-match "\\*)" line) (substring line (match-end 0)) ""))) + ;; one pattern, so that whichever comes first is taken + (setq line (replace-regexp-in-string + "\"\\(?:[^\"\\\\]\\|\\\\.\\)*\"\\|'\\(?:[^'\\\\]\\|\\\\.\\)*'\\|(\\*.*?\\*)" + (lambda (m) (if (string-prefix-p "(" m) "" "0")) line t t)) + (setq line (replace-regexp-in-string "(\\*.*\\'" "" line t t)) + (string-trim line))) + +(defun raz--count (re s) + (let ((n 0) (i 0)) + (while (string-match re s i) + (setq n (1+ n) i (match-end 0))) + n)) + +(defun raz--continues (n) + "Whether the expression on line N goes on to the next line." + (let ((code (raz--code n))) + (or (> (raz--count "[([{]" code) (raz--count "[])}]" code)) + (string-match-p "\\(?:,\\|:=\\|[-+*/=#<>]\\|\\_ l 1) (not (string-match-p "(\\*" (raz--line l)))) + (setq l (1- l))) + l)) + +(defun raz-calculate-indent () + "The column line at point should start at, or nil to leave it." + (let* ((case-fold-search nil) + (n (line-number-at-pos)) + (cur (raz--line n)) + (prev (raz--prev n))) + (catch 'done + (when (raz--in-comment n) (throw 'done nil)) + (when (and (string-match-p raz--decl cur) (not (string-match-p "^[ \t]*proc[ \t]*(" cur))) + (throw 'done 0)) + ;; a comment before a declaration goes with it, at the margin + (when (string-match-p "^[ \t]*(\\*" cur) + (let ((l n) (last (line-number-at-pos (point-max)))) + (while (and (< l last) (not (string-match-p "\\*)" (raz--line l)))) + (setq l (1+ l))) + (setq l (1+ l)) + (while (and (<= l last) (string-match-p "\\`[ \t]*\\'" (raz--line l))) + (setq l (1+ l))) + (when (and (<= l last) (string-match-p raz--decl (raz--line l))) + (throw 'done 0)))) + (when (string-match-p "^[ \t]*\\(?:end\\|until\\)\\_>" cur) + (throw 'done (or (raz--opener n) 0))) + (when (= prev 0) (throw 'done 0)) + (when (string-match-p "^[ \t]*\\(?:\\(?:else\\|elsif\\)\\_>\\||\\)" cur) + (throw 'done (or (raz--opener n) (raz--indent-of prev)))) + (when (or (raz--continues prev) (string-match-p raz--leading cur)) + (throw 'done nil)) + (when (string= (raz--code prev) "") + (throw 'done (raz--indent-of (raz--comment-start prev)))) + (let* ((start (raz--start prev)) + (ind (raz--indent-of start)) + (code (mapconcat #'raz--code (number-sequence start prev) " "))) + (cond + ((or (string-match-p "\\`\\(?:const\\|type\\|var\\)\\'" code) + (and (string-match-p "\\`else\\_>" code) (>= (raz--opens code) 0)) + (string-match-p "\\`|.*:\\'" code) + (string-match-p "\\`elsif\\_>.*\\_.*\\_ (raz--opens code) 0) (+ ind raz-indent-offset)) + (t ind)))))) + +(defun raz-indent-line () + "Indent the current line as raz's blocks say." + (interactive) + (let ((col (save-excursion (raz-calculate-indent))) + (offset (- (current-column) (current-indentation)))) + (when col + (indent-line-to col) + (when (> offset 0) (move-to-column (+ col offset)))))) + +;;;###autoload +(define-derived-mode raz-mode prog-mode "raz" + "Major mode for editing raz." + :syntax-table raz-mode-syntax-table + (setq-local font-lock-defaults '(raz-font-lock-keywords nil nil)) + (setq-local comment-start "(* ") + (setq-local comment-end " *)") + (setq-local comment-start-skip "(\\*+[ \t]*") + (setq-local indent-tabs-mode nil) + (setq-local indent-line-function #'raz-indent-line)) + +;;;###autoload +(add-to-list 'auto-mode-alist '("\\.raz\\'" . raz-mode)) + +(provide 'raz-mode) + +;;; raz-mode.el ends here diff --git a/editor/vim/ftdetect/jed.vim b/editor/vim/ftdetect/jed.vim deleted file mode 100644 index b81b8e9..0000000 --- a/editor/vim/ftdetect/jed.vim +++ /dev/null @@ -1,3 +0,0 @@ -" jed: *.jed files, indented by 4 spaces. -autocmd BufRead,BufNewFile *.jed setfiletype jed -autocmd FileType jed setlocal shiftwidth=4 softtabstop=4 expandtab diff --git a/editor/vim/ftdetect/raz.vim b/editor/vim/ftdetect/raz.vim new file mode 100644 index 0000000..9b04450 --- /dev/null +++ b/editor/vim/ftdetect/raz.vim @@ -0,0 +1,3 @@ +" raz: *.raz files, indented by 4 spaces. +autocmd BufRead,BufNewFile *.raz setfiletype raz +autocmd FileType raz setlocal shiftwidth=4 softtabstop=4 expandtab diff --git a/editor/vim/indent/jed.vim b/editor/vim/indent/jed.vim deleted file mode 100644 index cba8770..0000000 --- a/editor/vim/indent/jed.vim +++ /dev/null @@ -1,157 +0,0 @@ -" Vim indent file for jed, by shiftwidth(): a block's statements one -" level in from the word that opens it; end, until, else and elsif at -" that word's level; match arms at the level of match; procedures, -" sections (const, type, var) and module bodies at the left margin. -" The text of a comment, and a line that goes on with the expression -" of the line before, keep the indent they have. - -if exists("b:did_indent") - finish -endif -let b:did_indent = 1 - -setlocal indentexpr=GetJedIndent(v:lnum) -setlocal indentkeys=o,O,0=end,0=else,0=elsif,0=until,0=\|,!^F -setlocal nolisp nosmartindent - -if exists("*GetJedIndent") - finish -endif - -" searchpair() needs groups that don't capture -let s:opener = '\C\<\%(if\|while\|for\|match\|record\|variant\|begin\|repeat\)\>' -let s:closer = '\C\<\%(end\|until\)\>' -let s:skip = 'synIDattr(synID(line("."), col("."), 1), "name") =~? "string\\|char\\|comment"' -let s:decl = '^\s*\%(module\|import\|link\|extern\|proc\|const\|type\|var\|begin\)\>' - -" The line's code, without strings, characters and comments. -function! s:Code(lnum) - let line = getline(a:lnum) - " a line that starts inside a comment: its code is after the comment - if s:InComment(a:lnum) - let line = line =~ '\*)' ? substitute(line, '^.\{-}\*)', '', '') : '' - endif - " one pattern, so that whichever comes first is taken: a " in a - " character, a ' in a string; strings become 0, comments go - let line = substitute(line, - \ '"\%([^"\\]\|\\.\)*"\|''\%([^''\\]\|\\.\)*''\|(\*.\{-}\*)', - \ '\=submatch(0)[0] == "(" ? "" : "0"', 'g') - let line = substitute(line, '(\*.*$', '', '') - return substitute(line, '^\s*\(.\{-}\)\s*$', '\1', '') -endfunction - -" Whether the expression on lnum goes on to the next line. -function! s:Continues(lnum) - let code = s:Code(a:lnum) - if len(substitute(code, '[^([{]', '', 'g')) > len(substitute(code, '[^)\]}]', '', 'g')) - return 1 - endif - return code =~# '\%(,\|:=\|[-+*/=#<>]\|\ 1 && getline(l) !~ '(\*' - let l -= 1 - endwhile - return l -endfunction - -" How many blocks the code opens, less those it closes. -function! s:Opens(code) - let n = 0 - let i = 0 - while 1 - let m = matchstrpos(a:code, '\C\<\%(if\|while\|for\|record\|variant\|begin\|repeat\|end\|until\)\>', i) - if m[1] < 0 - return n - endif - let n += (m[0] ==# 'end' || m[0] ==# 'until') ? -1 : 1 - let i = m[2] - endwhile -endfunction - -function! s:InComment(lnum) - let col = match(getline(a:lnum), '\S') + 1 - return col > 0 && synIDattr(synID(a:lnum, col, 1), "name") =~? 'comment' - \ && getline(a:lnum) !~ '^\s*(\*' -endfunction - -function! GetJedIndent(lnum) - let cur = getline(a:lnum) - if s:InComment(a:lnum) - return -1 - endif - if cur =~# s:decl && cur !~# '^\s*proc\s*(' - return 0 - endif - " a comment before a declaration goes with it, at the margin - if cur =~ '^\s*(\*' - let l = a:lnum - while l < line('$') && getline(l) !~ '\*)' - let l += 1 - endwhile - if getline(nextnonblank(l + 1)) =~# s:decl - return 0 - endif - endif - if cur =~# '^\s*\%(end\|until\)\>' - call cursor(a:lnum, 1) - let l = searchpair(s:opener, '', s:closer, 'bW', s:skip) - return l > 0 ? indent(l) : 0 - endif - let prev = prevnonblank(a:lnum - 1) - if prev == 0 - return 0 - endif - if cur =~# '^\s*\%(else\|elsif\)\>' - call cursor(a:lnum, 1) - let l = searchpair(s:opener, '', s:closer, 'bW', s:skip) - return l > 0 ? indent(l) : indent(prev) - endif - if cur =~# '^\s*|' - call cursor(a:lnum, 1) - let l = searchpair(s:opener, '', s:closer, 'bW', s:skip) - return l > 0 ? indent(l) : indent(prev) - endif - if s:Continues(prev) || cur =~# s:leading - return -1 - endif - if s:Code(prev) == '' - return indent(s:Reference(prev)) - endif - - let start = s:Start(prev) - let ind = indent(start) - let code = join(map(range(start, prev), 's:Code(v:val)'), ' ') - if code =~# '^\%(const\|type\|var\)$' || code =~# '^else\>' && s:Opens(code) >= 0 - \ || code =~# '^|.*:$' || code =~# '^elsif\>.*\.*\ 0 - return ind + shiftwidth() - endif - return ind -endfunction diff --git a/editor/vim/indent/raz.vim b/editor/vim/indent/raz.vim new file mode 100644 index 0000000..eb141d0 --- /dev/null +++ b/editor/vim/indent/raz.vim @@ -0,0 +1,157 @@ +" Vim indent file for raz, by shiftwidth(): a block's statements one +" level in from the word that opens it; end, until, else and elsif at +" that word's level; match arms at the level of match; procedures, +" sections (const, type, var) and module bodies at the left margin. +" The text of a comment, and a line that goes on with the expression +" of the line before, keep the indent they have. + +if exists("b:did_indent") + finish +endif +let b:did_indent = 1 + +setlocal indentexpr=GetRazIndent(v:lnum) +setlocal indentkeys=o,O,0=end,0=else,0=elsif,0=until,0=\|,!^F +setlocal nolisp nosmartindent + +if exists("*GetRazIndent") + finish +endif + +" searchpair() needs groups that don't capture +let s:opener = '\C\<\%(if\|while\|for\|match\|record\|variant\|begin\|repeat\)\>' +let s:closer = '\C\<\%(end\|until\)\>' +let s:skip = 'synIDattr(synID(line("."), col("."), 1), "name") =~? "string\\|char\\|comment"' +let s:decl = '^\s*\%(module\|import\|link\|extern\|proc\|const\|type\|var\|begin\)\>' + +" The line's code, without strings, characters and comments. +function! s:Code(lnum) + let line = getline(a:lnum) + " a line that starts inside a comment: its code is after the comment + if s:InComment(a:lnum) + let line = line =~ '\*)' ? substitute(line, '^.\{-}\*)', '', '') : '' + endif + " one pattern, so that whichever comes first is taken: a " in a + " character, a ' in a string; strings become 0, comments go + let line = substitute(line, + \ '"\%([^"\\]\|\\.\)*"\|''\%([^''\\]\|\\.\)*''\|(\*.\{-}\*)', + \ '\=submatch(0)[0] == "(" ? "" : "0"', 'g') + let line = substitute(line, '(\*.*$', '', '') + return substitute(line, '^\s*\(.\{-}\)\s*$', '\1', '') +endfunction + +" Whether the expression on lnum goes on to the next line. +function! s:Continues(lnum) + let code = s:Code(a:lnum) + if len(substitute(code, '[^([{]', '', 'g')) > len(substitute(code, '[^)\]}]', '', 'g')) + return 1 + endif + return code =~# '\%(,\|:=\|[-+*/=#<>]\|\ 1 && getline(l) !~ '(\*' + let l -= 1 + endwhile + return l +endfunction + +" How many blocks the code opens, less those it closes. +function! s:Opens(code) + let n = 0 + let i = 0 + while 1 + let m = matchstrpos(a:code, '\C\<\%(if\|while\|for\|record\|variant\|begin\|repeat\|end\|until\)\>', i) + if m[1] < 0 + return n + endif + let n += (m[0] ==# 'end' || m[0] ==# 'until') ? -1 : 1 + let i = m[2] + endwhile +endfunction + +function! s:InComment(lnum) + let col = match(getline(a:lnum), '\S') + 1 + return col > 0 && synIDattr(synID(a:lnum, col, 1), "name") =~? 'comment' + \ && getline(a:lnum) !~ '^\s*(\*' +endfunction + +function! GetRazIndent(lnum) + let cur = getline(a:lnum) + if s:InComment(a:lnum) + return -1 + endif + if cur =~# s:decl && cur !~# '^\s*proc\s*(' + return 0 + endif + " a comment before a declaration goes with it, at the margin + if cur =~ '^\s*(\*' + let l = a:lnum + while l < line('$') && getline(l) !~ '\*)' + let l += 1 + endwhile + if getline(nextnonblank(l + 1)) =~# s:decl + return 0 + endif + endif + if cur =~# '^\s*\%(end\|until\)\>' + call cursor(a:lnum, 1) + let l = searchpair(s:opener, '', s:closer, 'bW', s:skip) + return l > 0 ? indent(l) : 0 + endif + let prev = prevnonblank(a:lnum - 1) + if prev == 0 + return 0 + endif + if cur =~# '^\s*\%(else\|elsif\)\>' + call cursor(a:lnum, 1) + let l = searchpair(s:opener, '', s:closer, 'bW', s:skip) + return l > 0 ? indent(l) : indent(prev) + endif + if cur =~# '^\s*|' + call cursor(a:lnum, 1) + let l = searchpair(s:opener, '', s:closer, 'bW', s:skip) + return l > 0 ? indent(l) : indent(prev) + endif + if s:Continues(prev) || cur =~# s:leading + return -1 + endif + if s:Code(prev) == '' + return indent(s:Reference(prev)) + endif + + let start = s:Start(prev) + let ind = indent(start) + let code = join(map(range(start, prev), 's:Code(v:val)'), ' ') + if code =~# '^\%(const\|type\|var\)$' || code =~# '^else\>' && s:Opens(code) >= 0 + \ || code =~# '^|.*:$' || code =~# '^elsif\>.*\.*\ 0 + return ind + shiftwidth() + endif + return ind +endfunction diff --git a/editor/vim/syntax/jed.vim b/editor/vim/syntax/jed.vim deleted file mode 100644 index 181e067..0000000 --- a/editor/vim/syntax/jed.vim +++ /dev/null @@ -1,42 +0,0 @@ -" Vim syntax file for jed: reserved words, basic types, built-in -" procedures, numbers, characters, strings and nested comments. - -if exists("b:current_syntax") - finish -endif - -syntax case match - -syntax keyword jedKeyword and begin break by code const defer div do else -syntax keyword jedKeyword elsif end extern for forward if import in link -syntax keyword jedKeyword match mod module not of or packed proc record -syntax keyword jedKeyword repeat return set shl shr then to type until var -syntax keyword jedKeyword variant VOLATILE while xor -syntax keyword jedType I8 I16 I32 I64 U8 U16 U32 U64 BOOL F32 F64 ERROR -syntax keyword jedBuiltin SIZE ADR LEN NEW MSG SYSCALL FENCE CAS XCHG XADD -syntax keyword jedBuiltin ARGC ARGV INC DEC -syntax keyword jedConstant true false nil - -" 123, 0FFH, 1.5, 2.0E-3 -syntax match jedNumber "\<\d[0-9A-F]*H\>" -syntax match jedNumber "\<\d\+\>" -syntax match jedNumber "\<\d\+\.\d\+\(E[+-]\=\d\+\)\=\>" - -syntax match jedEscape contained "\\\([ntr0\\'\"]\|x\x\x\|u{\x\+}\)" -syntax region jedString start=+"+ skip=+\\.+ end=+"+ contains=jedEscape oneline -syntax region jedChar start=+'+ skip=+\\.+ end=+'+ contains=jedEscape oneline - -syntax region jedComment start="(\*" end="\*)" contains=jedComment,@Spell -syntax sync fromstart - -highlight default link jedKeyword Statement -highlight default link jedType Type -highlight default link jedBuiltin Function -highlight default link jedConstant Constant -highlight default link jedNumber Number -highlight default link jedString String -highlight default link jedChar Character -highlight default link jedEscape SpecialChar -highlight default link jedComment Comment - -let b:current_syntax = "jed" diff --git a/editor/vim/syntax/raz.vim b/editor/vim/syntax/raz.vim new file mode 100644 index 0000000..6a30213 --- /dev/null +++ b/editor/vim/syntax/raz.vim @@ -0,0 +1,42 @@ +" Vim syntax file for raz: reserved words, basic types, built-in +" procedures, numbers, characters, strings and nested comments. + +if exists("b:current_syntax") + finish +endif + +syntax case match + +syntax keyword razKeyword and begin break by code const defer div do else +syntax keyword razKeyword elsif end extern for forward if import in link +syntax keyword razKeyword match mod module not of or packed proc record +syntax keyword razKeyword repeat return set shl shr then to type until var +syntax keyword razKeyword variant VOLATILE while xor +syntax keyword razType I8 I16 I32 I64 U8 U16 U32 U64 BOOL F32 F64 ERROR +syntax keyword razBuiltin SIZE ADR LEN NEW MSG SYSCALL FENCE CAS XCHG XADD +syntax keyword razBuiltin ARGC ARGV INC DEC +syntax keyword razConstant true false nil + +" 123, 0FFH, 1.5, 2.0E-3 +syntax match razNumber "\<\d[0-9A-F]*H\>" +syntax match razNumber "\<\d\+\>" +syntax match razNumber "\<\d\+\.\d\+\(E[+-]\=\d\+\)\=\>" + +syntax match razEscape contained "\\\([ntr0\\'\"]\|x\x\x\|u{\x\+}\)" +syntax region razString start=+"+ skip=+\\.+ end=+"+ contains=razEscape oneline +syntax region razChar start=+'+ skip=+\\.+ end=+'+ contains=razEscape oneline + +syntax region razComment start="(\*" end="\*)" contains=razComment,@Spell +syntax sync fromstart + +highlight default link razKeyword Statement +highlight default link razType Type +highlight default link razBuiltin Function +highlight default link razConstant Constant +highlight default link razNumber Number +highlight default link razString String +highlight default link razChar Character +highlight default link razEscape SpecialChar +highlight default link razComment Comment + +let b:current_syntax = "raz" diff --git a/examples/Args.jed b/examples/Args.jed deleted file mode 100644 index e79fb27..0000000 --- a/examples/Args.jed +++ /dev/null @@ -1,25 +0,0 @@ -(* Prints its arguments, one per line, and exits with how many. *) -module Args; -import Out; - -(* The length of a C string. *) -proc len(s: ^U8): I64; -var n: I64; -begin - n := 0; - while s[n] # 0 do n := n + 1; end; - return n; -end; - -proc main*: I64; -var i: I64; s: ^U8; -begin - for i := 1 to ARGC() - 1 do - s := ARGV()[i]; - Out.str(s[0..len(s)]); - Out.ln; - end; - return ARGC() - 1; -end; - -end Args. diff --git a/examples/Args.raz b/examples/Args.raz new file mode 100644 index 0000000..e79fb27 --- /dev/null +++ b/examples/Args.raz @@ -0,0 +1,25 @@ +(* Prints its arguments, one per line, and exits with how many. *) +module Args; +import Out; + +(* The length of a C string. *) +proc len(s: ^U8): I64; +var n: I64; +begin + n := 0; + while s[n] # 0 do n := n + 1; end; + return n; +end; + +proc main*: I64; +var i: I64; s: ^U8; +begin + for i := 1 to ARGC() - 1 do + s := ARGV()[i]; + Out.str(s[0..len(s)]); + Out.ln; + end; + return ARGC() - 1; +end; + +end Args. diff --git a/examples/Cpu.jed b/examples/Cpu.jed deleted file mode 100644 index 60b5538..0000000 --- a/examples/Cpu.jed +++ /dev/null @@ -1,29 +0,0 @@ -(* A code procedure: machine code written as bytes, called like any - other procedure. cpuid's vendor string, from leaf 0. *) -module Cpu; -import Out; - -(* cpuid leaf 0: puts the 12 bytes of the vendor in buf, rdi. *) -proc vendor(buf: ^U8); -code 53H, (* push rbx *) - 49H, 89H, 0F8H, (* mov r8, rdi *) - 31H, 0C0H, (* xor eax, eax *) - 0FH, 0A2H, (* cpuid *) - 41H, 89H, 18H, (* mov [r8], ebx *) - 41H, 89H, 50H, 04H, (* mov [r8+4], edx *) - 41H, 89H, 48H, 08H, (* mov [r8+8], ecx *) - 5BH, (* pop rbx *) - 0C3H; (* ret *) - -proc main*; -var buf: [12]U8; i: I64; ok: BOOL; -begin - vendor(ADR(buf[0])); - ok := true; - for i := 0 to 11 do - if (buf[i] < ' ') or (buf[i] > '~') then ok := false; end; - end; - if ok then Out.str("vendor is printable\n"); end; -end; - -end Cpu. diff --git a/examples/Cpu.raz b/examples/Cpu.raz new file mode 100644 index 0000000..60b5538 --- /dev/null +++ b/examples/Cpu.raz @@ -0,0 +1,29 @@ +(* A code procedure: machine code written as bytes, called like any + other procedure. cpuid's vendor string, from leaf 0. *) +module Cpu; +import Out; + +(* cpuid leaf 0: puts the 12 bytes of the vendor in buf, rdi. *) +proc vendor(buf: ^U8); +code 53H, (* push rbx *) + 49H, 89H, 0F8H, (* mov r8, rdi *) + 31H, 0C0H, (* xor eax, eax *) + 0FH, 0A2H, (* cpuid *) + 41H, 89H, 18H, (* mov [r8], ebx *) + 41H, 89H, 50H, 04H, (* mov [r8+4], edx *) + 41H, 89H, 48H, 08H, (* mov [r8+8], ecx *) + 5BH, (* pop rbx *) + 0C3H; (* ret *) + +proc main*; +var buf: [12]U8; i: I64; ok: BOOL; +begin + vendor(ADR(buf[0])); + ok := true; + for i := 0 to 11 do + if (buf[i] < ' ') or (buf[i] > '~') then ok := false; end; + end; + if ok then Out.str("vendor is printable\n"); end; +end; + +end Cpu. diff --git a/examples/Flags.jed b/examples/Flags.jed deleted file mode 100644 index e2dea05..0000000 --- a/examples/Flags.jed +++ /dev/null @@ -1,44 +0,0 @@ -(* Enumerations, sets, record literals and defer: Unix permissions as - sets, which are their bits, and a report that closes its brackets - however it leaves. *) -module Flags; -import Out; - -type - Perm = (x, w, r); (* bits 0, 1, 2, as chmod has them *) - Perms = set of Perm; - Mode = record user, group, other: Perms; end; - -proc digit(p: Perms): I64; -begin - return I64(U8(p)); -end; - -proc show(p: Perms); -begin - if r in p then Out.str("r"); else Out.str("-"); end; - if w in p then Out.str("w"); else Out.str("-"); end; - if x in p then Out.str("x"); else Out.str("-"); end; -end; - -proc report(m: Mode); -begin - Out.str("["); - defer Out.str("]\n"); - show(m.user); show(m.group); show(m.other); - if m.other = {} then return; end; - Out.str(" octal "); - Out.int(digit(m.user)); Out.int(digit(m.group)); Out.int(digit(m.other)); -end; - -proc main*; -var m: Mode; -begin - m := {user: {r, w, x}, group: {r, x}, other: {r}}; - report(m); - m.user := m.user - {x}; - m.other := {}; - report(m); -end; - -end Flags. diff --git a/examples/Flags.raz b/examples/Flags.raz new file mode 100644 index 0000000..e2dea05 --- /dev/null +++ b/examples/Flags.raz @@ -0,0 +1,44 @@ +(* Enumerations, sets, record literals and defer: Unix permissions as + sets, which are their bits, and a report that closes its brackets + however it leaves. *) +module Flags; +import Out; + +type + Perm = (x, w, r); (* bits 0, 1, 2, as chmod has them *) + Perms = set of Perm; + Mode = record user, group, other: Perms; end; + +proc digit(p: Perms): I64; +begin + return I64(U8(p)); +end; + +proc show(p: Perms); +begin + if r in p then Out.str("r"); else Out.str("-"); end; + if w in p then Out.str("w"); else Out.str("-"); end; + if x in p then Out.str("x"); else Out.str("-"); end; +end; + +proc report(m: Mode); +begin + Out.str("["); + defer Out.str("]\n"); + show(m.user); show(m.group); show(m.other); + if m.other = {} then return; end; + Out.str(" octal "); + Out.int(digit(m.user)); Out.int(digit(m.group)); Out.int(digit(m.other)); +end; + +proc main*; +var m: Mode; +begin + m := {user: {r, w, x}, group: {r, x}, other: {r}}; + report(m); + m.user := m.user - {x}; + m.other := {}; + report(m); +end; + +end Flags. diff --git a/examples/Hello.jed b/examples/Hello.jed deleted file mode 100644 index dede538..0000000 --- a/examples/Hello.jed +++ /dev/null @@ -1,9 +0,0 @@ -module Hello; -import Out; - -proc main*; -begin - Out.str("hello, world\n"); -end; - -end Hello. diff --git a/examples/Hello.raz b/examples/Hello.raz new file mode 100644 index 0000000..dede538 --- /dev/null +++ b/examples/Hello.raz @@ -0,0 +1,9 @@ +module Hello; +import Out; + +proc main*; +begin + Out.str("hello, world\n"); +end; + +end Hello. diff --git a/examples/Printf.expect b/examples/Printf.expect index 68d4068..71d6056 100644 --- a/examples/Printf.expect +++ b/examples/Printf.expect @@ -1,6 +1,6 @@ -jed says 1 +raz says 1 C says 1, squared -jed says 2 +raz says 2 C says 4, squared -jed says 3 +raz says 3 C says 9, squared diff --git a/examples/Printf.jed b/examples/Printf.jed deleted file mode 100644 index 5a4193f..0000000 --- a/examples/Printf.jed +++ /dev/null @@ -1,17 +0,0 @@ -(* Out and C's printf, writing to the same standard output. Each keeps - a buffer of its own, so each is flushed before the other writes. *) -module Printf; -import Out, C; - -proc main*; -var i: I64; -begin - for i := 1 to 3 do - Out.str("jed says "); Out.int(i); Out.ln; - Out.flush; - C.printf("C says %d, %s\n", I32(i * i), "squared"); - C.fflush(C.stdout); - end; -end; - -end Printf. diff --git a/examples/Printf.raz b/examples/Printf.raz new file mode 100644 index 0000000..90d6c0f --- /dev/null +++ b/examples/Printf.raz @@ -0,0 +1,17 @@ +(* Out and C's printf, writing to the same standard output. Each keeps + a buffer of its own, so each is flushed before the other writes. *) +module Printf; +import Out, C; + +proc main*; +var i: I64; +begin + for i := 1 to 3 do + Out.str("raz says "); Out.int(i); Out.ln; + Out.flush; + C.printf("C says %d, %s\n", I32(i * i), "squared"); + C.fflush(C.stdout); + end; +end; + +end Printf. diff --git a/examples/Pthreads.jed b/examples/Pthreads.jed deleted file mode 100644 index a38ad4f..0000000 --- a/examples/Pthreads.jed +++ /dev/null @@ -1,52 +0,0 @@ -(* Threads from C's pthread_create, each summing its part of an array - and using the heap and Out, which lock themselves. *) -module Pthreads; -import Out, C, Heap, Mem; - -const - Workers = 4; - N = 1000000; - -type - Part = record lo, hi, sum: I64; end; - Numbers = [N]I64; - -var numbers: ^Numbers; - -proc work(arg: ^U8): ^U8; -var p: ^Part; i: I64; scratch: ^U8; -begin - p := ^Part(arg); - for i := p^.lo to p^.hi - 1 do - p^.sum := p^.sum + numbers^[i]; - if i mod 1000 = 0 then - scratch := Mem.alloc(Heap.heap, 100, 8); - Mem.free(Heap.heap, scratch); - end; - end; - Out.str("a part summed\n"); - return nil; -end; - -proc main*: I64; -var t: [Workers]U64; parts: [Workers]Part; i, total: I64; -begin - NEW(numbers, Heap.heap); - for i := 0 to N - 1 do numbers^[i] := i + 1; end; - for i := 0 to Workers - 1 do - parts[i] := {lo: i * N div Workers, hi: (i + 1) * N div Workers}; - if C.pthread_create(ADR(t[i]), nil, work, ^U8(ADR(parts[i]))) # 0 then - Out.str("can't start a thread\n"); - return 1; - end; - end; - total := 0; - for i := 0 to Workers - 1 do - C.pthread_join(t[i], nil); - total := total + parts[i].sum; - end; - Out.str("total "); Out.int(total); Out.ln; - return 0; -end; - -end Pthreads. diff --git a/examples/Pthreads.raz b/examples/Pthreads.raz new file mode 100644 index 0000000..a38ad4f --- /dev/null +++ b/examples/Pthreads.raz @@ -0,0 +1,52 @@ +(* Threads from C's pthread_create, each summing its part of an array + and using the heap and Out, which lock themselves. *) +module Pthreads; +import Out, C, Heap, Mem; + +const + Workers = 4; + N = 1000000; + +type + Part = record lo, hi, sum: I64; end; + Numbers = [N]I64; + +var numbers: ^Numbers; + +proc work(arg: ^U8): ^U8; +var p: ^Part; i: I64; scratch: ^U8; +begin + p := ^Part(arg); + for i := p^.lo to p^.hi - 1 do + p^.sum := p^.sum + numbers^[i]; + if i mod 1000 = 0 then + scratch := Mem.alloc(Heap.heap, 100, 8); + Mem.free(Heap.heap, scratch); + end; + end; + Out.str("a part summed\n"); + return nil; +end; + +proc main*: I64; +var t: [Workers]U64; parts: [Workers]Part; i, total: I64; +begin + NEW(numbers, Heap.heap); + for i := 0 to N - 1 do numbers^[i] := i + 1; end; + for i := 0 to Workers - 1 do + parts[i] := {lo: i * N div Workers, hi: (i + 1) * N div Workers}; + if C.pthread_create(ADR(t[i]), nil, work, ^U8(ADR(parts[i]))) # 0 then + Out.str("can't start a thread\n"); + return 1; + end; + end; + total := 0; + for i := 0 to Workers - 1 do + C.pthread_join(t[i], nil); + total := total + parts[i].sum; + end; + Out.str("total "); Out.int(total); Out.ln; + return 0; +end; + +end Pthreads. diff --git a/examples/Shapes.jed b/examples/Shapes.jed deleted file mode 100644 index d5e95da..0000000 --- a/examples/Shapes.jed +++ /dev/null @@ -1,39 +0,0 @@ -(* Variants and slices: a list of shapes, measured. *) -module Shapes; -import Out; - -type - Shape = variant - circle(r: I64); - rect(w, h: I64); - dot; - end; - -(* Twice the area, rounded down, of a circle taken as pi = 22/7. *) -proc area(s: Shape): I64; -begin - match s of - | circle(r): return 44 * r * r div 7; - | rect(w, h): return 2 * w * h; - | dot: return 0; - end; -end; - -proc total(shapes: []Shape): I64; -var i, sum: I64; -begin - sum := 0; - for i := 0 to LEN(shapes) - 1 do sum := sum + area(shapes[i]); end; - return sum; -end; - -proc main*; -var shapes: [4]Shape; -begin - shapes := [circle(7), rect(3, 4), dot, rect(1, 1)]; - Out.str("all: "); Out.int(total(shapes)); Out.ln; - Out.str("last two: "); Out.int(total(shapes[2..4])); Out.ln; - Out.str("none: "); Out.int(total(shapes[0..0])); Out.ln; -end; - -end Shapes. diff --git a/examples/Shapes.raz b/examples/Shapes.raz new file mode 100644 index 0000000..d5e95da --- /dev/null +++ b/examples/Shapes.raz @@ -0,0 +1,39 @@ +(* Variants and slices: a list of shapes, measured. *) +module Shapes; +import Out; + +type + Shape = variant + circle(r: I64); + rect(w, h: I64); + dot; + end; + +(* Twice the area, rounded down, of a circle taken as pi = 22/7. *) +proc area(s: Shape): I64; +begin + match s of + | circle(r): return 44 * r * r div 7; + | rect(w, h): return 2 * w * h; + | dot: return 0; + end; +end; + +proc total(shapes: []Shape): I64; +var i, sum: I64; +begin + sum := 0; + for i := 0 to LEN(shapes) - 1 do sum := sum + area(shapes[i]); end; + return sum; +end; + +proc main*; +var shapes: [4]Shape; +begin + shapes := [circle(7), rect(3, 4), dot, rect(1, 1)]; + Out.str("all: "); Out.int(total(shapes)); Out.ln; + Out.str("last two: "); Out.int(total(shapes[2..4])); Out.ln; + Out.str("none: "); Out.int(total(shapes[0..0])); Out.ln; +end; + +end Shapes. diff --git a/examples/Volatile.jed b/examples/Volatile.jed deleted file mode 100644 index fe0bc9f..0000000 --- a/examples/Volatile.jed +++ /dev/null @@ -1,32 +0,0 @@ -(* A record laid over memory that something else may change: here a - page of the program's own, as a device's registers would be. Every - access through the ^VOLATILE pointer is one instruction of its - size, in the order written. *) -module Volatile; -import Out; - -type - Uart = record - data: U32; - status: U32; - control: U8; - end; - -var page: [64]U8; - -proc main*; -var dev: ^VOLATILE Uart; i: I64; -begin - dev := ^VOLATILE Uart(ADR(page)); - dev^.control := 1; - dev^.status := 0FFH; - for i := 0 to 2 do - dev^.data := U32('a' + i); - Out.char(U8(dev^.data)); - end; - Out.ln; - FENCE; - Out.int(I64(page[8])); Out.str(" "); Out.int(I64(dev^.status)); Out.ln; -end; - -end Volatile. diff --git a/examples/Volatile.raz b/examples/Volatile.raz new file mode 100644 index 0000000..fe0bc9f --- /dev/null +++ b/examples/Volatile.raz @@ -0,0 +1,32 @@ +(* A record laid over memory that something else may change: here a + page of the program's own, as a device's registers would be. Every + access through the ^VOLATILE pointer is one instruction of its + size, in the order written. *) +module Volatile; +import Out; + +type + Uart = record + data: U32; + status: U32; + control: U8; + end; + +var page: [64]U8; + +proc main*; +var dev: ^VOLATILE Uart; i: I64; +begin + dev := ^VOLATILE Uart(ADR(page)); + dev^.control := 1; + dev^.status := 0FFH; + for i := 0 to 2 do + dev^.data := U32('a' + i); + Out.char(U8(dev^.data)); + end; + Out.ln; + FENCE; + Out.int(I64(page[8])); Out.str(" "); Out.int(I64(dev^.status)); Out.ln; +end; + +end Volatile. diff --git a/examples/Window.jed b/examples/Window.jed deleted file mode 100644 index 99c5079..0000000 --- a/examples/Window.jed +++ /dev/null @@ -1,70 +0,0 @@ -(* An X11 window that says hello, and closes at a key press. An XEvent - is a C union: it is read as an array of words, and the member its - type says it holds through a pointer conversion. Compiled by make - check, not run: it needs a display. *) -module Window; -import Out; -link "libX11.so.6"; - -const - KeyPress = 2; - Expose = 12; - KeyPressMask = 1; - ExposureMask = 8000H; - -type - (* XKeyEvent, laid out as C lays it out *) - KeyEvent = record - typ: I32; - serial: U64; - sendEvent: I32; - display: ^U8; - window, root, subwindow, time: U64; - x, y, xRoot, yRoot: I32; - state, keycode: U32; - sameScreen: I32; - end; - -extern proc XOpenDisplay(name: ^U8): ^U8; -extern proc XDefaultScreen(d: ^U8): I32; -extern proc XRootWindow(d: ^U8; screen: I32): U64; -extern proc XBlackPixel(d: ^U8; screen: I32): U64; -extern proc XWhitePixel(d: ^U8; screen: I32): U64; -extern proc XDefaultGC(d: ^U8; screen: I32): ^U8; -extern proc XCreateSimpleWindow(d: ^U8; parent: U64; x, y: I32; - width, height, border: U32; borderColor, background: U64): U64; -extern proc XStoreName(d: ^U8; w: U64; name: ^U8): I32; -extern proc XSelectInput(d: ^U8; w: U64; mask: I64): I32; -extern proc XMapWindow(d: ^U8; w: U64): I32; -extern proc XNextEvent(d: ^U8; ev: ^U8): I32; -extern proc XDrawString(d: ^U8; w: U64; gc: ^U8; x, y: I32; s: ^U8; n: I32): I32; -extern proc XCloseDisplay(d: ^U8): I32; - -proc main*: I64; -const text = "hello, world: press a key"; -var - d: ^U8; s: I32; w: U64; - ev: [24]I64; (* XEvent: 192 bytes *) - key: ^KeyEvent; -begin - d := XOpenDisplay(nil); - if d = nil then Out.str("no display\n"); return 1; end; - s := XDefaultScreen(d); - w := XCreateSimpleWindow(d, XRootWindow(d, s), 0, 0, 320, 80, 1, - XBlackPixel(d, s), XWhitePixel(d, s)); - XStoreName(d, w, "jed"); - XSelectInput(d, w, ExposureMask + KeyPressMask); - XMapWindow(d, w); - repeat - XNextEvent(d, ^U8(ADR(ev))); - if I32(ev[0]) = Expose then - XDrawString(d, w, XDefaultGC(d, s), 20, 45, text, I32(LEN(text))); - end; - until I32(ev[0]) = KeyPress; - key := ^KeyEvent(ADR(ev)); - Out.str("key "); Out.int(I64(key^.keycode)); Out.ln; - XCloseDisplay(d); - return 0; -end; - -end Window. diff --git a/examples/Window.raz b/examples/Window.raz new file mode 100644 index 0000000..3d74e8e --- /dev/null +++ b/examples/Window.raz @@ -0,0 +1,70 @@ +(* An X11 window that says hello, and closes at a key press. An XEvent + is a C union: it is read as an array of words, and the member its + type says it holds through a pointer conversion. Compiled by make + check, not run: it needs a display. *) +module Window; +import Out; +link "libX11.so.6"; + +const + KeyPress = 2; + Expose = 12; + KeyPressMask = 1; + ExposureMask = 8000H; + +type + (* XKeyEvent, laid out as C lays it out *) + KeyEvent = record + typ: I32; + serial: U64; + sendEvent: I32; + display: ^U8; + window, root, subwindow, time: U64; + x, y, xRoot, yRoot: I32; + state, keycode: U32; + sameScreen: I32; + end; + +extern proc XOpenDisplay(name: ^U8): ^U8; +extern proc XDefaultScreen(d: ^U8): I32; +extern proc XRootWindow(d: ^U8; screen: I32): U64; +extern proc XBlackPixel(d: ^U8; screen: I32): U64; +extern proc XWhitePixel(d: ^U8; screen: I32): U64; +extern proc XDefaultGC(d: ^U8; screen: I32): ^U8; +extern proc XCreateSimpleWindow(d: ^U8; parent: U64; x, y: I32; + width, height, border: U32; borderColor, background: U64): U64; +extern proc XStoreName(d: ^U8; w: U64; name: ^U8): I32; +extern proc XSelectInput(d: ^U8; w: U64; mask: I64): I32; +extern proc XMapWindow(d: ^U8; w: U64): I32; +extern proc XNextEvent(d: ^U8; ev: ^U8): I32; +extern proc XDrawString(d: ^U8; w: U64; gc: ^U8; x, y: I32; s: ^U8; n: I32): I32; +extern proc XCloseDisplay(d: ^U8): I32; + +proc main*: I64; +const text = "hello, world: press a key"; +var + d: ^U8; s: I32; w: U64; + ev: [24]I64; (* XEvent: 192 bytes *) + key: ^KeyEvent; +begin + d := XOpenDisplay(nil); + if d = nil then Out.str("no display\n"); return 1; end; + s := XDefaultScreen(d); + w := XCreateSimpleWindow(d, XRootWindow(d, s), 0, 0, 320, 80, 1, + XBlackPixel(d, s), XWhitePixel(d, s)); + XStoreName(d, w, "raz"); + XSelectInput(d, w, ExposureMask + KeyPressMask); + XMapWindow(d, w); + repeat + XNextEvent(d, ^U8(ADR(ev))); + if I32(ev[0]) = Expose then + XDrawString(d, w, XDefaultGC(d, s), 20, 45, text, I32(LEN(text))); + end; + until I32(ev[0]) = KeyPress; + key := ^KeyEvent(ADR(ev)); + Out.str("key "); Out.int(I64(key^.keycode)); Out.ln; + XCloseDisplay(d); + return 0; +end; + +end Window. diff --git a/examples/Words.jed b/examples/Words.jed deleted file mode 100644 index ee1eba9..0000000 --- a/examples/Words.jed +++ /dev/null @@ -1,37 +0,0 @@ -(* Generic modules: counts the words of a text in a Map from []U8 to - I64, hashed and compared by Str's procedures, keeps them in order of - first sight in a List([]U8), and prints them with Fmt. *) -module Words; -import Fmt, Str, Heap, Count := Map([]U8, I64, Str.hash, Str.eq), Names := List([]U8); - -const Text = "the cat and the hat and the bat"; - -proc main*; -var - counts: Count.Map; order: Names.List; n: ^Names.Node; - i, start, k, total: I64; found, ok: BOOL; w: []U8; -begin - Count.init(ADR(counts), Heap.heap); - Names.init(ADR(order), Heap.heap); - start := 0; - for i := 0 to LEN(Text) do - if (i = LEN(Text)) or (Text[i] = ' ') then - w := Text[start..i]; - INC(total); - k, found := Count.get(ADR(counts), w); - if not found then ok := Names.push(ADR(order), w); end; - ok := Count.put(ADR(counts), w, k + 1); - start := i + 1; - end; - end; - Names.reverse(ADR(order)); - n := order.head; - while n # nil do - k, found := Count.get(ADR(counts), n^.val); - Fmt.print("{} {}\n", [Fmt.str(n^.val), Fmt.int(k)]); - n := n^.next; - end; - Fmt.print("{} words, {} different\n", [Fmt.int(total), Fmt.int(counts.len)]); -end; - -end Words. diff --git a/examples/Words.raz b/examples/Words.raz new file mode 100644 index 0000000..ee1eba9 --- /dev/null +++ b/examples/Words.raz @@ -0,0 +1,37 @@ +(* Generic modules: counts the words of a text in a Map from []U8 to + I64, hashed and compared by Str's procedures, keeps them in order of + first sight in a List([]U8), and prints them with Fmt. *) +module Words; +import Fmt, Str, Heap, Count := Map([]U8, I64, Str.hash, Str.eq), Names := List([]U8); + +const Text = "the cat and the hat and the bat"; + +proc main*; +var + counts: Count.Map; order: Names.List; n: ^Names.Node; + i, start, k, total: I64; found, ok: BOOL; w: []U8; +begin + Count.init(ADR(counts), Heap.heap); + Names.init(ADR(order), Heap.heap); + start := 0; + for i := 0 to LEN(Text) do + if (i = LEN(Text)) or (Text[i] = ' ') then + w := Text[start..i]; + INC(total); + k, found := Count.get(ADR(counts), w); + if not found then ok := Names.push(ADR(order), w); end; + ok := Count.put(ADR(counts), w, k + 1); + start := i + 1; + end; + end; + Names.reverse(ADR(order)); + n := order.head; + while n # nil do + k, found := Count.get(ADR(counts), n^.val); + Fmt.print("{} {}\n", [Fmt.str(n^.val), Fmt.int(k)]); + n := n^.next; + end; + Fmt.print("{} words, {} different\n", [Fmt.int(total), Fmt.int(counts.len)]); +end; + +end Words. diff --git a/examples/Workers.jed b/examples/Workers.jed deleted file mode 100644 index cd95a50..0000000 --- a/examples/Workers.jed +++ /dev/null @@ -1,48 +0,0 @@ -(* Native threads, for a program without C: workers that take jobs - from a shared counter and add up their results under a Mutex. *) -module Workers; -import Out, Thread; - -const - Workers = 4; - Jobs = 100; - -var - next: I64; (* the next job, taken with XADD *) - m: Thread.Mutex; - total: I64; - -(* job n: the sum of the squares up to n *) -proc job(n: I64): I64; -var i, s: I64; -begin - s := 0; - for i := 1 to n do s := s + i * i; end; - return s; -end; - -proc work(arg: ^U8); -var n, r: I64; -begin - n := XADD(ADR(next), 1); - while n < Jobs do - r := job(n * 1000); - Thread.lock(ADR(m)); - total := total + r; - Thread.unlock(ADR(m)); - n := XADD(ADR(next), 1); - end; -end; - -proc main*; -var t: [Workers]^Thread.Thread; i: I64; err: ERROR; -begin - for i := 0 to Workers - 1 do - t[i], err := Thread.spawn(work, nil); - if err # nil then Out.str(MSG(err)); Out.ln; return; end; - end; - for i := 0 to Workers - 1 do Thread.join(t[i]); end; - Out.str("total "); Out.int(total); Out.ln; -end; - -end Workers. diff --git a/examples/Workers.raz b/examples/Workers.raz new file mode 100644 index 0000000..cd95a50 --- /dev/null +++ b/examples/Workers.raz @@ -0,0 +1,48 @@ +(* Native threads, for a program without C: workers that take jobs + from a shared counter and add up their results under a Mutex. *) +module Workers; +import Out, Thread; + +const + Workers = 4; + Jobs = 100; + +var + next: I64; (* the next job, taken with XADD *) + m: Thread.Mutex; + total: I64; + +(* job n: the sum of the squares up to n *) +proc job(n: I64): I64; +var i, s: I64; +begin + s := 0; + for i := 1 to n do s := s + i * i; end; + return s; +end; + +proc work(arg: ^U8); +var n, r: I64; +begin + n := XADD(ADR(next), 1); + while n < Jobs do + r := job(n * 1000); + Thread.lock(ADR(m)); + total := total + r; + Thread.unlock(ADR(m)); + n := XADD(ADR(next), 1); + end; +end; + +proc main*; +var t: [Workers]^Thread.Thread; i: I64; err: ERROR; +begin + for i := 0 to Workers - 1 do + t[i], err := Thread.spawn(work, nil); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + end; + for i := 0 to Workers - 1 do Thread.join(t[i]); end; + Out.str("total "); Out.int(total); Out.ln; +end; + +end Workers. diff --git a/lib/Arena.jed b/lib/Arena.jed deleted file mode 100644 index 278014c..0000000 --- a/lib/Arena.jed +++ /dev/null @@ -1,68 +0,0 @@ -(* An allocator that hands out memory from one block and frees it all - at once: free does nothing, reset forgets everything. An Arena is - its allocator: ADR(arena.base) is the ^Mem.Allocator to give NEW. *) -module Arena; -import Mem, Rt; - -type - Arena* = record - base*: Mem.Allocator; (* first, so that ^Arena(a) finds the rest *) - buf: ^U8; - used, cap: I64; - end; - -proc alloc(a: ^Mem.Allocator; size, align: I64): ^U8; -var ar: ^Arena; at: I64; -begin - ar := ^Arena(a); - at := (ar^.used + align - 1) div align * align; - if (size < 0) or (at + size > ar^.cap) then return nil; end; - ar^.used := at + size; - return ar^.buf + at; -end; - -proc free(a: ^Mem.Allocator; p: ^U8); -begin -end; - -(* An arena of size bytes; false if the system has none. *) -proc init*(ar: ^Arena; size: I64): BOOL; -begin - ar^.base := {alloc: alloc, free: free}; - ar^.buf := Mem.pages(size); - ar^.used := 0; - ar^.cap := size; - if ar^.buf = nil then ar^.cap := 0; end; - return ar^.buf # nil; -end; - -(* Forgets every allocation; the memory is used again. *) -proc reset*(ar: ^Arena); -begin - ar^.used := 0; -end; - -proc done*(ar: ^Arena); -begin - if ar^.buf # nil then Mem.unmap(ar^.buf, ar^.cap); end; - ar^.buf := nil; - ar^.cap := 0; -end; - -(* The module's test. *) -proc main*; -var ar: Arena; a: ^Mem.Allocator; p, q: ^U8; -begin - if not init(ADR(ar), 4096) then Rt.stop("Arena.init"); end; - a := ADR(ar.base); - p := Mem.alloc(a, 3, 1); - q := Mem.alloc(a, 8, 8); - if (p = nil) or (q # p + 8) then Rt.stop("Arena: alignment"); end; - if Mem.alloc(a, 5000, 1) # nil then Rt.stop("Arena: too big"); end; - if Mem.alloc(a, -1, 1) # nil then Rt.stop("Arena: negative"); end; - reset(ADR(ar)); - if Mem.alloc(a, 4096, 1) # p then Rt.stop("Arena.reset"); end; - done(ADR(ar)); -end; - -end Arena. diff --git a/lib/Arena.raz b/lib/Arena.raz new file mode 100644 index 0000000..278014c --- /dev/null +++ b/lib/Arena.raz @@ -0,0 +1,68 @@ +(* An allocator that hands out memory from one block and frees it all + at once: free does nothing, reset forgets everything. An Arena is + its allocator: ADR(arena.base) is the ^Mem.Allocator to give NEW. *) +module Arena; +import Mem, Rt; + +type + Arena* = record + base*: Mem.Allocator; (* first, so that ^Arena(a) finds the rest *) + buf: ^U8; + used, cap: I64; + end; + +proc alloc(a: ^Mem.Allocator; size, align: I64): ^U8; +var ar: ^Arena; at: I64; +begin + ar := ^Arena(a); + at := (ar^.used + align - 1) div align * align; + if (size < 0) or (at + size > ar^.cap) then return nil; end; + ar^.used := at + size; + return ar^.buf + at; +end; + +proc free(a: ^Mem.Allocator; p: ^U8); +begin +end; + +(* An arena of size bytes; false if the system has none. *) +proc init*(ar: ^Arena; size: I64): BOOL; +begin + ar^.base := {alloc: alloc, free: free}; + ar^.buf := Mem.pages(size); + ar^.used := 0; + ar^.cap := size; + if ar^.buf = nil then ar^.cap := 0; end; + return ar^.buf # nil; +end; + +(* Forgets every allocation; the memory is used again. *) +proc reset*(ar: ^Arena); +begin + ar^.used := 0; +end; + +proc done*(ar: ^Arena); +begin + if ar^.buf # nil then Mem.unmap(ar^.buf, ar^.cap); end; + ar^.buf := nil; + ar^.cap := 0; +end; + +(* The module's test. *) +proc main*; +var ar: Arena; a: ^Mem.Allocator; p, q: ^U8; +begin + if not init(ADR(ar), 4096) then Rt.stop("Arena.init"); end; + a := ADR(ar.base); + p := Mem.alloc(a, 3, 1); + q := Mem.alloc(a, 8, 8); + if (p = nil) or (q # p + 8) then Rt.stop("Arena: alignment"); end; + if Mem.alloc(a, 5000, 1) # nil then Rt.stop("Arena: too big"); end; + if Mem.alloc(a, -1, 1) # nil then Rt.stop("Arena: negative"); end; + reset(ADR(ar)); + if Mem.alloc(a, 4096, 1) # p then Rt.stop("Arena.reset"); end; + done(ADR(ar)); +end; + +end Arena. diff --git a/lib/Buf.jed b/lib/Buf.jed deleted file mode 100644 index 276ba65..0000000 --- a/lib/Buf.jed +++ /dev/null @@ -1,91 +0,0 @@ -(* A growable byte buffer, its memory from an allocator. *) -module Buf; -import Mem, Arena, Rt; - -type - Buf* = record - a: ^Mem.Allocator; - data: ^U8; - len*, cap: I64; - end; - -proc init*(b: ^Buf; a: ^Mem.Allocator); -begin - b^ := {a: a}; -end; - -(* Room for n more bytes; false if the allocator has none. *) -proc room*(b: ^Buf; n: I64): BOOL; -var cap, i: I64; p: ^U8; -begin - if b^.len + n <= b^.cap then return true; end; - cap := b^.cap * 2; - if cap < 64 then cap := 64; end; - while cap < b^.len + n do cap := cap * 2; end; - p := Mem.alloc(b^.a, cap, 1); - if p = nil then return false; end; - for i := 0 to b^.len - 1 do p[i] := b^.data[i]; end; - if b^.data # nil then Mem.free(b^.a, b^.data); end; - b^.data := p; - b^.cap := cap; - return true; -end; - -proc add*(b: ^Buf; c: U8); -begin - if room(b, 1) then - b^.data[b^.len] := c; - INC(b^.len); - end; -end; - -proc str*(b: ^Buf; s: []U8); -var i: I64; -begin - if room(b, LEN(s)) then - for i := 0 to LEN(s) - 1 do b^.data[b^.len + i] := s[i]; end; - INC(b^.len, LEN(s)); - end; -end; - -(* What the buffer holds, until it next grows. *) -proc bytes*(b: ^Buf): []U8; -begin - if b^.len = 0 then return ""; end; - return b^.data[0..b^.len]; -end; - -proc reset*(b: ^Buf); -begin - b^.len := 0; -end; - -proc done*(b: ^Buf); -begin - if b^.data # nil then Mem.free(b^.a, b^.data); end; - b^.data := nil; - b^.len := 0; - b^.cap := 0; -end; - -(* The module's test, over an arena. *) -proc main*; -var ar: Arena.Arena; b: Buf; i: I64; s: []U8; -begin - if not Arena.init(ADR(ar), 1 shl 20) then Rt.stop("Buf: no arena"); end; - init(ADR(b), ADR(ar.base)); - if LEN(bytes(ADR(b))) # 0 then Rt.stop("Buf: not empty"); end; - for i := 0 to 9999 do add(ADR(b), U8(i mod 251)); end; - str(ADR(b), "end"); - s := bytes(ADR(b)); - if (LEN(s) # 10003) or (s[9998] # U8(9998 mod 251)) or (s[10000..10003] # "end") then - Rt.stop("Buf: contents"); - end; - reset(ADR(b)); - str(ADR(b), "again"); - if bytes(ADR(b)) # "again" then Rt.stop("Buf.reset"); end; - done(ADR(b)); - Arena.done(ADR(ar)); -end; - -end Buf. diff --git a/lib/Buf.raz b/lib/Buf.raz new file mode 100644 index 0000000..276ba65 --- /dev/null +++ b/lib/Buf.raz @@ -0,0 +1,91 @@ +(* A growable byte buffer, its memory from an allocator. *) +module Buf; +import Mem, Arena, Rt; + +type + Buf* = record + a: ^Mem.Allocator; + data: ^U8; + len*, cap: I64; + end; + +proc init*(b: ^Buf; a: ^Mem.Allocator); +begin + b^ := {a: a}; +end; + +(* Room for n more bytes; false if the allocator has none. *) +proc room*(b: ^Buf; n: I64): BOOL; +var cap, i: I64; p: ^U8; +begin + if b^.len + n <= b^.cap then return true; end; + cap := b^.cap * 2; + if cap < 64 then cap := 64; end; + while cap < b^.len + n do cap := cap * 2; end; + p := Mem.alloc(b^.a, cap, 1); + if p = nil then return false; end; + for i := 0 to b^.len - 1 do p[i] := b^.data[i]; end; + if b^.data # nil then Mem.free(b^.a, b^.data); end; + b^.data := p; + b^.cap := cap; + return true; +end; + +proc add*(b: ^Buf; c: U8); +begin + if room(b, 1) then + b^.data[b^.len] := c; + INC(b^.len); + end; +end; + +proc str*(b: ^Buf; s: []U8); +var i: I64; +begin + if room(b, LEN(s)) then + for i := 0 to LEN(s) - 1 do b^.data[b^.len + i] := s[i]; end; + INC(b^.len, LEN(s)); + end; +end; + +(* What the buffer holds, until it next grows. *) +proc bytes*(b: ^Buf): []U8; +begin + if b^.len = 0 then return ""; end; + return b^.data[0..b^.len]; +end; + +proc reset*(b: ^Buf); +begin + b^.len := 0; +end; + +proc done*(b: ^Buf); +begin + if b^.data # nil then Mem.free(b^.a, b^.data); end; + b^.data := nil; + b^.len := 0; + b^.cap := 0; +end; + +(* The module's test, over an arena. *) +proc main*; +var ar: Arena.Arena; b: Buf; i: I64; s: []U8; +begin + if not Arena.init(ADR(ar), 1 shl 20) then Rt.stop("Buf: no arena"); end; + init(ADR(b), ADR(ar.base)); + if LEN(bytes(ADR(b))) # 0 then Rt.stop("Buf: not empty"); end; + for i := 0 to 9999 do add(ADR(b), U8(i mod 251)); end; + str(ADR(b), "end"); + s := bytes(ADR(b)); + if (LEN(s) # 10003) or (s[9998] # U8(9998 mod 251)) or (s[10000..10003] # "end") then + Rt.stop("Buf: contents"); + end; + reset(ADR(b)); + str(ADR(b), "again"); + if bytes(ADR(b)) # "again" then Rt.stop("Buf.reset"); end; + done(ADR(b)); + Arena.done(ADR(ar)); +end; + +end Buf. diff --git a/lib/C.jed b/lib/C.jed deleted file mode 100644 index d2ece07..0000000 --- a/lib/C.jed +++ /dev/null @@ -1,25 +0,0 @@ -(* The C library: what jed's own library calls in it, and what most - programs reach for. A program that imports C uses C, and so is - linked dynamically and starts through the C library. *) -module C; - -extern proc write*(fd: I32; buf: ^U8; n: U64): I64; -extern proc read*(fd: I32; buf: ^U8; n: U64): I64; -extern proc open*(path: ^U8; flags: I32; ...): I32; -extern proc creat*(path: ^U8; mode: U32): I32; -extern proc close*(fd: I32): I32; -extern proc mmap*(addr: ^U8; n: U64; prot, flags, fd: I32; off: I64): ^U8; -extern proc munmap*(addr: ^U8; n: U64): I32; -extern proc isatty*(fd: I32): I32; -extern proc exit*(status: I32); -extern proc _exit*(status: I32); -extern proc __errno_location*: ^I32; (* errno is this thread's: through here *) -extern proc sched_yield*: I32; -extern proc pthread_create*(t: ^U64; attr: ^U8; start: proc(arg: ^U8): ^U8; arg: ^U8): I32; -extern proc pthread_join*(t: U64; result: ^^U8): I32; -extern proc printf*(format: ^U8; ...): I32; -extern proc fflush*(f: ^U8): I32; -extern var stdout*: ^U8; (* FILE * *) -extern var stderr*: ^U8; - -end C. diff --git a/lib/C.raz b/lib/C.raz new file mode 100644 index 0000000..07affb9 --- /dev/null +++ b/lib/C.raz @@ -0,0 +1,25 @@ +(* The C library: what raz's own library calls in it, and what most + programs reach for. A program that imports C uses C, and so is + linked dynamically and starts through the C library. *) +module C; + +extern proc write*(fd: I32; buf: ^U8; n: U64): I64; +extern proc read*(fd: I32; buf: ^U8; n: U64): I64; +extern proc open*(path: ^U8; flags: I32; ...): I32; +extern proc creat*(path: ^U8; mode: U32): I32; +extern proc close*(fd: I32): I32; +extern proc mmap*(addr: ^U8; n: U64; prot, flags, fd: I32; off: I64): ^U8; +extern proc munmap*(addr: ^U8; n: U64): I32; +extern proc isatty*(fd: I32): I32; +extern proc exit*(status: I32); +extern proc _exit*(status: I32); +extern proc __errno_location*: ^I32; (* errno is this thread's: through here *) +extern proc sched_yield*: I32; +extern proc pthread_create*(t: ^U64; attr: ^U8; start: proc(arg: ^U8): ^U8; arg: ^U8): I32; +extern proc pthread_join*(t: U64; result: ^^U8): I32; +extern proc printf*(format: ^U8; ...): I32; +extern proc fflush*(f: ^U8): I32; +extern var stdout*: ^U8; (* FILE * *) +extern var stderr*: ^U8; + +end C. diff --git a/lib/Fmt.jed b/lib/Fmt.jed deleted file mode 100644 index bc8e059..0000000 --- a/lib/Fmt.jed +++ /dev/null @@ -1,105 +0,0 @@ -(* Formatted output. Each {} in the format takes the next argument: - Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)]); - {{ and }} stand for { and }. print writes to standard output, - write appends to a Buf. *) -module Fmt; -import Out, Buf, Arena, Rt; - -type - Arg* = variant - int(i: I64); - uint(u: U64); - hex(h: U64); - str(s: []U8); - char(c: U8); - bool(b: BOOL); - end; - -(* The digits of u in base, at the end of the array: it and where they start. *) -proc digits(u: U64; base: U64): ([24]U8, I64); -var d: [24]U8; i: I64; v: U8; -begin - i := 24; - repeat - DEC(i); - v := U8(u mod base); - if v < 10 then d[i] := v + '0'; else d[i] := v - 10 + 'A'; end; - u := u div base; - until u = 0; - return d, i; -end; - -(* Where the pieces go: to b, or to standard output if b is nil. *) -proc put(b: ^Buf.Buf; s: []U8); -begin - if b = nil then Out.str(s); else Buf.str(b, s); end; -end; - -proc arg(b: ^Buf.Buf; a: Arg); -var d: [24]U8; at: I64; one: [1]U8; -begin - match a of - | int(i): - if i < 0 then - put(b, "-"); - d, at := digits(0 - U64(i), 10); - else - d, at := digits(U64(i), 10); - end; - put(b, d[at..24]); - | uint(u): d, at := digits(u, 10); put(b, d[at..24]); - | hex(h): d, at := digits(h, 16); put(b, d[at..24]); - | str(s): put(b, s); - | char(c): one[0] := c; put(b, one); - | bool(t): if t then put(b, "true"); else put(b, "false"); end; - end; -end; - -proc format(b: ^Buf.Buf; f: []U8; args: []Arg); -var i, start, n: I64; -begin - i := 0; start := 0; n := 0; - while i < LEN(f) do - if (f[i] = '{') or (f[i] = '}') then - put(b, f[start..i]); - if (i + 1 < LEN(f)) and (f[i + 1] = f[i]) then - put(b, f[i..i + 1]); - INC(i); - elsif (f[i] = '{') and (i + 1 < LEN(f)) and (f[i + 1] = '}') then - if n < LEN(args) then arg(b, args[n]); end; - INC(n); - INC(i); - end; - start := i + 1; - end; - INC(i); - end; - put(b, f[start..LEN(f)]); -end; - -proc print*(f: []U8; args: []Arg); -begin - format(nil, f, args); -end; - -proc write*(b: ^Buf.Buf; f: []U8; args: []Arg); -begin - format(b, f, args); -end; - -(* The module's test: formats into a buffer over an arena. *) -proc main*; -var ar: Arena.Arena; b: Buf.Buf; -begin - if not Arena.init(ADR(ar), 1 shl 16) then Rt.stop("Fmt: no arena"); end; - Buf.init(ADR(b), ADR(ar.base)); - write(ADR(b), "{} {} {} {}|{}{}{} {{}}", [int(-42), uint(0FFFFFFFFFFFFFFFFH), hex(48879), - str("s"), char('c'), bool(true), int(0)]); - if Buf.bytes(ADR(b)) # "-42 18446744073709551615 BEEF s|ctrue0 {}" then Rt.stop("Fmt.write"); end; - Buf.reset(ADR(b)); - write(ADR(b), "{} and {}", [int(1)]); - if Buf.bytes(ADR(b)) # "1 and " then Rt.stop("Fmt: too few arguments"); end; - Arena.done(ADR(ar)); -end; - -end Fmt. diff --git a/lib/Fmt.raz b/lib/Fmt.raz new file mode 100644 index 0000000..bc8e059 --- /dev/null +++ b/lib/Fmt.raz @@ -0,0 +1,105 @@ +(* Formatted output. Each {} in the format takes the next argument: + Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)]); + {{ and }} stand for { and }. print writes to standard output, + write appends to a Buf. *) +module Fmt; +import Out, Buf, Arena, Rt; + +type + Arg* = variant + int(i: I64); + uint(u: U64); + hex(h: U64); + str(s: []U8); + char(c: U8); + bool(b: BOOL); + end; + +(* The digits of u in base, at the end of the array: it and where they start. *) +proc digits(u: U64; base: U64): ([24]U8, I64); +var d: [24]U8; i: I64; v: U8; +begin + i := 24; + repeat + DEC(i); + v := U8(u mod base); + if v < 10 then d[i] := v + '0'; else d[i] := v - 10 + 'A'; end; + u := u div base; + until u = 0; + return d, i; +end; + +(* Where the pieces go: to b, or to standard output if b is nil. *) +proc put(b: ^Buf.Buf; s: []U8); +begin + if b = nil then Out.str(s); else Buf.str(b, s); end; +end; + +proc arg(b: ^Buf.Buf; a: Arg); +var d: [24]U8; at: I64; one: [1]U8; +begin + match a of + | int(i): + if i < 0 then + put(b, "-"); + d, at := digits(0 - U64(i), 10); + else + d, at := digits(U64(i), 10); + end; + put(b, d[at..24]); + | uint(u): d, at := digits(u, 10); put(b, d[at..24]); + | hex(h): d, at := digits(h, 16); put(b, d[at..24]); + | str(s): put(b, s); + | char(c): one[0] := c; put(b, one); + | bool(t): if t then put(b, "true"); else put(b, "false"); end; + end; +end; + +proc format(b: ^Buf.Buf; f: []U8; args: []Arg); +var i, start, n: I64; +begin + i := 0; start := 0; n := 0; + while i < LEN(f) do + if (f[i] = '{') or (f[i] = '}') then + put(b, f[start..i]); + if (i + 1 < LEN(f)) and (f[i + 1] = f[i]) then + put(b, f[i..i + 1]); + INC(i); + elsif (f[i] = '{') and (i + 1 < LEN(f)) and (f[i + 1] = '}') then + if n < LEN(args) then arg(b, args[n]); end; + INC(n); + INC(i); + end; + start := i + 1; + end; + INC(i); + end; + put(b, f[start..LEN(f)]); +end; + +proc print*(f: []U8; args: []Arg); +begin + format(nil, f, args); +end; + +proc write*(b: ^Buf.Buf; f: []U8; args: []Arg); +begin + format(b, f, args); +end; + +(* The module's test: formats into a buffer over an arena. *) +proc main*; +var ar: Arena.Arena; b: Buf.Buf; +begin + if not Arena.init(ADR(ar), 1 shl 16) then Rt.stop("Fmt: no arena"); end; + Buf.init(ADR(b), ADR(ar.base)); + write(ADR(b), "{} {} {} {}|{}{}{} {{}}", [int(-42), uint(0FFFFFFFFFFFFFFFFH), hex(48879), + str("s"), char('c'), bool(true), int(0)]); + if Buf.bytes(ADR(b)) # "-42 18446744073709551615 BEEF s|ctrue0 {}" then Rt.stop("Fmt.write"); end; + Buf.reset(ADR(b)); + write(ADR(b), "{} and {}", [int(1)]); + if Buf.bytes(ADR(b)) # "1 and " then Rt.stop("Fmt: too few arguments"); end; + Arena.done(ADR(ar)); +end; + +end Fmt. diff --git a/lib/Heap.jed b/lib/Heap.jed deleted file mode 100644 index d51c8e5..0000000 --- a/lib/Heap.jed +++ /dev/null @@ -1,128 +0,0 @@ -(* A general allocator: Heap.heap. Small blocks come in nine sizes, - 16 to 4096 bytes with their header, each with a list of the free - ones; a block bigger than that gets pages of its own. Every block - has a 16-byte header before it: its size class, or minus the size - of its pages for a big one, which start less than a page before it; - then a marker, which says the block is out, - so that freeing it twice, or freeing what the heap never gave out, - stops the program. One lock keeps it whole across threads. *) -module Heap; -import Mem, Lock, Rt; - -const - Classes = 9; - Header = 16; - Refill = 65536; - Largest = 1 shl 46; (* bigger sizes are refused *) - Out = 5A6564426C6F636BH; (* the marker, xor the header's address *) - -type - Block = record next: ^Block; end; - Head = record size, mark: I64; end; - -var - lists: [Classes]^Block; - cur: ^U8; (* where the next new small block comes from *) - left: I64; - lock: Lock.Lock; - std: Mem.Allocator; - heap*: ^Mem.Allocator; - -(* The block p, with size for its header, given out. *) -proc give(p: ^U8; size: I64): ^U8; -var h: ^Head; -begin - h := ^Head(p); - h^.size := size; - h^.mark := Out xor I64(h); - return p + Header; -end; - -(* size bytes aligned to align, or nil: also for a size below zero or - too big, and an alignment that isn't a power of two up to a page. *) -proc alloc(a: ^Mem.Allocator; size, align: I64): ^U8; -var c, n: I64; b: ^Block; p: ^U8; -begin - if (size < 0) or (size > Largest) or (align < 1) or (align > Mem.Page) - or (align and (align - 1) # 0) then - return nil; - end; - n := size + Header; - c := 0; - while (c < Classes) and (16 shl c < n) do INC(c); end; - if (c = Classes) or (align > Header) then - (* pages of its own, the block at align from their start *) - if align < Header then align := Header; end; - n := (size + align + Mem.Page - 1) div Mem.Page * Mem.Page; - p := Mem.pages(n); - if p = nil then return nil; end; - return give(p + align - Header, -n); - end; - Lock.take(ADR(lock)); - defer Lock.give(ADR(lock)); - b := lists[c]; - if b # nil then - lists[c] := b^.next; - p := ^U8(b); - else - if left < 16 shl c then - cur := Mem.pages(Refill); - if cur = nil then left := 0; return nil; end; - left := Refill; - end; - p := cur; - cur := cur + (16 shl c); - left := left - (16 shl c); - end; - return give(p, c); -end; - -proc free(a: ^Mem.Allocator; p: ^U8); -var h: ^Head; b: ^Block; c: I64; -begin - if p = nil then return; end; - h := ^Head(p - Header); - Lock.take(ADR(lock)); - if h^.mark # Out xor I64(h) then - Rt.stop("Heap: a block freed twice, or never given out"); - end; - h^.mark := 0; - if h^.size < 0 then - Lock.give(ADR(lock)); - Mem.unmap(^U8(I64(h) - I64(h) mod Mem.Page), -h^.size); - else - c := h^.size; (* before next, which takes its place, is set *) - b := ^Block(h); - b^.next := lists[c]; - lists[c] := b; - Lock.give(ADR(lock)); - end; -end; - -(* The module's test: blocks of every class and big ones, written, - freed and taken again. *) -proc main*; -var p: [40]^U8; i, j, n: I64; again: ^U8; -begin - for i := 0 to 39 do - n := (i * i * 37) mod 9000 + 1; - p[i] := Mem.alloc(heap, n, 8); - if (p[i] = nil) or (I64(p[i]) mod 8 # 0) then Rt.stop("Heap: alloc"); end; - for j := 0 to n - 1 do p[i][j] := U8(i); end; - end; - for i := 0 to 39 do - n := (i * i * 37) mod 9000 + 1; - if (p[i][0] # U8(i)) or (p[i][n - 1] # U8(i)) then Rt.stop("Heap: overlap"); end; - end; - Mem.free(heap, p[5]); - again := Mem.alloc(heap, (25 * 37) mod 9000 + 1, 8); - if again # p[5] then Rt.stop("Heap: a freed block isn't taken again"); end; - for i := 0 to 39 do Mem.free(heap, p[i]); end; - if Mem.alloc(heap, -1, 8) # nil then Rt.stop("Heap: negative size"); end; - if Mem.alloc(heap, 7FFFFFFFFFFFFFFFH - 4, 8) # nil then Rt.stop("Heap: huge size"); end; -end; - -begin - std := {alloc: alloc, free: free}; - heap := ADR(std); -end Heap. diff --git a/lib/Heap.raz b/lib/Heap.raz new file mode 100644 index 0000000..d51c8e5 --- /dev/null +++ b/lib/Heap.raz @@ -0,0 +1,128 @@ +(* A general allocator: Heap.heap. Small blocks come in nine sizes, + 16 to 4096 bytes with their header, each with a list of the free + ones; a block bigger than that gets pages of its own. Every block + has a 16-byte header before it: its size class, or minus the size + of its pages for a big one, which start less than a page before it; + then a marker, which says the block is out, + so that freeing it twice, or freeing what the heap never gave out, + stops the program. One lock keeps it whole across threads. *) +module Heap; +import Mem, Lock, Rt; + +const + Classes = 9; + Header = 16; + Refill = 65536; + Largest = 1 shl 46; (* bigger sizes are refused *) + Out = 5A6564426C6F636BH; (* the marker, xor the header's address *) + +type + Block = record next: ^Block; end; + Head = record size, mark: I64; end; + +var + lists: [Classes]^Block; + cur: ^U8; (* where the next new small block comes from *) + left: I64; + lock: Lock.Lock; + std: Mem.Allocator; + heap*: ^Mem.Allocator; + +(* The block p, with size for its header, given out. *) +proc give(p: ^U8; size: I64): ^U8; +var h: ^Head; +begin + h := ^Head(p); + h^.size := size; + h^.mark := Out xor I64(h); + return p + Header; +end; + +(* size bytes aligned to align, or nil: also for a size below zero or + too big, and an alignment that isn't a power of two up to a page. *) +proc alloc(a: ^Mem.Allocator; size, align: I64): ^U8; +var c, n: I64; b: ^Block; p: ^U8; +begin + if (size < 0) or (size > Largest) or (align < 1) or (align > Mem.Page) + or (align and (align - 1) # 0) then + return nil; + end; + n := size + Header; + c := 0; + while (c < Classes) and (16 shl c < n) do INC(c); end; + if (c = Classes) or (align > Header) then + (* pages of its own, the block at align from their start *) + if align < Header then align := Header; end; + n := (size + align + Mem.Page - 1) div Mem.Page * Mem.Page; + p := Mem.pages(n); + if p = nil then return nil; end; + return give(p + align - Header, -n); + end; + Lock.take(ADR(lock)); + defer Lock.give(ADR(lock)); + b := lists[c]; + if b # nil then + lists[c] := b^.next; + p := ^U8(b); + else + if left < 16 shl c then + cur := Mem.pages(Refill); + if cur = nil then left := 0; return nil; end; + left := Refill; + end; + p := cur; + cur := cur + (16 shl c); + left := left - (16 shl c); + end; + return give(p, c); +end; + +proc free(a: ^Mem.Allocator; p: ^U8); +var h: ^Head; b: ^Block; c: I64; +begin + if p = nil then return; end; + h := ^Head(p - Header); + Lock.take(ADR(lock)); + if h^.mark # Out xor I64(h) then + Rt.stop("Heap: a block freed twice, or never given out"); + end; + h^.mark := 0; + if h^.size < 0 then + Lock.give(ADR(lock)); + Mem.unmap(^U8(I64(h) - I64(h) mod Mem.Page), -h^.size); + else + c := h^.size; (* before next, which takes its place, is set *) + b := ^Block(h); + b^.next := lists[c]; + lists[c] := b; + Lock.give(ADR(lock)); + end; +end; + +(* The module's test: blocks of every class and big ones, written, + freed and taken again. *) +proc main*; +var p: [40]^U8; i, j, n: I64; again: ^U8; +begin + for i := 0 to 39 do + n := (i * i * 37) mod 9000 + 1; + p[i] := Mem.alloc(heap, n, 8); + if (p[i] = nil) or (I64(p[i]) mod 8 # 0) then Rt.stop("Heap: alloc"); end; + for j := 0 to n - 1 do p[i][j] := U8(i); end; + end; + for i := 0 to 39 do + n := (i * i * 37) mod 9000 + 1; + if (p[i][0] # U8(i)) or (p[i][n - 1] # U8(i)) then Rt.stop("Heap: overlap"); end; + end; + Mem.free(heap, p[5]); + again := Mem.alloc(heap, (25 * 37) mod 9000 + 1, 8); + if again # p[5] then Rt.stop("Heap: a freed block isn't taken again"); end; + for i := 0 to 39 do Mem.free(heap, p[i]); end; + if Mem.alloc(heap, -1, 8) # nil then Rt.stop("Heap: negative size"); end; + if Mem.alloc(heap, 7FFFFFFFFFFFFFFFH - 4, 8) # nil then Rt.stop("Heap: huge size"); end; +end; + +begin + std := {alloc: alloc, free: free}; + heap := ADR(std); +end Heap. diff --git a/lib/List.jed b/lib/List.jed deleted file mode 100644 index 13eeef2..0000000 --- a/lib/List.jed +++ /dev/null @@ -1,68 +0,0 @@ -(* A singly linked list of T, its nodes from an allocator. *) -module List(T); -import Mem; - -type - Node* = record - next*: ^Node; - val*: T; - end; - List* = record - head*: ^Node; - len*: I64; - a: ^Mem.Allocator; - end; - -proc init*(l: ^List; a: ^Mem.Allocator); -begin - l^ := {a: a}; -end; - -(* v at the front; false if the allocator has no room. *) -proc push*(l: ^List; v: T): BOOL; -var n: ^Node; -begin - NEW(n, l^.a); - if n = nil then return false; end; - n^.val := v; - n^.next := l^.head; - l^.head := n; - INC(l^.len); - return true; -end; - -(* The front value, taken off; false if the list is empty. *) -proc pop*(l: ^List): (T, BOOL); -var n: ^Node; v: T; -begin - n := l^.head; - if n = nil then return v, false; end; - v := n^.val; - l^.head := n^.next; - DEC(l^.len); - Mem.free(l^.a, ^U8(n)); - return v, true; -end; - -(* The list backwards. *) -proc reverse*(l: ^List); -var p, q, next: ^Node; -begin - p := l^.head; - q := nil; - while p # nil do - next := p^.next; - p^.next := q; - q := p; - p := next; - end; - l^.head := q; -end; - -proc clear*(l: ^List); -var ok: BOOL; v: T; -begin - while l^.head # nil do v, ok := pop(l); end; -end; - -end List. diff --git a/lib/List.raz b/lib/List.raz new file mode 100644 index 0000000..13eeef2 --- /dev/null +++ b/lib/List.raz @@ -0,0 +1,68 @@ +(* A singly linked list of T, its nodes from an allocator. *) +module List(T); +import Mem; + +type + Node* = record + next*: ^Node; + val*: T; + end; + List* = record + head*: ^Node; + len*: I64; + a: ^Mem.Allocator; + end; + +proc init*(l: ^List; a: ^Mem.Allocator); +begin + l^ := {a: a}; +end; + +(* v at the front; false if the allocator has no room. *) +proc push*(l: ^List; v: T): BOOL; +var n: ^Node; +begin + NEW(n, l^.a); + if n = nil then return false; end; + n^.val := v; + n^.next := l^.head; + l^.head := n; + INC(l^.len); + return true; +end; + +(* The front value, taken off; false if the list is empty. *) +proc pop*(l: ^List): (T, BOOL); +var n: ^Node; v: T; +begin + n := l^.head; + if n = nil then return v, false; end; + v := n^.val; + l^.head := n^.next; + DEC(l^.len); + Mem.free(l^.a, ^U8(n)); + return v, true; +end; + +(* The list backwards. *) +proc reverse*(l: ^List); +var p, q, next: ^Node; +begin + p := l^.head; + q := nil; + while p # nil do + next := p^.next; + p^.next := q; + q := p; + p := next; + end; + l^.head := q; +end; + +proc clear*(l: ^List); +var ok: BOOL; v: T; +begin + while l^.head # nil do v, ok := pop(l); end; +end; + +end List. diff --git a/lib/Lock.jed b/lib/Lock.jed deleted file mode 100644 index cbb1179..0000000 --- a/lib/Lock.jed +++ /dev/null @@ -1,37 +0,0 @@ -(* A lock for short sections of code: a word set to 1, atomically, by - the thread that takes it. A thread that finds it taken tries again, - giving up the processor now and then. It works with C's threads and - with Thread's alike; Thread.Mutex is the one that sleeps. *) -module Lock; -import Sys, Rt; - -type Lock* = record held: I64; end; - -proc take*(l: ^Lock); -var tries: I64; -begin - tries := 0; - while not CAS(ADR(l^.held), 0, 1) do - INC(tries); - if tries = 64 then Sys.yield; tries := 0; end; - end; -end; - -proc give*(l: ^Lock); -begin - XCHG(ADR(l^.held), 0); -end; - -(* The module's test, in one thread: taken, given, taken again. *) -proc main*; -var l: Lock; -begin - take(ADR(l)); - if l.held # 1 then Rt.stop("Lock.take"); end; - give(ADR(l)); - take(ADR(l)); - give(ADR(l)); - if l.held # 0 then Rt.stop("Lock.give"); end; -end; - -end Lock. diff --git a/lib/Lock.raz b/lib/Lock.raz new file mode 100644 index 0000000..cbb1179 --- /dev/null +++ b/lib/Lock.raz @@ -0,0 +1,37 @@ +(* A lock for short sections of code: a word set to 1, atomically, by + the thread that takes it. A thread that finds it taken tries again, + giving up the processor now and then. It works with C's threads and + with Thread's alike; Thread.Mutex is the one that sleeps. *) +module Lock; +import Sys, Rt; + +type Lock* = record held: I64; end; + +proc take*(l: ^Lock); +var tries: I64; +begin + tries := 0; + while not CAS(ADR(l^.held), 0, 1) do + INC(tries); + if tries = 64 then Sys.yield; tries := 0; end; + end; +end; + +proc give*(l: ^Lock); +begin + XCHG(ADR(l^.held), 0); +end; + +(* The module's test, in one thread: taken, given, taken again. *) +proc main*; +var l: Lock; +begin + take(ADR(l)); + if l.held # 1 then Rt.stop("Lock.take"); end; + give(ADR(l)); + take(ADR(l)); + give(ADR(l)); + if l.held # 0 then Rt.stop("Lock.give"); end; +end; + +end Lock. diff --git a/lib/Map.jed b/lib/Map.jed deleted file mode 100644 index 746d7af..0000000 --- a/lib/Map.jed +++ /dev/null @@ -1,81 +0,0 @@ -(* A hash map from K to V, by open addressing; it hashes and compares - keys with the procedures it is given: - import Count := Map([]U8, I64, Str.hash, Str.eq); *) -module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL); -import Mem; - -type - Entry = record - key: K; - val: V; - used: BOOL; - end; - Map* = record - a: ^Mem.Allocator; - slots: ^Entry; - cap: I64; (* a power of two, or 0 *) - len*: I64; - end; - -proc init*(m: ^Map; a: ^Mem.Allocator); -begin - m^ := {a: a}; -end; - -(* The slot of k, or of the empty slot where it would go. *) -proc slot(m: ^Map; k: K): I64; -var i: I64; -begin - i := I64(hash(k) and U64(m^.cap - 1)); - while m^.slots[i].used and not eq(m^.slots[i].key, k) do - i := (i + 1) and (m^.cap - 1); - end; - return i; -end; - -proc grow(m: ^Map): BOOL; -var old: ^Entry; n, i, j: I64; -begin - old := m^.slots; - n := m^.cap; - if n = 0 then m^.cap := 16; else m^.cap := n * 2; end; - m^.slots := ^Entry(Mem.alloc(m^.a, m^.cap * SIZE(Entry), 8)); - if m^.slots = nil then m^.slots := old; m^.cap := n; return false; end; - for i := 0 to m^.cap - 1 do m^.slots[i].used := false; end; - for i := 0 to n - 1 do - if old[i].used then - j := slot(m, old[i].key); - m^.slots[j] := old[i]; - end; - end; - if old # nil then Mem.free(m^.a, ^U8(old)); end; - return true; -end; - -(* k now maps to v; false if there was no room. *) -proc put*(m: ^Map; k: K; v: V): BOOL; -var i: I64; -begin - if (m^.len + 1) * 4 > m^.cap * 3 then - if not grow(m) then return false; end; - end; - i := slot(m, k); - if not m^.slots[i].used then - m^.slots[i] := {key: k, used: true}; - INC(m^.len); - end; - m^.slots[i].val := v; - return true; -end; - -(* What k maps to, and whether it maps to anything. *) -proc get*(m: ^Map; k: K): (V, BOOL); -var i: I64; none: V; -begin - if m^.cap = 0 then return none, false; end; - i := slot(m, k); - if not m^.slots[i].used then return none, false; end; - return m^.slots[i].val, true; -end; - -end Map. diff --git a/lib/Map.raz b/lib/Map.raz new file mode 100644 index 0000000..746d7af --- /dev/null +++ b/lib/Map.raz @@ -0,0 +1,81 @@ +(* A hash map from K to V, by open addressing; it hashes and compares + keys with the procedures it is given: + import Count := Map([]U8, I64, Str.hash, Str.eq); *) +module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL); +import Mem; + +type + Entry = record + key: K; + val: V; + used: BOOL; + end; + Map* = record + a: ^Mem.Allocator; + slots: ^Entry; + cap: I64; (* a power of two, or 0 *) + len*: I64; + end; + +proc init*(m: ^Map; a: ^Mem.Allocator); +begin + m^ := {a: a}; +end; + +(* The slot of k, or of the empty slot where it would go. *) +proc slot(m: ^Map; k: K): I64; +var i: I64; +begin + i := I64(hash(k) and U64(m^.cap - 1)); + while m^.slots[i].used and not eq(m^.slots[i].key, k) do + i := (i + 1) and (m^.cap - 1); + end; + return i; +end; + +proc grow(m: ^Map): BOOL; +var old: ^Entry; n, i, j: I64; +begin + old := m^.slots; + n := m^.cap; + if n = 0 then m^.cap := 16; else m^.cap := n * 2; end; + m^.slots := ^Entry(Mem.alloc(m^.a, m^.cap * SIZE(Entry), 8)); + if m^.slots = nil then m^.slots := old; m^.cap := n; return false; end; + for i := 0 to m^.cap - 1 do m^.slots[i].used := false; end; + for i := 0 to n - 1 do + if old[i].used then + j := slot(m, old[i].key); + m^.slots[j] := old[i]; + end; + end; + if old # nil then Mem.free(m^.a, ^U8(old)); end; + return true; +end; + +(* k now maps to v; false if there was no room. *) +proc put*(m: ^Map; k: K; v: V): BOOL; +var i: I64; +begin + if (m^.len + 1) * 4 > m^.cap * 3 then + if not grow(m) then return false; end; + end; + i := slot(m, k); + if not m^.slots[i].used then + m^.slots[i] := {key: k, used: true}; + INC(m^.len); + end; + m^.slots[i].val := v; + return true; +end; + +(* What k maps to, and whether it maps to anything. *) +proc get*(m: ^Map; k: K): (V, BOOL); +var i: I64; none: V; +begin + if m^.cap = 0 then return none, false; end; + i := slot(m, k); + if not m^.slots[i].used then return none, false; end; + return m^.slots[i].val, true; +end; + +end Map. diff --git a/lib/Mem.jed b/lib/Mem.jed deleted file mode 100644 index 55ceb3c..0000000 --- a/lib/Mem.jed +++ /dev/null @@ -1,48 +0,0 @@ -(* Memory: Allocator, the interface every allocator offers, and pages - from the system. NEW(p, a) calls a^.alloc. *) -module Mem; -import Sys, Rt; - -type - Allocator* = record - alloc*: proc(a: ^Allocator; size, align: I64): ^U8; (* nil if out of room *) - free*: proc(a: ^Allocator; p: ^U8); - end; - -const Page* = 4096; - -(* size bytes, rounded up to whole pages, zeroed; or nil. *) -proc pages*(size: I64): ^U8; -begin - return Sys.mmap((size + Page - 1) div Page * Page); -end; - -proc unmap*(p: ^U8; size: I64); -begin - Sys.munmap(p, (size + Page - 1) div Page * Page); -end; - -proc alloc*(a: ^Allocator; size, align: I64): ^U8; -begin - return a^.alloc(a, size, align); -end; - -proc free*(a: ^Allocator; p: ^U8); -begin - a^.free(a, p); -end; - -(* The module's test. *) -proc main*; -var p: ^U8; i: I64; -begin - p := pages(10000); - if p = nil then Rt.stop("Mem.pages"); end; - for i := 0 to 12287 do - if p[i] # 0 then Rt.stop("Mem.pages: not zeroed"); end; - end; - p[12287] := 1; - unmap(p, 10000); -end; - -end Mem. diff --git a/lib/Mem.raz b/lib/Mem.raz new file mode 100644 index 0000000..55ceb3c --- /dev/null +++ b/lib/Mem.raz @@ -0,0 +1,48 @@ +(* Memory: Allocator, the interface every allocator offers, and pages + from the system. NEW(p, a) calls a^.alloc. *) +module Mem; +import Sys, Rt; + +type + Allocator* = record + alloc*: proc(a: ^Allocator; size, align: I64): ^U8; (* nil if out of room *) + free*: proc(a: ^Allocator; p: ^U8); + end; + +const Page* = 4096; + +(* size bytes, rounded up to whole pages, zeroed; or nil. *) +proc pages*(size: I64): ^U8; +begin + return Sys.mmap((size + Page - 1) div Page * Page); +end; + +proc unmap*(p: ^U8; size: I64); +begin + Sys.munmap(p, (size + Page - 1) div Page * Page); +end; + +proc alloc*(a: ^Allocator; size, align: I64): ^U8; +begin + return a^.alloc(a, size, align); +end; + +proc free*(a: ^Allocator; p: ^U8); +begin + a^.free(a, p); +end; + +(* The module's test. *) +proc main*; +var p: ^U8; i: I64; +begin + p := pages(10000); + if p = nil then Rt.stop("Mem.pages"); end; + for i := 0 to 12287 do + if p[i] # 0 then Rt.stop("Mem.pages: not zeroed"); end; + end; + p[12287] := 1; + unmap(p, 10000); +end; + +end Mem. diff --git a/lib/Out.jed b/lib/Out.jed deleted file mode 100644 index 5597fec..0000000 --- a/lib/Out.jed +++ /dev/null @@ -1,100 +0,0 @@ -(* Writing text and numbers to standard output, through a buffer of - 4 KB. The buffer is written out when it is full, at each line feed - when standard output is a terminal, by flush, and when the program - ends by Rt.exit. C's stdio keeps a buffer of its own: a program that - writes with both flushes one before writing with the other. A lock - keeps what each call writes together when threads write at once. *) -module Out; -import Rt, Sys, Lock; - -var - buf: [4096]U8; - n: I64; (* bytes in buf *) - tty: BOOL; (* standard output is a terminal *) - lock: Lock.Lock; - -(* Writes out the buffer, with the lock held. What can't be written is - dropped. *) -proc out; -var i, k: I64; -begin - i := 0; - while i < n do - k := Sys.write(Sys.stdout, buf[i..n]); - if k > 0 then i := i + k; - elsif k # -4 then break; (* -EINTR: try again *) - end; - end; - n := 0; -end; - -proc flush*; -begin - Lock.take(ADR(lock)); - out; - Lock.give(ADR(lock)); -end; - -proc str*(s: []U8); -var i: I64; -begin - Lock.take(ADR(lock)); - for i := 0 to LEN(s) - 1 do - if n = LEN(buf) then out; end; - buf[n] := s[i]; - INC(n); - if (s[i] = '\n') and tty then out; end; - end; - Lock.give(ADR(lock)); -end; - -proc char*(c: U8); -var b: [1]U8; -begin - b[0] := c; - str(b); -end; - -proc ln*; -begin - char('\n'); -end; - -(* n in decimal *) -proc int*(n: I64); -var buf: [20]U8; i: I64; u: U64; -begin - u := U64(n); - if n < 0 then u := 0 - u; end; - i := 20; - repeat - i := i - 1; - buf[i] := U8(u mod 10) + '0'; - u := u div 10; - until u = 0; - if n < 0 then - i := i - 1; - buf[i] := '-'; - end; - str(buf[i..20]); -end; - -(* n in hexadecimal, digits digits at least *) -proc hex*(n: U64; digits: I64); -var buf: [16]U8; i: I64; d: U8; -begin - i := 16; - repeat - i := i - 1; - d := U8(n and 15); - if d < 10 then buf[i] := d + '0'; else buf[i] := d - 10 + 'A'; end; - n := n shr 4; - digits := digits - 1; - until (n = 0) and (digits <= 0) or (i = 0); - str(buf[i..16]); -end; - -begin - tty := Sys.isTerminal(Sys.stdout); - Rt.atExit(flush); -end Out. diff --git a/lib/Out.raz b/lib/Out.raz new file mode 100644 index 0000000..5597fec --- /dev/null +++ b/lib/Out.raz @@ -0,0 +1,100 @@ +(* Writing text and numbers to standard output, through a buffer of + 4 KB. The buffer is written out when it is full, at each line feed + when standard output is a terminal, by flush, and when the program + ends by Rt.exit. C's stdio keeps a buffer of its own: a program that + writes with both flushes one before writing with the other. A lock + keeps what each call writes together when threads write at once. *) +module Out; +import Rt, Sys, Lock; + +var + buf: [4096]U8; + n: I64; (* bytes in buf *) + tty: BOOL; (* standard output is a terminal *) + lock: Lock.Lock; + +(* Writes out the buffer, with the lock held. What can't be written is + dropped. *) +proc out; +var i, k: I64; +begin + i := 0; + while i < n do + k := Sys.write(Sys.stdout, buf[i..n]); + if k > 0 then i := i + k; + elsif k # -4 then break; (* -EINTR: try again *) + end; + end; + n := 0; +end; + +proc flush*; +begin + Lock.take(ADR(lock)); + out; + Lock.give(ADR(lock)); +end; + +proc str*(s: []U8); +var i: I64; +begin + Lock.take(ADR(lock)); + for i := 0 to LEN(s) - 1 do + if n = LEN(buf) then out; end; + buf[n] := s[i]; + INC(n); + if (s[i] = '\n') and tty then out; end; + end; + Lock.give(ADR(lock)); +end; + +proc char*(c: U8); +var b: [1]U8; +begin + b[0] := c; + str(b); +end; + +proc ln*; +begin + char('\n'); +end; + +(* n in decimal *) +proc int*(n: I64); +var buf: [20]U8; i: I64; u: U64; +begin + u := U64(n); + if n < 0 then u := 0 - u; end; + i := 20; + repeat + i := i - 1; + buf[i] := U8(u mod 10) + '0'; + u := u div 10; + until u = 0; + if n < 0 then + i := i - 1; + buf[i] := '-'; + end; + str(buf[i..20]); +end; + +(* n in hexadecimal, digits digits at least *) +proc hex*(n: U64; digits: I64); +var buf: [16]U8; i: I64; d: U8; +begin + i := 16; + repeat + i := i - 1; + d := U8(n and 15); + if d < 10 then buf[i] := d + '0'; else buf[i] := d - 10 + 'A'; end; + n := n shr 4; + digits := digits - 1; + until (n = 0) and (digits <= 0) or (i = 0); + str(buf[i..16]); +end; + +begin + tty := Sys.isTerminal(Sys.stdout); + Rt.atExit(flush); +end Out. diff --git a/lib/Rt.jed b/lib/Rt.jed deleted file mode 100644 index e68abd5..0000000 --- a/lib/Rt.jed +++ /dev/null @@ -1,83 +0,0 @@ -(* The run time: ending the program, and what the compiler's code - calls: fail when a check fails, eq when = or # compares two strings; - and stop, for the library's own failures. - The compiler finds fail, eq, exit and cExit by these names. *) -module Rt; -import Sys; - -const - Full*: ERROR = "too many procedures to run at exit"; - MaxAtExit = 32; - -var - atExits: [MaxAtExit]proc; - numAtExit: I64; - cExit: proc(status: I32); (* C's exit, set first thing in a program that uses C *) - -(* Registers p to run when the program ends by exit. *) -proc atExit*(p: proc): ERROR; -begin - if numAtExit = MaxAtExit then return Full; end; - atExits[numAtExit] := p; - INC(numAtExit); - return nil; -end; - -(* Runs the procedures registered with atExit, the last first, then - ends the program with status: through C's exit in a program that - uses C, so that C flushes its buffers too. Each procedure is taken - off the list before it runs, so it runs once even if it fails or - calls exit itself. *) -proc exit*(status: I64); -var p: proc; -begin - while numAtExit > 0 do - DEC(numAtExit); - p := atExits[numAtExit]; - p(); - end; - if cExit # nil then cExit(I32(status)); end; - Sys.exit(status); -end; - -(* Stops the program: says msg on standard error, then ends it by exit - with status 2, as a failed check does. *) -proc stop*(msg: []U8); -begin - Sys.write(Sys.stderr, msg); - Sys.write(Sys.stderr, "\n"); - exit(2); -end; - -(* A check failed at line of file: says so on standard error and ends - the program with status 2. *) -proc fail*(file: ^U8; line: I64); -var buf: [20]U8; i, n: I64; -begin - n := 0; - while file[n] # 0 do n := n + 1; end; - Sys.write(Sys.stderr, file[0..n]); - i := 20; - repeat - i := i - 1; - buf[i] := U8(line mod 10) + '0'; - line := line div 10; - until line = 0; - i := i - 1; - buf[i] := ':'; - Sys.write(Sys.stderr, buf[i..20]); - Sys.write(Sys.stderr, ": index out of range\n"); - exit(2); -end; - -proc eq*(a, b: []U8): BOOL; -var i: I64; -begin - if LEN(a) # LEN(b) then return false; end; - for i := 0 to LEN(a) - 1 do - if a[i] # b[i] then return false; end; - end; - return true; -end; - -end Rt. diff --git a/lib/Rt.raz b/lib/Rt.raz new file mode 100644 index 0000000..e68abd5 --- /dev/null +++ b/lib/Rt.raz @@ -0,0 +1,83 @@ +(* The run time: ending the program, and what the compiler's code + calls: fail when a check fails, eq when = or # compares two strings; + and stop, for the library's own failures. + The compiler finds fail, eq, exit and cExit by these names. *) +module Rt; +import Sys; + +const + Full*: ERROR = "too many procedures to run at exit"; + MaxAtExit = 32; + +var + atExits: [MaxAtExit]proc; + numAtExit: I64; + cExit: proc(status: I32); (* C's exit, set first thing in a program that uses C *) + +(* Registers p to run when the program ends by exit. *) +proc atExit*(p: proc): ERROR; +begin + if numAtExit = MaxAtExit then return Full; end; + atExits[numAtExit] := p; + INC(numAtExit); + return nil; +end; + +(* Runs the procedures registered with atExit, the last first, then + ends the program with status: through C's exit in a program that + uses C, so that C flushes its buffers too. Each procedure is taken + off the list before it runs, so it runs once even if it fails or + calls exit itself. *) +proc exit*(status: I64); +var p: proc; +begin + while numAtExit > 0 do + DEC(numAtExit); + p := atExits[numAtExit]; + p(); + end; + if cExit # nil then cExit(I32(status)); end; + Sys.exit(status); +end; + +(* Stops the program: says msg on standard error, then ends it by exit + with status 2, as a failed check does. *) +proc stop*(msg: []U8); +begin + Sys.write(Sys.stderr, msg); + Sys.write(Sys.stderr, "\n"); + exit(2); +end; + +(* A check failed at line of file: says so on standard error and ends + the program with status 2. *) +proc fail*(file: ^U8; line: I64); +var buf: [20]U8; i, n: I64; +begin + n := 0; + while file[n] # 0 do n := n + 1; end; + Sys.write(Sys.stderr, file[0..n]); + i := 20; + repeat + i := i - 1; + buf[i] := U8(line mod 10) + '0'; + line := line div 10; + until line = 0; + i := i - 1; + buf[i] := ':'; + Sys.write(Sys.stderr, buf[i..20]); + Sys.write(Sys.stderr, ": index out of range\n"); + exit(2); +end; + +proc eq*(a, b: []U8): BOOL; +var i: I64; +begin + if LEN(a) # LEN(b) then return false; end; + for i := 0 to LEN(a) - 1 do + if a[i] # b[i] then return false; end; + end; + return true; +end; + +end Rt. diff --git a/lib/Str.jed b/lib/Str.jed deleted file mode 100644 index 7519b07..0000000 --- a/lib/Str.jed +++ /dev/null @@ -1,66 +0,0 @@ -(* Operations on strings, which are []U8. = and # compare them; this - module orders, searches and hashes them. *) -module Str; -import Rt; - -(* -1, 0 or 1 as a sorts before, with or after b, byte by byte. *) -proc cmp*(a, b: []U8): I64; -var i, n: I64; -begin - n := LEN(a); - if LEN(b) < n then n := LEN(b); end; - for i := 0 to n - 1 do - if a[i] # b[i] then - if a[i] < b[i] then return -1; end; - return 1; - end; - end; - if LEN(a) < LEN(b) then return -1; end; - if LEN(a) > LEN(b) then return 1; end; - return 0; -end; - -proc eq*(a, b: []U8): BOOL; -begin - return a = b; -end; - -(* FNV-1a, 64 bits. *) -proc hash*(s: []U8): U64; -var h: U64; i: I64; -begin - h := 0CBF29CE484222325H; - for i := 0 to LEN(s) - 1 do - h := (h xor U64(s[i])) * 100000001B3H; - end; - return h; -end; - -(* Where sub first starts in s, or -1. *) -proc find*(s, sub: []U8): I64; -var i: I64; -begin - for i := 0 to LEN(s) - LEN(sub) do - if s[i..i + LEN(sub)] = sub then return i; end; - end; - return -1; -end; - -proc hasPrefix*(s, p: []U8): BOOL; -begin - return (LEN(s) >= LEN(p)) and (s[0..LEN(p)] = p); -end; - -(* The module's test: stops the program if something is wrong. *) -proc main*; -begin - if (cmp("a", "b") # -1) or (cmp("b", "a") # 1) or (cmp("ab", "ab") # 0) - or (cmp("a", "ab") # -1) or (cmp("", "") # 0) then Rt.stop("Str.cmp"); end; - if not eq("x", "x") or eq("x", "y") then Rt.stop("Str.eq"); end; - if (hash("") # 0CBF29CE484222325H) or (hash("a") # 0AF63DC4C8601EC8CH) then Rt.stop("Str.hash"); end; - if (find("hello", "ll") # 2) or (find("hello", "x") # -1) or (find("", "") # 0) - or (find("ab", "abc") # -1) then Rt.stop("Str.find"); end; - if not hasPrefix("hello", "he") or hasPrefix("he", "hello") then Rt.stop("Str.hasPrefix"); end; -end; - -end Str. diff --git a/lib/Str.raz b/lib/Str.raz new file mode 100644 index 0000000..7519b07 --- /dev/null +++ b/lib/Str.raz @@ -0,0 +1,66 @@ +(* Operations on strings, which are []U8. = and # compare them; this + module orders, searches and hashes them. *) +module Str; +import Rt; + +(* -1, 0 or 1 as a sorts before, with or after b, byte by byte. *) +proc cmp*(a, b: []U8): I64; +var i, n: I64; +begin + n := LEN(a); + if LEN(b) < n then n := LEN(b); end; + for i := 0 to n - 1 do + if a[i] # b[i] then + if a[i] < b[i] then return -1; end; + return 1; + end; + end; + if LEN(a) < LEN(b) then return -1; end; + if LEN(a) > LEN(b) then return 1; end; + return 0; +end; + +proc eq*(a, b: []U8): BOOL; +begin + return a = b; +end; + +(* FNV-1a, 64 bits. *) +proc hash*(s: []U8): U64; +var h: U64; i: I64; +begin + h := 0CBF29CE484222325H; + for i := 0 to LEN(s) - 1 do + h := (h xor U64(s[i])) * 100000001B3H; + end; + return h; +end; + +(* Where sub first starts in s, or -1. *) +proc find*(s, sub: []U8): I64; +var i: I64; +begin + for i := 0 to LEN(s) - LEN(sub) do + if s[i..i + LEN(sub)] = sub then return i; end; + end; + return -1; +end; + +proc hasPrefix*(s, p: []U8): BOOL; +begin + return (LEN(s) >= LEN(p)) and (s[0..LEN(p)] = p); +end; + +(* The module's test: stops the program if something is wrong. *) +proc main*; +begin + if (cmp("a", "b") # -1) or (cmp("b", "a") # 1) or (cmp("ab", "ab") # 0) + or (cmp("a", "ab") # -1) or (cmp("", "") # 0) then Rt.stop("Str.cmp"); end; + if not eq("x", "x") or eq("x", "y") then Rt.stop("Str.eq"); end; + if (hash("") # 0CBF29CE484222325H) or (hash("a") # 0AF63DC4C8601EC8CH) then Rt.stop("Str.hash"); end; + if (find("hello", "ll") # 2) or (find("hello", "x") # -1) or (find("", "") # 0) + or (find("ab", "abc") # -1) then Rt.stop("Str.find"); end; + if not hasPrefix("hello", "he") or hasPrefix("he", "hello") then Rt.stop("Str.hasPrefix"); end; +end; + +end Str. diff --git a/lib/Sys.jed b/lib/Sys.jed deleted file mode 100644 index 2d40230..0000000 --- a/lib/Sys.jed +++ /dev/null @@ -1,130 +0,0 @@ -(* System calls through the C library: Sys for the targets that have no - file of their own, with the same exports. A program that imports it - uses C. *) -module Sys; -import C; - -const - stdin* = 0; - stdout* = 1; - stderr* = 2; - -(* minus errno, as a system call returns it *) -proc failed: I64; -var e: ^I32; -begin - e := C.__errno_location(); - return -I64(e^); -end; - -(* Writes s to the file descriptor fd; the number of bytes written, or - minus an errno. *) -proc write*(fd: I64; s: []U8): I64; -var r: I64; -begin - if LEN(s) = 0 then return 0; end; - r := C.write(I32(fd), ADR(s[0]), U64(LEN(s))); - if r < 0 then return failed(); end; - return r; -end; - -(* Reads into buf from fd; the number of bytes read, 0 at the end, or - minus an errno. *) -proc read*(fd: I64; buf: []U8): I64; -var r: I64; -begin - if LEN(buf) = 0 then return 0; end; - r := C.read(I32(fd), ADR(buf[0]), U64(LEN(buf))); - if r < 0 then return failed(); end; - return r; -end; - -(* path, a C string in buf, or false if it doesn't fit. *) -proc cstr(path: []U8; var buf: [4096]U8): BOOL; -var i: I64; -begin - if LEN(path) >= LEN(buf) then return false; end; - for i := 0 to LEN(path) - 1 do buf[i] := path[i]; end; - buf[LEN(path)] := 0; - return true; -end; - -(* The file at path, opened for reading: its file descriptor, or minus - an errno. *) -proc openRead*(path: []U8): I64; -var buf: [4096]U8; r: I64; -begin - if not cstr(path, buf) then return -36; end; - r := I64(C.open(ADR(buf[0]), 0)); (* O_RDONLY is 0 everywhere *) - if r < 0 then return failed(); end; - return r; -end; - -(* The file at path, made empty or new, opened for writing, readable by - all: its file descriptor, or minus an errno. *) -proc create*(path: []U8): I64; -var buf: [4096]U8; r: I64; -begin - if not cstr(path, buf) then return -36; end; - r := I64(C.creat(ADR(buf[0]), 420)); (* mode 644 *) - if r < 0 then return failed(); end; - return r; -end; - -proc close*(fd: I64); -begin - C.close(I32(fd)); -end; - -(* size bytes of fresh, zeroed memory from the system, a multiple of - pages, or nil. *) -proc mmap*(size: I64): ^U8; -var p: ^U8; -begin - p := C.mmap(nil, U64(size), 3, 22H, -1, 0); (* read, write; private, anonymous *) - if I64(p) = -1 then return nil; end; - return p; -end; - -proc munmap*(p: ^U8; size: I64); -begin - C.munmap(p, U64(size)); -end; - -proc isTerminal*(fd: I64): BOOL; -begin - return C.isatty(I32(fd)) = 1; -end; - -proc yield*; -begin - C.sched_yield(); -end; - -(* Ends the program, at once, with status. *) -proc exit*(status: I64); -begin - C._exit(I32(status)); -end; - -(* The module's test: a file written, read back and closed. *) -proc main*; -var fd, n: I64; buf: [16]U8; p: ^U8; -begin - fd := create("/tmp/jed-sys-test"); - if fd < 0 then exit(2); end; - if write(fd, "hello") # 5 then exit(2); end; - close(fd); - fd := openRead("/tmp/jed-sys-test"); - if fd < 0 then exit(2); end; - n := read(fd, buf); - if (n # 5) or (buf[0..5] # "hello") or (read(fd, buf) # 0) then exit(2); end; - close(fd); - if openRead("/no/such/file") >= 0 then exit(2); end; - if isTerminal(-1) then exit(2); end; - p := mmap(100); - if (p = nil) or (p[99] # 0) then exit(2); end; - munmap(p, 100); -end; - -end Sys. diff --git a/lib/Sys.linux-x86_64.jed b/lib/Sys.linux-x86_64.jed deleted file mode 100644 index 7e707e8..0000000 --- a/lib/Sys.linux-x86_64.jed +++ /dev/null @@ -1,114 +0,0 @@ -(* System calls on Linux for x86-64. Other targets supply their own - Sys, with the same exports. *) -module Sys; - -const - stdin* = 0; - stdout* = 1; - stderr* = 2; - -(* Writes s to the file descriptor fd; the number of bytes written, or - minus an errno. *) -proc write*(fd: I64; s: []U8): I64; -begin - if LEN(s) = 0 then return 0; end; - return SYSCALL(1, fd, ADR(s[0]), LEN(s)); -end; - -(* Reads into buf from fd; the number of bytes read, 0 at the end, or - minus an errno. *) -proc read*(fd: I64; buf: []U8): I64; -begin - if LEN(buf) = 0 then return 0; end; - return SYSCALL(0, fd, ADR(buf[0]), LEN(buf)); -end; - -(* path, a C string in buf, or false if it doesn't fit. *) -proc cstr(path: []U8; var buf: [4096]U8): BOOL; -var i: I64; -begin - if LEN(path) >= LEN(buf) then return false; end; - for i := 0 to LEN(path) - 1 do buf[i] := path[i]; end; - buf[LEN(path)] := 0; - return true; -end; - -(* The file at path, opened for reading: its file descriptor, or minus - an errno. *) -proc openRead*(path: []U8): I64; -var buf: [4096]U8; -begin - if not cstr(path, buf) then return -36; end; (* ENAMETOOLONG *) - return SYSCALL(2, ADR(buf), 0); (* open, O_RDONLY *) -end; - -(* The file at path, made empty or new, opened for writing, readable by - all: its file descriptor, or minus an errno. *) -proc create*(path: []U8): I64; -var buf: [4096]U8; -begin - if not cstr(path, buf) then return -36; end; - return SYSCALL(85, ADR(buf), 420); (* creat, mode 644 *) -end; - -proc close*(fd: I64); -begin - SYSCALL(3, fd); -end; - -(* size bytes of fresh, zeroed memory from the system, a multiple of - pages, or nil. *) -proc mmap*(size: I64): ^U8; -var p: I64; -begin - p := SYSCALL(9, 0, size, 3, 22H, -1, 0); (* read, write; private, anonymous *) - if p < 0 then return nil; end; - return ^U8(p); -end; - -proc munmap*(p: ^U8; size: I64); -begin - SYSCALL(11, p, size); -end; - -(* Whether the file descriptor fd is a terminal: whether it has a - terminal's settings to read (ioctl TCGETS). *) -proc isTerminal*(fd: I64): BOOL; -var t: [8]I64; (* struct termios: 60 bytes *) -begin - return SYSCALL(16, fd, 5401H, ADR(t)) = 0; -end; - -(* Gives the processor to another thread. *) -proc yield*; -begin - SYSCALL(24); -end; - -(* Ends the program, at once, with status. *) -proc exit*(status: I64); -begin - SYSCALL(231, status); -end; - -(* The module's test: a file written, read back and closed. *) -proc main*; -var fd, n: I64; buf: [16]U8; p: ^U8; -begin - fd := create("/tmp/jed-sys-test"); - if fd < 0 then exit(2); end; - if write(fd, "hello") # 5 then exit(2); end; - close(fd); - fd := openRead("/tmp/jed-sys-test"); - if fd < 0 then exit(2); end; - n := read(fd, buf); - if (n # 5) or (buf[0..5] # "hello") or (read(fd, buf) # 0) then exit(2); end; - close(fd); - if openRead("/no/such/file") >= 0 then exit(2); end; - if isTerminal(-1) then exit(2); end; - p := mmap(100); - if (p = nil) or (p[99] # 0) then exit(2); end; - munmap(p, 100); -end; - -end Sys. diff --git a/lib/Sys.linux-x86_64.raz b/lib/Sys.linux-x86_64.raz new file mode 100644 index 0000000..5f9b3ef --- /dev/null +++ b/lib/Sys.linux-x86_64.raz @@ -0,0 +1,114 @@ +(* System calls on Linux for x86-64. Other targets supply their own + Sys, with the same exports. *) +module Sys; + +const + stdin* = 0; + stdout* = 1; + stderr* = 2; + +(* Writes s to the file descriptor fd; the number of bytes written, or + minus an errno. *) +proc write*(fd: I64; s: []U8): I64; +begin + if LEN(s) = 0 then return 0; end; + return SYSCALL(1, fd, ADR(s[0]), LEN(s)); +end; + +(* Reads into buf from fd; the number of bytes read, 0 at the end, or + minus an errno. *) +proc read*(fd: I64; buf: []U8): I64; +begin + if LEN(buf) = 0 then return 0; end; + return SYSCALL(0, fd, ADR(buf[0]), LEN(buf)); +end; + +(* path, a C string in buf, or false if it doesn't fit. *) +proc cstr(path: []U8; var buf: [4096]U8): BOOL; +var i: I64; +begin + if LEN(path) >= LEN(buf) then return false; end; + for i := 0 to LEN(path) - 1 do buf[i] := path[i]; end; + buf[LEN(path)] := 0; + return true; +end; + +(* The file at path, opened for reading: its file descriptor, or minus + an errno. *) +proc openRead*(path: []U8): I64; +var buf: [4096]U8; +begin + if not cstr(path, buf) then return -36; end; (* ENAMETOOLONG *) + return SYSCALL(2, ADR(buf), 0); (* open, O_RDONLY *) +end; + +(* The file at path, made empty or new, opened for writing, readable by + all: its file descriptor, or minus an errno. *) +proc create*(path: []U8): I64; +var buf: [4096]U8; +begin + if not cstr(path, buf) then return -36; end; + return SYSCALL(85, ADR(buf), 420); (* creat, mode 644 *) +end; + +proc close*(fd: I64); +begin + SYSCALL(3, fd); +end; + +(* size bytes of fresh, zeroed memory from the system, a multiple of + pages, or nil. *) +proc mmap*(size: I64): ^U8; +var p: I64; +begin + p := SYSCALL(9, 0, size, 3, 22H, -1, 0); (* read, write; private, anonymous *) + if p < 0 then return nil; end; + return ^U8(p); +end; + +proc munmap*(p: ^U8; size: I64); +begin + SYSCALL(11, p, size); +end; + +(* Whether the file descriptor fd is a terminal: whether it has a + terminal's settings to read (ioctl TCGETS). *) +proc isTerminal*(fd: I64): BOOL; +var t: [8]I64; (* struct termios: 60 bytes *) +begin + return SYSCALL(16, fd, 5401H, ADR(t)) = 0; +end; + +(* Gives the processor to another thread. *) +proc yield*; +begin + SYSCALL(24); +end; + +(* Ends the program, at once, with status. *) +proc exit*(status: I64); +begin + SYSCALL(231, status); +end; + +(* The module's test: a file written, read back and closed. *) +proc main*; +var fd, n: I64; buf: [16]U8; p: ^U8; +begin + fd := create("/tmp/raz-sys-test"); + if fd < 0 then exit(2); end; + if write(fd, "hello") # 5 then exit(2); end; + close(fd); + fd := openRead("/tmp/raz-sys-test"); + if fd < 0 then exit(2); end; + n := read(fd, buf); + if (n # 5) or (buf[0..5] # "hello") or (read(fd, buf) # 0) then exit(2); end; + close(fd); + if openRead("/no/such/file") >= 0 then exit(2); end; + if isTerminal(-1) then exit(2); end; + p := mmap(100); + if (p = nil) or (p[99] # 0) then exit(2); end; + munmap(p, 100); +end; + +end Sys. diff --git a/lib/Sys.raz b/lib/Sys.raz new file mode 100644 index 0000000..5c3438a --- /dev/null +++ b/lib/Sys.raz @@ -0,0 +1,130 @@ +(* System calls through the C library: Sys for the targets that have no + file of their own, with the same exports. A program that imports it + uses C. *) +module Sys; +import C; + +const + stdin* = 0; + stdout* = 1; + stderr* = 2; + +(* minus errno, as a system call returns it *) +proc failed: I64; +var e: ^I32; +begin + e := C.__errno_location(); + return -I64(e^); +end; + +(* Writes s to the file descriptor fd; the number of bytes written, or + minus an errno. *) +proc write*(fd: I64; s: []U8): I64; +var r: I64; +begin + if LEN(s) = 0 then return 0; end; + r := C.write(I32(fd), ADR(s[0]), U64(LEN(s))); + if r < 0 then return failed(); end; + return r; +end; + +(* Reads into buf from fd; the number of bytes read, 0 at the end, or + minus an errno. *) +proc read*(fd: I64; buf: []U8): I64; +var r: I64; +begin + if LEN(buf) = 0 then return 0; end; + r := C.read(I32(fd), ADR(buf[0]), U64(LEN(buf))); + if r < 0 then return failed(); end; + return r; +end; + +(* path, a C string in buf, or false if it doesn't fit. *) +proc cstr(path: []U8; var buf: [4096]U8): BOOL; +var i: I64; +begin + if LEN(path) >= LEN(buf) then return false; end; + for i := 0 to LEN(path) - 1 do buf[i] := path[i]; end; + buf[LEN(path)] := 0; + return true; +end; + +(* The file at path, opened for reading: its file descriptor, or minus + an errno. *) +proc openRead*(path: []U8): I64; +var buf: [4096]U8; r: I64; +begin + if not cstr(path, buf) then return -36; end; + r := I64(C.open(ADR(buf[0]), 0)); (* O_RDONLY is 0 everywhere *) + if r < 0 then return failed(); end; + return r; +end; + +(* The file at path, made empty or new, opened for writing, readable by + all: its file descriptor, or minus an errno. *) +proc create*(path: []U8): I64; +var buf: [4096]U8; r: I64; +begin + if not cstr(path, buf) then return -36; end; + r := I64(C.creat(ADR(buf[0]), 420)); (* mode 644 *) + if r < 0 then return failed(); end; + return r; +end; + +proc close*(fd: I64); +begin + C.close(I32(fd)); +end; + +(* size bytes of fresh, zeroed memory from the system, a multiple of + pages, or nil. *) +proc mmap*(size: I64): ^U8; +var p: ^U8; +begin + p := C.mmap(nil, U64(size), 3, 22H, -1, 0); (* read, write; private, anonymous *) + if I64(p) = -1 then return nil; end; + return p; +end; + +proc munmap*(p: ^U8; size: I64); +begin + C.munmap(p, U64(size)); +end; + +proc isTerminal*(fd: I64): BOOL; +begin + return C.isatty(I32(fd)) = 1; +end; + +proc yield*; +begin + C.sched_yield(); +end; + +(* Ends the program, at once, with status. *) +proc exit*(status: I64); +begin + C._exit(I32(status)); +end; + +(* The module's test: a file written, read back and closed. *) +proc main*; +var fd, n: I64; buf: [16]U8; p: ^U8; +begin + fd := create("/tmp/raz-sys-test"); + if fd < 0 then exit(2); end; + if write(fd, "hello") # 5 then exit(2); end; + close(fd); + fd := openRead("/tmp/raz-sys-test"); + if fd < 0 then exit(2); end; + n := read(fd, buf); + if (n # 5) or (buf[0..5] # "hello") or (read(fd, buf) # 0) then exit(2); end; + close(fd); + if openRead("/no/such/file") >= 0 then exit(2); end; + if isTerminal(-1) then exit(2); end; + p := mmap(100); + if (p = nil) or (p[99] # 0) then exit(2); end; + munmap(p, 100); +end; + +end Sys. diff --git a/lib/Thread.linux-x86_64.jed b/lib/Thread.linux-x86_64.jed deleted file mode 100644 index d9fdc57..0000000 --- a/lib/Thread.linux-x86_64.jed +++ /dev/null @@ -1,178 +0,0 @@ -(* Threads for programs without C, made with the clone system call. - Each runs on a stack of its own, mmaped, with a page below it that - can't be touched, so that running off the stack stops the program - rather than spoiling what lies below. join waits on the thread's id, - which the kernel clears, and wakes it for, when the thread ends; - a Mutex sleeps on a futex. A program with C threads uses C's, - through pthread_create, and so can't use these. *) -module Thread; -import Sys, Rt; -link static; - -const - Failed*: ERROR = "can't start a thread"; - Stack = 1 shl 20; - Page = 4096; - (* clone: share memory, files, signal handlers, the thread group; - write the id to tid, and clear it at the end *) - Flags = 350F00H; - FutexWait = 0; - FutexWake = 1; - Private = 128; - -type - Thread* = record - tid: I64; (* the kernel's id, until the thread ends *) - base: ^U8; (* its stack's mapping, the guard page first *) - size: I64; - end; - (* 0 free, 1 taken, 2 taken with a thread waiting *) - Mutex* = record state: I64; end; - -(* clone(flags, stack, tid, tid), the new thread starting with fn(arg) - on stack and ending, when fn returns, with the exit system call. - fn and arg go on the new stack first, since the new thread has no - registers but rsp of its own to find them by. Returns the new - thread's id, or minus an errno. *) -proc start(flags: I64; stack: ^U8; ptid, ctid: ^I64; fn: proc(arg: ^U8); arg: ^U8): I64; -code 48H, 83H, 0EEH, 10H, (* sub rsi, 16 *) - 4CH, 89H, 06H, (* mov [rsi], r8 *) - 4CH, 89H, 4EH, 08H, (* mov [rsi + 8], r9 *) - 49H, 89H, 0CAH, (* mov r10, rcx *) - 45H, 31H, 0C0H, (* xor r8d, r8d: no tls *) - 0B8H, 38H, 0, 0, 0, (* mov eax, 56: clone *) - 0FH, 05H, (* syscall *) - 48H, 85H, 0C0H, (* test rax, rax *) - 75H, 0DH, (* jnz parent *) - 58H, (* pop rax: fn *) - 5FH, (* pop rdi: arg *) - 0FFH, 0D0H, (* call rax *) - 31H, 0FFH, (* xor edi, edi *) - 0B8H, 3CH, 0, 0, 0, (* mov eax, 60: exit, this thread only *) - 0FH, 05H, (* syscall *) - 0C3H; (* parent: ret *) - -proc futex(word: ^I64; op, val: I64): I64; -begin - return SYSCALL(202, word, op, val, 0); -end; - -(* Starts p(arg) in a new thread. *) -proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR); -var base: ^U8; t: ^Thread; size: I64; -begin - size := Stack + Page; - base := Sys.mmap(size); - if base = nil then return nil, Failed; end; - (* mprotect: the guard page, no access; it fails when the process - has as many mappings as it may *) - if SYSCALL(10, base, Page, 0) < 0 then - Sys.munmap(base, size); - return nil, Failed; - end; - (* the Thread at the top, the stack below it, aligned to 16 *) - t := ^Thread(base + size - 32); - t^.base := base; - t^.size := size; - if start(Flags, base + size - 32, ADR(t^.tid), ADR(t^.tid), p, arg) < 0 then - Sys.munmap(base, size); - return nil, Failed; - end; - return t, nil; -end; - -(* Waits for t to end, then frees its stack. *) -proc join*(t: ^Thread); -var tid: ^VOLATILE I64; v: I64; base: ^U8; size: I64; -begin - tid := ADR(t^.tid); - v := tid^; - while v # 0 do - futex(ADR(t^.tid), FutexWait, v); - v := tid^; - end; - base := t^.base; - size := t^.size; - Sys.munmap(base, size); -end; - -proc lock*(m: ^Mutex); -var c: I64; -begin - if CAS(ADR(m^.state), 0, 1) then return; end; - c := XCHG(ADR(m^.state), 2); - while c # 0 do - futex(ADR(m^.state), FutexWait + Private, 2); - c := XCHG(ADR(m^.state), 2); - end; -end; - -proc unlock*(m: ^Mutex); -begin - if XADD(ADR(m^.state), -1) # 1 then - XCHG(ADR(m^.state), 0); - futex(ADR(m^.state), FutexWake + Private, 1); - end; -end; - -(* The module's test, and make stress's. It starts n threads, in waves - of up to alive at a time, all waiting on one Mutex the test holds - until the wave is out; each, given it, adds one to a count. Every - thread is joined, so that a stack join didn't free would, over - enough of them, run the process out of mappings. With "fail", it - starts threads, all waiting, until spawn fails, which it must do - with Failed: make stress and make check run it with little memory. - Thread [n alive], Thread fail *) -var - testLock: Mutex; - testCount: I64; - wave: [1000]^Thread; - -proc testWork(arg: ^U8); -begin - lock(ADR(testLock)); - INC(testCount); - unlock(ADR(testLock)); -end; - -proc testArg(i: I64): I64; -var s: ^U8; n, v: I64; -begin - s := ARGV()[i]; - v := 0; - n := 0; - while s[n] # 0 do v := v * 10 + I64(s[n]) - '0'; INC(n); end; - return v; -end; - -proc main*; -var n, alive, started, k, i: I64; t: ^Thread; err: ERROR; fail: BOOL; -begin - n := 2000; alive := 50; - fail := (ARGC() = 2) and (ARGV()[1][0] = 'f'); - if ARGC() = 3 then n := testArg(1); alive := testArg(2); end; - if fail then n := LEN(wave); alive := LEN(wave); end; - if (alive < 1) or (alive > LEN(wave)) then Rt.stop("Thread: alive is 1 to 1000"); end; - started := 0; - while started < n do - lock(ADR(testLock)); - k := 0; - while (k < alive) and (started + k < n) do - t, err := spawn(testWork, nil); - if err # nil then - if not fail or (err # Failed) then Rt.stop("Thread.spawn failed"); end; - n := started + k; - break; - end; - wave[k] := t; - INC(k); - end; - unlock(ADR(testLock)); - for i := 0 to k - 1 do join(wave[i]); end; - started := started + k; - end; - if testCount # started then Rt.stop("Thread: a thread didn't run"); end; - if fail and (started = LEN(wave)) then Rt.stop("Thread: spawn never failed"); end; -end; - -end Thread. diff --git a/lib/Thread.linux-x86_64.raz b/lib/Thread.linux-x86_64.raz new file mode 100644 index 0000000..d9fdc57 --- /dev/null +++ b/lib/Thread.linux-x86_64.raz @@ -0,0 +1,178 @@ +(* Threads for programs without C, made with the clone system call. + Each runs on a stack of its own, mmaped, with a page below it that + can't be touched, so that running off the stack stops the program + rather than spoiling what lies below. join waits on the thread's id, + which the kernel clears, and wakes it for, when the thread ends; + a Mutex sleeps on a futex. A program with C threads uses C's, + through pthread_create, and so can't use these. *) +module Thread; +import Sys, Rt; +link static; + +const + Failed*: ERROR = "can't start a thread"; + Stack = 1 shl 20; + Page = 4096; + (* clone: share memory, files, signal handlers, the thread group; + write the id to tid, and clear it at the end *) + Flags = 350F00H; + FutexWait = 0; + FutexWake = 1; + Private = 128; + +type + Thread* = record + tid: I64; (* the kernel's id, until the thread ends *) + base: ^U8; (* its stack's mapping, the guard page first *) + size: I64; + end; + (* 0 free, 1 taken, 2 taken with a thread waiting *) + Mutex* = record state: I64; end; + +(* clone(flags, stack, tid, tid), the new thread starting with fn(arg) + on stack and ending, when fn returns, with the exit system call. + fn and arg go on the new stack first, since the new thread has no + registers but rsp of its own to find them by. Returns the new + thread's id, or minus an errno. *) +proc start(flags: I64; stack: ^U8; ptid, ctid: ^I64; fn: proc(arg: ^U8); arg: ^U8): I64; +code 48H, 83H, 0EEH, 10H, (* sub rsi, 16 *) + 4CH, 89H, 06H, (* mov [rsi], r8 *) + 4CH, 89H, 4EH, 08H, (* mov [rsi + 8], r9 *) + 49H, 89H, 0CAH, (* mov r10, rcx *) + 45H, 31H, 0C0H, (* xor r8d, r8d: no tls *) + 0B8H, 38H, 0, 0, 0, (* mov eax, 56: clone *) + 0FH, 05H, (* syscall *) + 48H, 85H, 0C0H, (* test rax, rax *) + 75H, 0DH, (* jnz parent *) + 58H, (* pop rax: fn *) + 5FH, (* pop rdi: arg *) + 0FFH, 0D0H, (* call rax *) + 31H, 0FFH, (* xor edi, edi *) + 0B8H, 3CH, 0, 0, 0, (* mov eax, 60: exit, this thread only *) + 0FH, 05H, (* syscall *) + 0C3H; (* parent: ret *) + +proc futex(word: ^I64; op, val: I64): I64; +begin + return SYSCALL(202, word, op, val, 0); +end; + +(* Starts p(arg) in a new thread. *) +proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR); +var base: ^U8; t: ^Thread; size: I64; +begin + size := Stack + Page; + base := Sys.mmap(size); + if base = nil then return nil, Failed; end; + (* mprotect: the guard page, no access; it fails when the process + has as many mappings as it may *) + if SYSCALL(10, base, Page, 0) < 0 then + Sys.munmap(base, size); + return nil, Failed; + end; + (* the Thread at the top, the stack below it, aligned to 16 *) + t := ^Thread(base + size - 32); + t^.base := base; + t^.size := size; + if start(Flags, base + size - 32, ADR(t^.tid), ADR(t^.tid), p, arg) < 0 then + Sys.munmap(base, size); + return nil, Failed; + end; + return t, nil; +end; + +(* Waits for t to end, then frees its stack. *) +proc join*(t: ^Thread); +var tid: ^VOLATILE I64; v: I64; base: ^U8; size: I64; +begin + tid := ADR(t^.tid); + v := tid^; + while v # 0 do + futex(ADR(t^.tid), FutexWait, v); + v := tid^; + end; + base := t^.base; + size := t^.size; + Sys.munmap(base, size); +end; + +proc lock*(m: ^Mutex); +var c: I64; +begin + if CAS(ADR(m^.state), 0, 1) then return; end; + c := XCHG(ADR(m^.state), 2); + while c # 0 do + futex(ADR(m^.state), FutexWait + Private, 2); + c := XCHG(ADR(m^.state), 2); + end; +end; + +proc unlock*(m: ^Mutex); +begin + if XADD(ADR(m^.state), -1) # 1 then + XCHG(ADR(m^.state), 0); + futex(ADR(m^.state), FutexWake + Private, 1); + end; +end; + +(* The module's test, and make stress's. It starts n threads, in waves + of up to alive at a time, all waiting on one Mutex the test holds + until the wave is out; each, given it, adds one to a count. Every + thread is joined, so that a stack join didn't free would, over + enough of them, run the process out of mappings. With "fail", it + starts threads, all waiting, until spawn fails, which it must do + with Failed: make stress and make check run it with little memory. + Thread [n alive], Thread fail *) +var + testLock: Mutex; + testCount: I64; + wave: [1000]^Thread; + +proc testWork(arg: ^U8); +begin + lock(ADR(testLock)); + INC(testCount); + unlock(ADR(testLock)); +end; + +proc testArg(i: I64): I64; +var s: ^U8; n, v: I64; +begin + s := ARGV()[i]; + v := 0; + n := 0; + while s[n] # 0 do v := v * 10 + I64(s[n]) - '0'; INC(n); end; + return v; +end; + +proc main*; +var n, alive, started, k, i: I64; t: ^Thread; err: ERROR; fail: BOOL; +begin + n := 2000; alive := 50; + fail := (ARGC() = 2) and (ARGV()[1][0] = 'f'); + if ARGC() = 3 then n := testArg(1); alive := testArg(2); end; + if fail then n := LEN(wave); alive := LEN(wave); end; + if (alive < 1) or (alive > LEN(wave)) then Rt.stop("Thread: alive is 1 to 1000"); end; + started := 0; + while started < n do + lock(ADR(testLock)); + k := 0; + while (k < alive) and (started + k < n) do + t, err := spawn(testWork, nil); + if err # nil then + if not fail or (err # Failed) then Rt.stop("Thread.spawn failed"); end; + n := started + k; + break; + end; + wave[k] := t; + INC(k); + end; + unlock(ADR(testLock)); + for i := 0 to k - 1 do join(wave[i]); end; + started := started + k; + end; + if testCount # started then Rt.stop("Thread: a thread didn't run"); end; + if fail and (started = LEN(wave)) then Rt.stop("Thread: spawn never failed"); end; +end; + +end Thread. diff --git a/src/elf.pas b/src/elf.pas index 6a375e4..dfdbd33 100644 --- a/src/elf.pas +++ b/src/elf.pas @@ -195,7 +195,7 @@ PutStr(mainPath); if FpGetcwd(@cwd, SizeOf(cwd)) = nil then cwd[0] := #0; PutStr(PChar(@cwd)); - PutStr('jed'); + PutStr('raz'); PutN(0, 4); { the line table, at 0 } PutN(Base + textOff, 8); PutN(textSize, 8); { the code, all of it } Patch(off[1], len - off[1] - 4, 4); diff --git a/src/jed.pas b/src/jed.pas deleted file mode 100644 index 7115843..0000000 --- a/src/jed.pas +++ /dev/null @@ -1,214 +0,0 @@ -{ jed.pas: the command line. - - jed [-I dir]... [-o file] Main.jed - jed run [-I dir]... Main.jed [arg]... - jed --version - - Compiles the main module and every module it imports, writes the - entry point, links what it reaches, and writes the executable: by - default the main module's file without its .jed. jed run writes it - to a memfd instead, a file that lives only in memory, and executes - it in jed's place with the arguments after Main.jed, so its status - is the program's; its argv[0] is Main.jed. - - The program starts by saving argc and argv, runs every module's body - (those of the modules the program imports, imported modules first), - then the main module's main, and ends with Rt.exit and main's - status. A static program does this from its entry point. One that - uses C starts through the C library, __libc_start_main, which sets - C up and calls this as C's main; first it gives Rt C's exit, which - Rt.exit then ends the program with. - - Depends on: everything else. } - -program jed; - -{$mode objfpc}{$H-} - -uses math, BaseUnix, syscall, scan, sym, x64, gen, parse, link, elf; - -const - Version = '0.3.0'; - Report = '2026-10.0'; { the version of doc/jed.md it follows } - MemfdCreate = 319; { the system call; FPC 3.2.2 has no name for it } - MfdCloexec = 1; { an ELF still executes: the kernel opens it first } - -{ The modules the program uses: the main module, Rt, and every module - they import. A module read only for the interface check is not. } -procedure Use(m: PModule); -var i: PImport; -begin - if m^.used then exit; - m^.used := true; - i := m^.imports; - while i <> nil do begin - Use(i^.module); - i := i^.next; - end; -end; - -{ Whether the program uses C: if so, the libraries it needs go to - elf.pas, the C library first. } -function UsesC: boolean; -var m, st, c: PModule; l: PLib; i: longint; seen: boolean; -begin - st := nil; c := nil; - numNeeded := 1; - needed[0] := Intern(PChar('libc.so.6'), 9); - m := firstModule; - while m <> nil do begin - if m^.used and m^.linkStatic then st := m; - if m^.used and m^.usesC then c := m; - l := m^.libs; - while m^.used and (l <> nil) do begin - seen := false; - for i := 0 to numNeeded - 1 do seen := seen or (needed[i] = l^.name); - if not seen then begin - if numNeeded > High(needed) then Fatal('too many libraries'); - needed[numNeeded] := l^.name; - inc(numNeeded); - end; - l := l^.next; - end; - m := m^.next; - end; - if (st <> nil) and (c <> nil) then - Fatal(NameOf(st^.name) + ' says link static, but ' + NameOf(c^.name) + ' uses C'); - if c = nil then numNeeded := 0; - UsesC := c <> nil; -end; - -function RtObj(rt: PModule; const n: shortstring): PObj; -var o: PObj; -begin - o := Find(rt^.scope, Intern(@n[1], length(n))); - if o = nil then Fatal('Rt has no ' + n); - RtObj := o; -end; - -var - path, outPath, dir, s: shortstring; - i, first, entry, start, fd: longint; - m, rt: PModule; - main: PObj; - hasResult, dynamic, run: boolean; - -begin - { constants fold as the machine computes: NaN and infinities, no traps } - SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, exUnderflow, exPrecision]); - path := ''; - outPath := ''; - numInc := 0; - run := (ParamCount >= 1) and (ParamStr(1) = 'run'); - i := 1 + ord(run); - while i <= ParamCount do begin - s := ParamStr(i); - if s = '-I' then begin - inc(i); - if numInc > High(incDirs) then Fatal('too many -I'); - incDirs[numInc] := ParamStr(i); - inc(numInc); - end else if s = '-o' then begin - inc(i); - outPath := ParamStr(i); - end else if s = '--version' then begin - writeln('jed ', Version, ', report ', Report); - Halt(0); - end else if (s <> '') and (s[1] = '-') then - Fatal('unknown option ' + s) - else begin - path := s; - first := i; - if run then break; { the rest are the program's } - end; - inc(i); - end; - if path = '' then - Fatal('usage: jed [-I dir]... [-o file] Main.jed, or jed run [-I dir]... Main.jed [arg]...'); - if run and (outPath <> '') then Fatal('jed run takes no -o'); - dir := ParamStr(0); - i := length(dir); - while (i > 0) and (dir[i] <> '/') do dec(i); - if i = 0 then libDir := 'lib' else libDir := copy(dir, 1, i) + 'lib'; - if outPath = '' then begin - outPath := path; - if copy(outPath, length(outPath) - 3, 4) = '.jed' then - outPath := copy(outPath, 1, length(outPath) - 4) - else outPath := outPath + '.out'; - end; - - m := CompileMain(path); - - Use(m); - rt := firstModule; - while (rt <> nil) and (NameOf(rt^.name) <> 'Rt') do rt := rt^.next; - if rt <> nil then Use(rt); - - main := Find(m^.scope, Intern('main', 4)); - hasResult := false; - if main <> nil then begin - if (main^.cls <> oProc) or not main^.exported then Fatal('main must be an exported procedure'); - if (main^.typ^.len <> 0) or ((main^.typ^.base <> nil) and (main^.typ^.base <> tI64)) then - Fatal('main must be proc main* or proc main*: I64'); - hasResult := main^.typ^.base <> nil; - end; - - if rt = nil then Fatal('can''t find module Rt'); - dynamic := UsesC; - entry := NewChunk(secText, -1, Intern('_start', 6)); - if dynamic then begin - { _start as C's crt1 does it: __libc_start_main(main, argc, argv, - nil, nil, rtld_fini, stack_end), with rsp aligned } - start := NewChunk(secText, -1, Intern('main', 4)); - BeginChunk(entry); - MovRI(RBP, 0); - MovRR(R9, RDX); - Pop(RSI); - MovRR(RDX, RSP); - AluI(aluAnd, RSP, -16); - Push(RAX); - Push(RSP); - MovRI(R8, 0); - MovRI(RCX, 0); - Lea(RDI, MemRip(start, 0)); - CallM(MemRip(ExternChunk(Intern('__libc_start_main', 17)), 0)); - Ud2; - EndChunk(entry); - BeginChunk(start); - Push(RBP); { aligns the stack again } - Store(MemRip(argcChunk, 0), RDI, 8); - Store(MemRip(argvChunk, 0), RSI, 8); - Load(RAX, MemRip(ExternChunk(Intern('exit', 4)), 0), 8, false); - Store(MemRip(RtObj(rt, 'cExit')^.chunk, 0), RAX, 8); - end else begin - start := entry; - BeginChunk(entry); - Load(RAX, Mem(RSP, 0), 8, false); - Store(MemRip(argcChunk, 0), RAX, 8); - Lea(RAX, Mem(RSP, 8)); - Store(MemRip(argvChunk, 0), RAX, 8); - end; - m := firstModule; - while m <> nil do begin - if m^.used and (m^.body >= 0) then CallChunk(m^.body); - m := m^.next; - end; - if main <> nil then CallChunk(main^.chunk); - if hasResult then MovRR(RDI, RAX) else MovRI(RDI, 0); - CallChunk(RtObj(rt, 'exit')^.chunk); - Ud2; - EndChunk(start); - - mainPath := path; - if run then begin - { argv from Main.jed on is the program's, ending in nil as it must } - fd := Do_SysCall(MemfdCreate, TSysParam(PChar('jed')), MfdCloexec); - if fd < 0 then Fatal('can''t create a memfd'); - Str(fd, s); - outPath := '/proc/self/fd/' + s + #0; - WriteElf(outPath, entry); - FpExecve(@outPath[1], @argv[first], envp); - Fatal('can''t run ' + path); - end; - WriteElf(outPath, entry); -end. diff --git a/src/parse.pas b/src/parse.pas index 32194cd..041029d 100644 --- a/src/parse.pas +++ b/src/parse.pas @@ -6,7 +6,7 @@ each comes after the modules it imports; that is the order in which their bodies run. - A module may come in one file per target (Name.linux-x86_64.jed and + A module may come in one file per target (Name.linux-x86_64.raz and so on). The file for this target is compiled; the others beside it are read for their declarations only, and must export the same interface. @@ -1741,7 +1741,7 @@ inc(i); end; if (copy(f, 1, length(prefix)) = prefix) and (length(f) > 4) - and (copy(f, length(f) - 3, 4) = '.jed') and (f <> chosen) + and (copy(f, length(f) - 3, 4) = '.raz') and (f <> chosen) and (numOthers <= High(others)) then begin others[numOthers] := f; inc(numOthers); @@ -1765,7 +1765,7 @@ else if i = numInc then dir := libDir else dir := incDirs[i]; for j := 0 to 3 do begin - f := NameOf(name) + Suffixes[j] + '.jed'; + f := NameOf(name) + Suffixes[j] + '.raz'; if Exists(dir + '/' + f) then begin m := CompileFile(dir + '/' + f, name, args, false); CheckSiblings(dir, f, name, m, args); diff --git a/src/raz.pas b/src/raz.pas new file mode 100644 index 0000000..db2a8a7 --- /dev/null +++ b/src/raz.pas @@ -0,0 +1,214 @@ +{ raz.pas: the command line. + + raz [-I dir]... [-o file] Main.raz + raz run [-I dir]... Main.raz [arg]... + raz --version + + Compiles the main module and every module it imports, writes the + entry point, links what it reaches, and writes the executable: by + default the main module's file without its .raz. raz run writes it + to a memfd instead, a file that lives only in memory, and executes + it in raz's place with the arguments after Main.raz, so its status + is the program's; its argv[0] is Main.raz. + + The program starts by saving argc and argv, runs every module's body + (those of the modules the program imports, imported modules first), + then the main module's main, and ends with Rt.exit and main's + status. A static program does this from its entry point. One that + uses C starts through the C library, __libc_start_main, which sets + C up and calls this as C's main; first it gives Rt C's exit, which + Rt.exit then ends the program with. + + Depends on: everything else. } + +program raz; + +{$mode objfpc}{$H-} + +uses math, BaseUnix, syscall, scan, sym, x64, gen, parse, link, elf; + +const + Version = '0.3.0'; + Report = '2026-10.0'; { the version of doc/raz.md it follows } + MemfdCreate = 319; { the system call; FPC 3.2.2 has no name for it } + MfdCloexec = 1; { an ELF still executes: the kernel opens it first } + +{ The modules the program uses: the main module, Rt, and every module + they import. A module read only for the interface check is not. } +procedure Use(m: PModule); +var i: PImport; +begin + if m^.used then exit; + m^.used := true; + i := m^.imports; + while i <> nil do begin + Use(i^.module); + i := i^.next; + end; +end; + +{ Whether the program uses C: if so, the libraries it needs go to + elf.pas, the C library first. } +function UsesC: boolean; +var m, st, c: PModule; l: PLib; i: longint; seen: boolean; +begin + st := nil; c := nil; + numNeeded := 1; + needed[0] := Intern(PChar('libc.so.6'), 9); + m := firstModule; + while m <> nil do begin + if m^.used and m^.linkStatic then st := m; + if m^.used and m^.usesC then c := m; + l := m^.libs; + while m^.used and (l <> nil) do begin + seen := false; + for i := 0 to numNeeded - 1 do seen := seen or (needed[i] = l^.name); + if not seen then begin + if numNeeded > High(needed) then Fatal('too many libraries'); + needed[numNeeded] := l^.name; + inc(numNeeded); + end; + l := l^.next; + end; + m := m^.next; + end; + if (st <> nil) and (c <> nil) then + Fatal(NameOf(st^.name) + ' says link static, but ' + NameOf(c^.name) + ' uses C'); + if c = nil then numNeeded := 0; + UsesC := c <> nil; +end; + +function RtObj(rt: PModule; const n: shortstring): PObj; +var o: PObj; +begin + o := Find(rt^.scope, Intern(@n[1], length(n))); + if o = nil then Fatal('Rt has no ' + n); + RtObj := o; +end; + +var + path, outPath, dir, s: shortstring; + i, first, entry, start, fd: longint; + m, rt: PModule; + main: PObj; + hasResult, dynamic, run: boolean; + +begin + { constants fold as the machine computes: NaN and infinities, no traps } + SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, exUnderflow, exPrecision]); + path := ''; + outPath := ''; + numInc := 0; + run := (ParamCount >= 1) and (ParamStr(1) = 'run'); + i := 1 + ord(run); + while i <= ParamCount do begin + s := ParamStr(i); + if s = '-I' then begin + inc(i); + if numInc > High(incDirs) then Fatal('too many -I'); + incDirs[numInc] := ParamStr(i); + inc(numInc); + end else if s = '-o' then begin + inc(i); + outPath := ParamStr(i); + end else if s = '--version' then begin + writeln('raz ', Version, ', report ', Report); + Halt(0); + end else if (s <> '') and (s[1] = '-') then + Fatal('unknown option ' + s) + else begin + path := s; + first := i; + if run then break; { the rest are the program's } + end; + inc(i); + end; + if path = '' then + Fatal('usage: raz [-I dir]... [-o file] Main.raz, or raz run [-I dir]... Main.raz [arg]...'); + if run and (outPath <> '') then Fatal('raz run takes no -o'); + dir := ParamStr(0); + i := length(dir); + while (i > 0) and (dir[i] <> '/') do dec(i); + if i = 0 then libDir := 'lib' else libDir := copy(dir, 1, i) + 'lib'; + if outPath = '' then begin + outPath := path; + if copy(outPath, length(outPath) - 3, 4) = '.raz' then + outPath := copy(outPath, 1, length(outPath) - 4) + else outPath := outPath + '.out'; + end; + + m := CompileMain(path); + + Use(m); + rt := firstModule; + while (rt <> nil) and (NameOf(rt^.name) <> 'Rt') do rt := rt^.next; + if rt <> nil then Use(rt); + + main := Find(m^.scope, Intern('main', 4)); + hasResult := false; + if main <> nil then begin + if (main^.cls <> oProc) or not main^.exported then Fatal('main must be an exported procedure'); + if (main^.typ^.len <> 0) or ((main^.typ^.base <> nil) and (main^.typ^.base <> tI64)) then + Fatal('main must be proc main* or proc main*: I64'); + hasResult := main^.typ^.base <> nil; + end; + + if rt = nil then Fatal('can''t find module Rt'); + dynamic := UsesC; + entry := NewChunk(secText, -1, Intern('_start', 6)); + if dynamic then begin + { _start as C's crt1 does it: __libc_start_main(main, argc, argv, + nil, nil, rtld_fini, stack_end), with rsp aligned } + start := NewChunk(secText, -1, Intern('main', 4)); + BeginChunk(entry); + MovRI(RBP, 0); + MovRR(R9, RDX); + Pop(RSI); + MovRR(RDX, RSP); + AluI(aluAnd, RSP, -16); + Push(RAX); + Push(RSP); + MovRI(R8, 0); + MovRI(RCX, 0); + Lea(RDI, MemRip(start, 0)); + CallM(MemRip(ExternChunk(Intern('__libc_start_main', 17)), 0)); + Ud2; + EndChunk(entry); + BeginChunk(start); + Push(RBP); { aligns the stack again } + Store(MemRip(argcChunk, 0), RDI, 8); + Store(MemRip(argvChunk, 0), RSI, 8); + Load(RAX, MemRip(ExternChunk(Intern('exit', 4)), 0), 8, false); + Store(MemRip(RtObj(rt, 'cExit')^.chunk, 0), RAX, 8); + end else begin + start := entry; + BeginChunk(entry); + Load(RAX, Mem(RSP, 0), 8, false); + Store(MemRip(argcChunk, 0), RAX, 8); + Lea(RAX, Mem(RSP, 8)); + Store(MemRip(argvChunk, 0), RAX, 8); + end; + m := firstModule; + while m <> nil do begin + if m^.used and (m^.body >= 0) then CallChunk(m^.body); + m := m^.next; + end; + if main <> nil then CallChunk(main^.chunk); + if hasResult then MovRR(RDI, RAX) else MovRI(RDI, 0); + CallChunk(RtObj(rt, 'exit')^.chunk); + Ud2; + EndChunk(start); + + mainPath := path; + if run then begin + { argv from Main.raz on is the program's, ending in nil as it must } + fd := Do_SysCall(MemfdCreate, TSysParam(PChar('raz')), MfdCloexec); + if fd < 0 then Fatal('can''t create a memfd'); + Str(fd, s); + outPath := '/proc/self/fd/' + s + #0; + WriteElf(outPath, entry); + FpExecve(@outPath[1], @argv[first], envp); + Fatal('can''t run ' + path); + end; + WriteElf(outPath, entry); +end. diff --git a/src/scan.pas b/src/scan.pas index 314c50a..1290c7e 100644 --- a/src/scan.pas +++ b/src/scan.pas @@ -1,6 +1,6 @@ { scan.pas: the scanner. - Reads a jed source file and hands the parser one symbol at a time: + Reads a raz source file and hands the parser one symbol at a time: reserved words, identifiers, numbers, characters, strings and operators. Identifiers are interned, so that the rest of the compiler compares names as small integers. The scanner also reports errors, @@ -191,7 +191,7 @@ procedure Fatal(const msg: shortstring); begin - writeln(StdErr, 'jed: ', msg); + writeln(StdErr, 'raz: ', msg); Halt(1); end; diff --git a/test/check.sh b/test/check.sh index 8b3404b..1817711 100755 --- a/test/check.sh +++ b/test/check.sh @@ -1,17 +1,17 @@ #!/bin/sh # Compiles and runs every example and test, and compares what each # prints, and its exit status, with what is expected: -# X.jed the program +# X.raz the program # X.expect its standard output # X.args its arguments, one per line (optional) # X.status its exit status (optional; 0 if missing) # A program without X.expect is compiled, not run. test/libc puts -# lib/Sys.jed, over the C library, before the system call one. +# lib/Sys.raz, over the C library, before the system call one. # Programs in test/err must not compile, and must print X.err. Then -# the version, tools/Doc.jed, the report's examples, tools/Pretty.jed, +# the version, tools/Doc.raz, the report's examples, tools/Pretty.raz, # and the library's own tests. -jed=./jed +raz=./raz out=build/check mkdir -p $out pass=0 @@ -19,7 +19,7 @@ run() { # run dir name dir=$1; name=$2 - if ! $jed -I $dir/mods -o $out/$name $dir/$name.jed 2>$out/$name.cerr; then + if ! $raz -I $dir/mods -o $out/$name $dir/$name.raz 2>$out/$name.cerr; then echo "FAIL $dir/$name: doesn't compile: $(cat $out/$name.cerr)" fail=$((fail + 1)); return fi @@ -44,24 +44,24 @@ fi } -for f in examples/*.jed test/run/*.jed test/libc/*.jed; do - run $(dirname $f) $(basename $f .jed) +for f in examples/*.raz test/run/*.raz test/libc/*.raz; do + run $(dirname $f) $(basename $f .raz) done -# jed run: a static program and one over C, from memory, with their +# raz run: a static program and one over C, from memory, with their # arguments, output and status passed through runs() { # runs file status [arg]... f=$1; want=$2; shift 2 - $jed run -I $(dirname $f)/mods $f "$@" > $out/run.out 2>/dev/null + $raz run -I $(dirname $f)/mods $f "$@" > $out/run.out 2>/dev/null status=$? - if cmp -s $out/run.out ${f%.jed}.expect && [ $status = $want ]; then pass=$((pass + 1)) - else echo "FAIL jed run $f: status $status, not $want, or output differs"; fail=$((fail + 1)); fi + if cmp -s $out/run.out ${f%.raz}.expect && [ $status = $want ]; then pass=$((pass + 1)) + else echo "FAIL raz run $f: status $status, not $want, or output differs"; fail=$((fail + 1)); fi } -runs test/run/Args.jed 4 one 'two words' é -runs test/libc/Through.jed 2 -for f in test/err/*.jed; do - name=$(basename $f .jed) - if $jed -I test/err/mods -I test/run/mods -o $out/$name $f 2>$out/$name.cerr; then +runs test/run/Args.raz 4 one 'two words' é +runs test/libc/Through.raz 2 +for f in test/err/*.raz; do + name=$(basename $f .raz) + if $raz -I test/err/mods -I test/run/mods -o $out/$name $f 2>$out/$name.cerr; then echo "FAIL $f: compiles" fail=$((fail + 1)) elif ! grep -qF "$(cat test/err/$name.err)" $out/$name.cerr; then @@ -72,19 +72,19 @@ fi done # the report's version is the one the compiler says it follows -want=$(sed -n 's/^This is version \([0-9.-]*\) of the report.*/\1/p' doc/jed.md) -if ./jed --version | grep -qF "report $want"; then pass=$((pass + 1)) -else echo "FAIL jed --version: not report $want"; fail=$((fail + 1)); fi +want=$(sed -n 's/^This is version \([0-9.-]*\) of the report.*/\1/p' doc/raz.md) +if ./raz --version | grep -qF "report $want"; then pass=$((pass + 1)) +else echo "FAIL raz --version: not report $want"; fail=$((fail + 1)); fi -# tools/Doc.jed: on every library module, and as test/doc expects -if ./jed -o $out/Doc tools/Doc.jed 2>$out/Doc.cerr; then - for f in lib/*.jed; do +# tools/Doc.raz: on every library module, and as test/doc expects +if ./raz -o $out/Doc tools/Doc.raz 2>$out/Doc.cerr; then + for f in lib/*.raz; do if ! $out/Doc $f > $out/doc.out; then echo "FAIL Doc $f"; fail=$((fail + 1)); fi done for f in test/doc/*.expect; do name=$(basename $f .expect) - m=lib/$name.jed - [ -f $m ] || m=lib/$name.linux-x86_64.jed + m=lib/$name.raz + [ -f $m ] || m=lib/$name.linux-x86_64.raz if $out/Doc $m | cmp -s - $f; then pass=$((pass + 1)) else echo "FAIL Doc $m: output differs"; fail=$((fail + 1)); fi done @@ -92,42 +92,42 @@ # the report's examples that are whole modules: each compiles, and # each with a main runs and ends with status 0 rm -rf $out/report; mkdir -p $out/report - for name in $($out/Doc examples doc/jed.md $out/report); do - if ! $jed -o $out/report/$name $out/report/$name.jed 2>$out/report/$name.cerr; then + for name in $($out/Doc examples doc/raz.md $out/report); do + if ! $raz -o $out/report/$name $out/report/$name.raz 2>$out/report/$name.cerr; then echo "FAIL report example $name: $(cat $out/report/$name.cerr)"; fail=$((fail + 1)) - elif grep -q '^proc main\*' $out/report/$name.jed && ! $out/report/$name > /dev/null 2>&1; then + elif grep -q '^proc main\*' $out/report/$name.raz && ! $out/report/$name > /dev/null 2>&1; then echo "FAIL report example $name: status $?"; fail=$((fail + 1)) else pass=$((pass + 1)); fi done else - echo "FAIL tools/Doc.jed: $(cat $out/Doc.cerr)"; fail=$((fail + 1)) + echo "FAIL tools/Doc.raz: $(cat $out/Doc.cerr)"; fail=$((fail + 1)) fi -# tools/Pretty.jed: each test/pretty/X.jed comes out as X.expect, which +# tools/Pretty.raz: each test/pretty/X.raz comes out as X.expect, which # comes out as it is; so do the library, the examples and the tools -if ./jed -o $out/Pretty tools/Pretty.jed 2>$out/Pretty.cerr; then - for f in test/pretty/*.jed; do - want=test/pretty/$(basename $f .jed).expect +if ./raz -o $out/Pretty tools/Pretty.raz 2>$out/Pretty.cerr; then + for f in test/pretty/*.raz; do + want=test/pretty/$(basename $f .raz).expect if $out/Pretty $f | cmp -s - $want && $out/Pretty $want | cmp -s - $want; then pass=$((pass + 1)) else echo "FAIL Pretty $f: output differs"; fail=$((fail + 1)); fi done - for f in lib/*.jed examples/*.jed tools/*.jed; do + for f in lib/*.raz examples/*.raz tools/*.raz; do if ! $out/Pretty $f | cmp -s - $f; then echo "FAIL Pretty $f: not formatted"; fail=$((fail + 1)) fi done pass=$((pass + 1)) else - echo "FAIL tools/Pretty.jed: $(cat $out/Pretty.cerr)"; fail=$((fail + 1)) + echo "FAIL tools/Pretty.raz: $(cat $out/Pretty.cerr)"; fail=$((fail + 1)) fi # each library module's main is its test; Sys over C is tested in test/libc -for f in lib/*.jed; do - [ $f = lib/Sys.jed ] && continue +for f in lib/*.raz; do + [ $f = lib/Sys.raz ] && continue grep -q '^proc main\*' $f || continue - name=lib_$(basename $f .jed) - if ! $jed -o $out/$name $f 2>$out/$name.cerr; then + name=lib_$(basename $f .raz) + if ! $raz -o $out/$name $f 2>$out/$name.cerr; then echo "FAIL $f: doesn't compile: $(cat $out/$name.cerr)"; fail=$((fail + 1)) elif ! $out/$name > $out/$name.out 2>&1; then echo "FAIL $f: its test says $(cat $out/$name.out)"; fail=$((fail + 1)) diff --git a/test/editors.sh b/test/editors.sh index 360fe6d..2341c4f 100755 --- a/test/editors.sh +++ b/test/editors.sh @@ -1,38 +1,38 @@ #!/bin/sh # Loads the editor support, headless, on each example: the file must be -# taken for jed, coloured without error, and indented again exactly as -# it is written; and test/editors/Colours.jed must be coloured as +# taken for raz, coloured without error, and indented again exactly as +# it is written; and test/editors/Colours.raz must be coloured as # Colours.expect says. Prints one line per failure; quiet if the editor # is missing. fail=0 if command -v vim >/dev/null; then - for f in examples/*.jed; do + for f in examples/*.raz; do vim -Nu NONE -i NONE -es \ -c 'set rtp^=editor/vim' -c 'filetype plugin indent on' -c 'syntax on' \ -c "edit $f" \ - -c 'if &filetype !=# "jed" || &shiftwidth != 4 | cquit | endif' \ + -c 'if &filetype !=# "raz" || &shiftwidth != 4 | cquit | endif' \ -c 'let before = getline(1, "$")' -c 'normal! gg=G' \ -c 'if getline(1, "$") != before | cquit | endif' -c 'qall!' \ || { echo "FAIL vim on $f"; fail=1; } done vim -Nu NONE -i NONE -es -c 'set rtp^=editor/vim' -c 'filetype plugin indent on' \ - -c 'syntax on' -c 'edit test/editors/Colours.jed' -S test/editors/colours.vim \ + -c 'syntax on' -c 'edit test/editors/Colours.raz' -S test/editors/colours.vim \ || { echo "FAIL vim colours"; fail=1; } fi if command -v emacs >/dev/null; then - for f in examples/*.jed; do - emacs -Q --batch -l editor/emacs/jed-mode.el --eval " + for f in examples/*.raz; do + emacs -Q --batch -l editor/emacs/raz-mode.el --eval " (progn (find-file \"$f\") - (unless (eq major-mode 'jed-mode) (kill-emacs 1)) + (unless (eq major-mode 'raz-mode) (kill-emacs 1)) (font-lock-ensure) (let ((before (buffer-string))) (indent-region (point-min) (point-max)) (unless (string= before (buffer-string)) (kill-emacs 2))))" \ 2>/dev/null || { echo "FAIL emacs on $f"; fail=1; } done - emacs -Q --batch -l editor/emacs/jed-mode.el -l test/editors/colours.el 2>/dev/null \ + emacs -Q --batch -l editor/emacs/raz-mode.el -l test/editors/colours.el 2>/dev/null \ || { echo "FAIL emacs colours"; fail=1; } fi exit $fail diff --git a/test/editors/Colours.jed b/test/editors/Colours.jed deleted file mode 100644 index ced1d47..0000000 --- a/test/editors/Colours.jed +++ /dev/null @@ -1,7 +0,0 @@ -(* outer (* nested *) still comment *) -module Colours; -const big = 0FFH; small = 2.5E-3; q = '\''; s = "a\"b"; -var x: I64; ok: BOOL; -begin - INC(x); ok := true; -end Colours. diff --git a/test/editors/Colours.raz b/test/editors/Colours.raz new file mode 100644 index 0000000..ced1d47 --- /dev/null +++ b/test/editors/Colours.raz @@ -0,0 +1,7 @@ +(* outer (* nested *) still comment *) +module Colours; +const big = 0FFH; small = 2.5E-3; q = '\''; s = "a\"b"; +var x: I64; ok: BOOL; +begin + INC(x); ok := true; +end Colours. diff --git a/test/editors/colours.el b/test/editors/colours.el index a359cea..51a0393 100644 --- a/test/editors/colours.el +++ b/test/editors/colours.el @@ -3,7 +3,7 @@ (insert-file-contents "test/editors/Colours.expect") (buffer-string)) "\n" t))) - (find-file "test/editors/Colours.jed") + (find-file "test/editors/Colours.raz") (font-lock-ensure) (dolist (want wants) (let* ((w (split-string want)) diff --git a/test/editors/colours.vim b/test/editors/colours.vim index aebb95b..0c6c9a8 100644 --- a/test/editors/colours.vim +++ b/test/editors/colours.vim @@ -1,7 +1,7 @@ " Checks each token of Colours.expect has the colour group it should. -let s:kinds = {'jedComment': 'comment', 'jedKeyword': 'keyword', 'jedNumber': 'number', - \ 'jedString': 'string', 'jedChar': 'string', 'jedType': 'type', - \ 'jedBuiltin': 'builtin', 'jedConstant': 'constant'} +let s:kinds = {'razComment': 'comment', 'razKeyword': 'keyword', 'razNumber': 'number', + \ 'razString': 'string', 'razChar': 'string', 'razType': 'type', + \ 'razBuiltin': 'builtin', 'razConstant': 'constant'} for s:want in readfile('test/editors/Colours.expect') let [s:l, s:c, s:k] = split(s:want) let s:group = synIDattr(synID(str2nr(s:l), str2nr(s:c), 1), 'name') diff --git a/test/err/Assign.jed b/test/err/Assign.jed deleted file mode 100644 index 1265423..0000000 --- a/test/err/Assign.jed +++ /dev/null @@ -1,7 +0,0 @@ -module Assign; -proc main*; -var a: I64; b: I32; -begin - a := b; -end; -end Assign. diff --git a/test/err/Assign.raz b/test/err/Assign.raz new file mode 100644 index 0000000..1265423 --- /dev/null +++ b/test/err/Assign.raz @@ -0,0 +1,7 @@ +module Assign; +proc main*; +var a: I64; b: I32; +begin + a := b; +end; +end Assign. diff --git a/test/err/BadProc.jed b/test/err/BadProc.jed deleted file mode 100644 index 97268d2..0000000 --- a/test/err/BadProc.jed +++ /dev/null @@ -1,3 +0,0 @@ -module BadProc; -import Str, M := Map([]U8, I64, Str.cmp, Str.eq); -end BadProc. diff --git a/test/err/BadProc.raz b/test/err/BadProc.raz new file mode 100644 index 0000000..97268d2 --- /dev/null +++ b/test/err/BadProc.raz @@ -0,0 +1,3 @@ +module BadProc; +import Str, M := Map([]U8, I64, Str.cmp, Str.eq); +end BadProc. diff --git a/test/err/BigI64.jed b/test/err/BigI64.jed deleted file mode 100644 index 19aacef..0000000 --- a/test/err/BigI64.jed +++ /dev/null @@ -1,7 +0,0 @@ -module BigI64; -proc main*; -var i: I64; -begin - i := 0FFFFFFFFFFFFFFFFH; -end; -end BigI64. diff --git a/test/err/BigI64.raz b/test/err/BigI64.raz new file mode 100644 index 0000000..19aacef --- /dev/null +++ b/test/err/BigI64.raz @@ -0,0 +1,7 @@ +module BigI64; +proc main*; +var i: I64; +begin + i := 0FFFFFFFFFFFFFFFFH; +end; +end BigI64. diff --git a/test/err/Break.jed b/test/err/Break.jed deleted file mode 100644 index b7e0697..0000000 --- a/test/err/Break.jed +++ /dev/null @@ -1,6 +0,0 @@ -module Break; -proc main*; -begin - break; -end; -end Break. diff --git a/test/err/Break.raz b/test/err/Break.raz new file mode 100644 index 0000000..b7e0697 --- /dev/null +++ b/test/err/Break.raz @@ -0,0 +1,6 @@ +module Break; +proc main*; +begin + break; +end; +end Break. diff --git a/test/err/Cycle.jed b/test/err/Cycle.jed deleted file mode 100644 index b8be661..0000000 --- a/test/err/Cycle.jed +++ /dev/null @@ -1,3 +0,0 @@ -module Cycle; -import CycleB; -end Cycle. diff --git a/test/err/Cycle.raz b/test/err/Cycle.raz new file mode 100644 index 0000000..b8be661 --- /dev/null +++ b/test/err/Cycle.raz @@ -0,0 +1,3 @@ +module Cycle; +import CycleB; +end Cycle. diff --git a/test/err/DeferBreak.jed b/test/err/DeferBreak.jed deleted file mode 100644 index 30abd59..0000000 --- a/test/err/DeferBreak.jed +++ /dev/null @@ -1,8 +0,0 @@ -module DeferBreak; -proc f; -begin - while true do - defer break; - end; -end; -end DeferBreak. diff --git a/test/err/DeferBreak.raz b/test/err/DeferBreak.raz new file mode 100644 index 0000000..30abd59 --- /dev/null +++ b/test/err/DeferBreak.raz @@ -0,0 +1,8 @@ +module DeferBreak; +proc f; +begin + while true do + defer break; + end; +end; +end DeferBreak. diff --git a/test/err/DeferDefer.jed b/test/err/DeferDefer.jed deleted file mode 100644 index acbb0f6..0000000 --- a/test/err/DeferDefer.jed +++ /dev/null @@ -1,6 +0,0 @@ -module DeferDefer; -proc f; -begin - defer defer f; -end; -end DeferDefer. diff --git a/test/err/DeferDefer.raz b/test/err/DeferDefer.raz new file mode 100644 index 0000000..acbb0f6 --- /dev/null +++ b/test/err/DeferDefer.raz @@ -0,0 +1,6 @@ +module DeferDefer; +proc f; +begin + defer defer f; +end; +end DeferDefer. diff --git a/test/err/DeferReturn.jed b/test/err/DeferReturn.jed deleted file mode 100644 index 2fdb85a..0000000 --- a/test/err/DeferReturn.jed +++ /dev/null @@ -1,7 +0,0 @@ -module DeferReturn; -proc f: I64; -begin - defer return 1; - return 0; -end; -end DeferReturn. diff --git a/test/err/DeferReturn.raz b/test/err/DeferReturn.raz new file mode 100644 index 0000000..2fdb85a --- /dev/null +++ b/test/err/DeferReturn.raz @@ -0,0 +1,7 @@ +module DeferReturn; +proc f: I64; +begin + defer return 1; + return 0; +end; +end DeferReturn. diff --git a/test/err/ErrOrder.jed b/test/err/ErrOrder.jed deleted file mode 100644 index f2fef84..0000000 --- a/test/err/ErrOrder.jed +++ /dev/null @@ -1,7 +0,0 @@ -module ErrOrder; -const A: ERROR = "a"; B: ERROR = "b"; -proc main*; -begin - if A < B then end; -end; -end ErrOrder. diff --git a/test/err/ErrOrder.raz b/test/err/ErrOrder.raz new file mode 100644 index 0000000..f2fef84 --- /dev/null +++ b/test/err/ErrOrder.raz @@ -0,0 +1,7 @@ +module ErrOrder; +const A: ERROR = "a"; B: ERROR = "b"; +proc main*; +begin + if A < B then end; +end; +end ErrOrder. diff --git a/test/err/ExternRec.jed b/test/err/ExternRec.jed deleted file mode 100644 index 6c90f96..0000000 --- a/test/err/ExternRec.jed +++ /dev/null @@ -1,7 +0,0 @@ -module ExternRec; - -type R = record a, b: I64; end; - -extern proc f(r: R); - -end ExternRec. diff --git a/test/err/ExternRec.raz b/test/err/ExternRec.raz new file mode 100644 index 0000000..6c90f96 --- /dev/null +++ b/test/err/ExternRec.raz @@ -0,0 +1,7 @@ +module ExternRec; + +type R = record a, b: I64; end; + +extern proc f(r: R); + +end ExternRec. diff --git a/test/err/F32Dots.jed b/test/err/F32Dots.jed deleted file mode 100644 index 445d23d..0000000 --- a/test/err/F32Dots.jed +++ /dev/null @@ -1,11 +0,0 @@ -module F32Dots; -import C; - -proc main*; -var x: F32; -begin - x := 1.5; - C.printf("%f\n", x); -end; - -end F32Dots. diff --git a/test/err/F32Dots.raz b/test/err/F32Dots.raz new file mode 100644 index 0000000..445d23d --- /dev/null +++ b/test/err/F32Dots.raz @@ -0,0 +1,11 @@ +module F32Dots; +import C; + +proc main*; +var x: F32; +begin + x := 1.5; + C.printf("%f\n", x); +end; + +end F32Dots. diff --git a/test/err/Field.jed b/test/err/Field.jed deleted file mode 100644 index 41c9cf9..0000000 --- a/test/err/Field.jed +++ /dev/null @@ -1,8 +0,0 @@ -module Field; -import Plat; -proc main*; -var i: Plat.Info; -begin - i.extra := 1; -end; -end Field. diff --git a/test/err/Field.raz b/test/err/Field.raz new file mode 100644 index 0000000..41c9cf9 --- /dev/null +++ b/test/err/Field.raz @@ -0,0 +1,8 @@ +module Field; +import Plat; +proc main*; +var i: Plat.Info; +begin + i.extra := 1; +end; +end Field. diff --git a/test/err/Match.jed b/test/err/Match.jed deleted file mode 100644 index f61cc23..0000000 --- a/test/err/Match.jed +++ /dev/null @@ -1,11 +0,0 @@ -module Match; -type S = variant a; b; c; end; -proc main*; -var s: S; -begin - match s of - | a: s := b; - | b: - end; -end; -end Match. diff --git a/test/err/Match.raz b/test/err/Match.raz new file mode 100644 index 0000000..f61cc23 --- /dev/null +++ b/test/err/Match.raz @@ -0,0 +1,11 @@ +module Match; +type S = variant a; b; c; end; +proc main*; +var s: S; +begin + match s of + | a: s := b; + | b: + end; +end; +end Match. diff --git a/test/err/Mixed.jed b/test/err/Mixed.jed deleted file mode 100644 index 693f8e4..0000000 --- a/test/err/Mixed.jed +++ /dev/null @@ -1,9 +0,0 @@ -module Mixed; - -proc main*; -var x: F32; y: F64; -begin - y := x + y; -end; - -end Mixed. diff --git a/test/err/Mixed.raz b/test/err/Mixed.raz new file mode 100644 index 0000000..693f8e4 --- /dev/null +++ b/test/err/Mixed.raz @@ -0,0 +1,9 @@ +module Mixed; + +proc main*; +var x: F32; y: F64; +begin + y := x + y; +end; + +end Mixed. diff --git a/test/err/NegU64.jed b/test/err/NegU64.jed deleted file mode 100644 index 867c83b..0000000 --- a/test/err/NegU64.jed +++ /dev/null @@ -1,7 +0,0 @@ -module NegU64; -proc main*; -var u: U64; -begin - u := -1; -end; -end NegU64. diff --git a/test/err/NegU64.raz b/test/err/NegU64.raz new file mode 100644 index 0000000..867c83b --- /dev/null +++ b/test/err/NegU64.raz @@ -0,0 +1,7 @@ +module NegU64; +proc main*; +var u: U64; +begin + u := -1; +end; +end NegU64. diff --git a/test/err/NoArgs.jed b/test/err/NoArgs.jed deleted file mode 100644 index f472904..0000000 --- a/test/err/NoArgs.jed +++ /dev/null @@ -1,3 +0,0 @@ -module NoArgs; -import List; -end NoArgs. diff --git a/test/err/NoArgs.raz b/test/err/NoArgs.raz new file mode 100644 index 0000000..f472904 --- /dev/null +++ b/test/err/NoArgs.raz @@ -0,0 +1,3 @@ +module NoArgs; +import List; +end NoArgs. diff --git a/test/err/NotGeneric.jed b/test/err/NotGeneric.jed deleted file mode 100644 index 547e417..0000000 --- a/test/err/NotGeneric.jed +++ /dev/null @@ -1,3 +0,0 @@ -module NotGeneric; -import S := Str(I64); -end NotGeneric. diff --git a/test/err/NotGeneric.raz b/test/err/NotGeneric.raz new file mode 100644 index 0000000..547e417 --- /dev/null +++ b/test/err/NotGeneric.raz @@ -0,0 +1,3 @@ +module NotGeneric; +import S := Str(I64); +end NotGeneric. diff --git a/test/err/PtrArray.jed b/test/err/PtrArray.jed deleted file mode 100644 index 17a91e7..0000000 --- a/test/err/PtrArray.jed +++ /dev/null @@ -1,8 +0,0 @@ -module PtrArray; -proc main*; -var a: [4]I64; p: ^[4]I64; -begin - p := ADR(a); - p[1] := 0; -end; -end PtrArray. diff --git a/test/err/PtrArray.raz b/test/err/PtrArray.raz new file mode 100644 index 0000000..17a91e7 --- /dev/null +++ b/test/err/PtrArray.raz @@ -0,0 +1,8 @@ +module PtrArray; +proc main*; +var a: [4]I64; p: ^[4]I64; +begin + p := ADR(a); + p[1] := 0; +end; +end PtrArray. diff --git a/test/err/Static.jed b/test/err/Static.jed deleted file mode 100644 index 7d4272b..0000000 --- a/test/err/Static.jed +++ /dev/null @@ -1,9 +0,0 @@ -module Static; -import Bare, C; - -proc main*; -begin - C.printf("%d\n", Bare.f()); -end; - -end Static. diff --git a/test/err/Static.raz b/test/err/Static.raz new file mode 100644 index 0000000..7d4272b --- /dev/null +++ b/test/err/Static.raz @@ -0,0 +1,9 @@ +module Static; +import Bare, C; + +proc main*; +begin + C.printf("%d\n", Bare.f()); +end; + +end Static. diff --git a/test/err/ThreadC.jed b/test/err/ThreadC.jed deleted file mode 100644 index f3794b8..0000000 --- a/test/err/ThreadC.jed +++ /dev/null @@ -1,8 +0,0 @@ -module ThreadC; -import Thread, C; - -proc main*; -begin -end; - -end ThreadC. diff --git a/test/err/ThreadC.raz b/test/err/ThreadC.raz new file mode 100644 index 0000000..f3794b8 --- /dev/null +++ b/test/err/ThreadC.raz @@ -0,0 +1,8 @@ +module ThreadC; +import Thread, C; + +proc main*; +begin +end; + +end ThreadC. diff --git a/test/err/Tuple.jed b/test/err/Tuple.jed deleted file mode 100644 index 2a077eb..0000000 --- a/test/err/Tuple.jed +++ /dev/null @@ -1,8 +0,0 @@ -module Tuple; -proc two: (I64, I64); begin return 1, 2; end; -proc main*; -var a: I64; -begin - a := two() + 1; -end; -end Tuple. diff --git a/test/err/Tuple.raz b/test/err/Tuple.raz new file mode 100644 index 0000000..2a077eb --- /dev/null +++ b/test/err/Tuple.raz @@ -0,0 +1,8 @@ +module Tuple; +proc two: (I64, I64); begin return 1, 2; end; +proc main*; +var a: I64; +begin + a := two() + 1; +end; +end Tuple. diff --git a/test/err/TwoTypes.jed b/test/err/TwoTypes.jed deleted file mode 100644 index 3269f35..0000000 --- a/test/err/TwoTypes.jed +++ /dev/null @@ -1,8 +0,0 @@ -module TwoTypes; -import A := List(I64), B := List(I32); -proc main*; -var a: A.List; b: B.List; -begin - a := b; -end; -end TwoTypes. diff --git a/test/err/TwoTypes.raz b/test/err/TwoTypes.raz new file mode 100644 index 0000000..3269f35 --- /dev/null +++ b/test/err/TwoTypes.raz @@ -0,0 +1,8 @@ +module TwoTypes; +import A := List(I64), B := List(I32); +proc main*; +var a: A.List; b: B.List; +begin + a := b; +end; +end TwoTypes. diff --git a/test/err/UsesExtra.jed b/test/err/UsesExtra.jed deleted file mode 100644 index d6482c5..0000000 --- a/test/err/UsesExtra.jed +++ /dev/null @@ -1,3 +0,0 @@ -module UsesExtra; -import Extra; -end UsesExtra. diff --git a/test/err/UsesExtra.raz b/test/err/UsesExtra.raz new file mode 100644 index 0000000..d6482c5 --- /dev/null +++ b/test/err/UsesExtra.raz @@ -0,0 +1,3 @@ +module UsesExtra; +import Extra; +end UsesExtra. diff --git a/test/err/UsesIface.jed b/test/err/UsesIface.jed deleted file mode 100644 index 9dd29d0..0000000 --- a/test/err/UsesIface.jed +++ /dev/null @@ -1,3 +0,0 @@ -module UsesIface; -import Iface; -end UsesIface. diff --git a/test/err/UsesIface.raz b/test/err/UsesIface.raz new file mode 100644 index 0000000..9dd29d0 --- /dev/null +++ b/test/err/UsesIface.raz @@ -0,0 +1,3 @@ +module UsesIface; +import Iface; +end UsesIface. diff --git a/test/err/UsesRec.jed b/test/err/UsesRec.jed deleted file mode 100644 index d446004..0000000 --- a/test/err/UsesRec.jed +++ /dev/null @@ -1,3 +0,0 @@ -module UsesRec; -import Rec; -end UsesRec. diff --git a/test/err/UsesRec.raz b/test/err/UsesRec.raz new file mode 100644 index 0000000..d446004 --- /dev/null +++ b/test/err/UsesRec.raz @@ -0,0 +1,3 @@ +module UsesRec; +import Rec; +end UsesRec. diff --git a/test/err/Utf.err b/test/err/Utf.err index a24bb48..6127c87 100644 --- a/test/err/Utf.err +++ b/test/err/Utf.err @@ -1 +1 @@ -Utf.jed:2:5: text outside strings, characters and comments must be ASCII +Utf.raz:2:5: text outside strings, characters and comments must be ASCII diff --git a/test/err/Utf.jed b/test/err/Utf.jed deleted file mode 100644 index c604f87..0000000 --- a/test/err/Utf.jed +++ /dev/null @@ -1,3 +0,0 @@ -module Utf; -var é: I64; -end Utf. diff --git a/test/err/Utf.raz b/test/err/Utf.raz new file mode 100644 index 0000000..c604f87 --- /dev/null +++ b/test/err/Utf.raz @@ -0,0 +1,3 @@ +module Utf; +var é: I64; +end Utf. diff --git a/test/err/Variadic.jed b/test/err/Variadic.jed deleted file mode 100644 index a3e39d2..0000000 --- a/test/err/Variadic.jed +++ /dev/null @@ -1,7 +0,0 @@ -module Variadic; - -proc f(a: I64; ...); -begin -end; - -end Variadic. diff --git a/test/err/Variadic.raz b/test/err/Variadic.raz new file mode 100644 index 0000000..a3e39d2 --- /dev/null +++ b/test/err/Variadic.raz @@ -0,0 +1,7 @@ +module Variadic; + +proc f(a: I64; ...); +begin +end; + +end Variadic. diff --git a/test/err/Volatile.jed b/test/err/Volatile.jed deleted file mode 100644 index f57aa24..0000000 --- a/test/err/Volatile.jed +++ /dev/null @@ -1,8 +0,0 @@ -module Volatile; -proc main*; -var x: I64; p: ^VOLATILE I64; q: ^I64; -begin - p := ADR(x); - q := p; -end; -end Volatile. diff --git a/test/err/Volatile.raz b/test/err/Volatile.raz new file mode 100644 index 0000000..f57aa24 --- /dev/null +++ b/test/err/Volatile.raz @@ -0,0 +1,8 @@ +module Volatile; +proc main*; +var x: I64; p: ^VOLATILE I64; q: ^I64; +begin + p := ADR(x); + q := p; +end; +end Volatile. diff --git a/test/err/mods/Bare.jed b/test/err/mods/Bare.jed deleted file mode 100644 index 98c6b81..0000000 --- a/test/err/mods/Bare.jed +++ /dev/null @@ -1,10 +0,0 @@ -(* A module that needs a program without C. *) -module Bare; -link static; - -proc f*: I64; -begin - return 1; -end; - -end Bare. diff --git a/test/err/mods/Bare.raz b/test/err/mods/Bare.raz new file mode 100644 index 0000000..98c6b81 --- /dev/null +++ b/test/err/mods/Bare.raz @@ -0,0 +1,10 @@ +(* A module that needs a program without C. *) +module Bare; +link static; + +proc f*: I64; +begin + return 1; +end; + +end Bare. diff --git a/test/err/mods/Cycle.jed b/test/err/mods/Cycle.jed deleted file mode 100644 index b8be661..0000000 --- a/test/err/mods/Cycle.jed +++ /dev/null @@ -1,3 +0,0 @@ -module Cycle; -import CycleB; -end Cycle. diff --git a/test/err/mods/Cycle.raz b/test/err/mods/Cycle.raz new file mode 100644 index 0000000..b8be661 --- /dev/null +++ b/test/err/mods/Cycle.raz @@ -0,0 +1,3 @@ +module Cycle; +import CycleB; +end Cycle. diff --git a/test/err/mods/CycleB.jed b/test/err/mods/CycleB.jed deleted file mode 100644 index 1e365e8..0000000 --- a/test/err/mods/CycleB.jed +++ /dev/null @@ -1,3 +0,0 @@ -module CycleB; -import Cycle; -end CycleB. diff --git a/test/err/mods/CycleB.raz b/test/err/mods/CycleB.raz new file mode 100644 index 0000000..1e365e8 --- /dev/null +++ b/test/err/mods/CycleB.raz @@ -0,0 +1,3 @@ +module CycleB; +import Cycle; +end CycleB. diff --git a/test/err/mods/Extra.jed b/test/err/mods/Extra.jed deleted file mode 100644 index 218c10e..0000000 --- a/test/err/mods/Extra.jed +++ /dev/null @@ -1,4 +0,0 @@ -module Extra; -type R* = record a*: I64; secret: [4]I64; end; -const more* = 1; -end Extra. diff --git a/test/err/mods/Extra.linux.jed b/test/err/mods/Extra.linux.jed deleted file mode 100644 index fa80151..0000000 --- a/test/err/mods/Extra.linux.jed +++ /dev/null @@ -1,3 +0,0 @@ -module Extra; -type R* = record a*: I64; hidden: U8; end; -end Extra. diff --git a/test/err/mods/Extra.linux.raz b/test/err/mods/Extra.linux.raz new file mode 100644 index 0000000..fa80151 --- /dev/null +++ b/test/err/mods/Extra.linux.raz @@ -0,0 +1,3 @@ +module Extra; +type R* = record a*: I64; hidden: U8; end; +end Extra. diff --git a/test/err/mods/Extra.raz b/test/err/mods/Extra.raz new file mode 100644 index 0000000..218c10e --- /dev/null +++ b/test/err/mods/Extra.raz @@ -0,0 +1,4 @@ +module Extra; +type R* = record a*: I64; secret: [4]I64; end; +const more* = 1; +end Extra. diff --git a/test/err/mods/Iface.jed b/test/err/mods/Iface.jed deleted file mode 100644 index 7ecbea9..0000000 --- a/test/err/mods/Iface.jed +++ /dev/null @@ -1,3 +0,0 @@ -module Iface; -proc f*(x: I32): I64; begin return 0; end; -end Iface. diff --git a/test/err/mods/Iface.linux-x86_64.jed b/test/err/mods/Iface.linux-x86_64.jed deleted file mode 100644 index 52d7f0c..0000000 --- a/test/err/mods/Iface.linux-x86_64.jed +++ /dev/null @@ -1,3 +0,0 @@ -module Iface; -proc f*(x: I64): I64; begin return x; end; -end Iface. diff --git a/test/err/mods/Iface.linux-x86_64.raz b/test/err/mods/Iface.linux-x86_64.raz new file mode 100644 index 0000000..52d7f0c --- /dev/null +++ b/test/err/mods/Iface.linux-x86_64.raz @@ -0,0 +1,3 @@ +module Iface; +proc f*(x: I64): I64; begin return x; end; +end Iface. diff --git a/test/err/mods/Iface.raz b/test/err/mods/Iface.raz new file mode 100644 index 0000000..7ecbea9 --- /dev/null +++ b/test/err/mods/Iface.raz @@ -0,0 +1,3 @@ +module Iface; +proc f*(x: I32): I64; begin return 0; end; +end Iface. diff --git a/test/err/mods/Rec.jed b/test/err/mods/Rec.jed deleted file mode 100644 index 3fa6ee9..0000000 --- a/test/err/mods/Rec.jed +++ /dev/null @@ -1,4 +0,0 @@ -module Rec; -type R* = record a*: I32; end; -proc f*(r: ^R); begin end; -end Rec. diff --git a/test/err/mods/Rec.linux-x86_64.jed b/test/err/mods/Rec.linux-x86_64.jed deleted file mode 100644 index 63611c0..0000000 --- a/test/err/mods/Rec.linux-x86_64.jed +++ /dev/null @@ -1,4 +0,0 @@ -module Rec; -type R* = record a*: I64; b: I64; end; -proc f*(r: ^R); begin end; -end Rec. diff --git a/test/err/mods/Rec.linux-x86_64.raz b/test/err/mods/Rec.linux-x86_64.raz new file mode 100644 index 0000000..63611c0 --- /dev/null +++ b/test/err/mods/Rec.linux-x86_64.raz @@ -0,0 +1,4 @@ +module Rec; +type R* = record a*: I64; b: I64; end; +proc f*(r: ^R); begin end; +end Rec. diff --git a/test/err/mods/Rec.raz b/test/err/mods/Rec.raz new file mode 100644 index 0000000..3fa6ee9 --- /dev/null +++ b/test/err/mods/Rec.raz @@ -0,0 +1,4 @@ +module Rec; +type R* = record a*: I32; end; +proc f*(r: ^R); begin end; +end Rec. diff --git a/test/gdb.sh b/test/gdb.sh index 30ec5d7..c270199 100755 --- a/test/gdb.sh +++ b/test/gdb.sh @@ -4,11 +4,11 @@ # caller. out=build/check mkdir -p $out -./jed -I test/run/mods -o $out/Procs test/run/Procs.jed || exit 1 -gdb -batch -ex 'break test/run/Procs.jed:13' -ex run -ex bt $out/Procs > $out/gdb.out 2>&1 -for want in 'Breakpoint 1, Procs.odd () at test/run/Procs.jed:13' \ - 'in Procs.even () at test/run/Procs.jed:20' \ - 'in Procs.main () at test/run/Procs.jed:'; do +./raz -I test/run/mods -o $out/Procs test/run/Procs.raz || exit 1 +gdb -batch -ex 'break test/run/Procs.raz:13' -ex run -ex bt $out/Procs > $out/gdb.out 2>&1 +for want in 'Breakpoint 1, Procs.odd () at test/run/Procs.raz:13' \ + 'in Procs.even () at test/run/Procs.raz:20' \ + 'in Procs.main () at test/run/Procs.raz:'; do if ! grep -qF "$want" $out/gdb.out; then echo "FAIL gdb: no \"$want\""; cat $out/gdb.out; exit 1 fi diff --git a/test/genbench.py b/test/genbench.py index 6794ea7..9a8a3df 100644 --- a/test/genbench.py +++ b/test/genbench.py @@ -1,4 +1,4 @@ -"""Writes a large jed program to standard output, for timing the +"""Writes a large raz program to standard output, for timing the compiler: n procedures of loops, conditions, records, slices and calls, each calling the one before, so that none is left out.""" import sys diff --git a/test/libc/SysTest.jed b/test/libc/SysTest.jed deleted file mode 100644 index 88666c4..0000000 --- a/test/libc/SysTest.jed +++ /dev/null @@ -1,10 +0,0 @@ -(* Sys over the C library, through its own test. *) -module SysTest; -import Sys; - -proc main*; -begin - Sys.main; -end; - -end SysTest. diff --git a/test/libc/SysTest.raz b/test/libc/SysTest.raz new file mode 100644 index 0000000..88666c4 --- /dev/null +++ b/test/libc/SysTest.raz @@ -0,0 +1,10 @@ +(* Sys over the C library, through its own test. *) +module SysTest; +import Sys; + +proc main*; +begin + Sys.main; +end; + +end SysTest. diff --git a/test/libc/Through.jed b/test/libc/Through.jed deleted file mode 100644 index 28345e7..0000000 --- a/test/libc/Through.jed +++ /dev/null @@ -1,33 +0,0 @@ -(* The library over C's Sys, lib/Sys.jed, which this directory puts - first: output, memory from the heap, and a failed check that still - writes out what Out holds. *) -module Through; -import Out, Heap, Mem; - -type Node = record next: ^Node; n: I64; end; - -proc main*; -var p, list: ^Node; i, sum: I64; a: [3]I64; -begin - Out.str("through C\n"); - list := nil; - for i := 1 to 1000 do - NEW(p, Heap.heap); - p^.n := i; - p^.next := list; - list := p; - end; - sum := 0; - while list # nil do - sum := sum + list^.n; - p := list; - list := list^.next; - Mem.free(Heap.heap, ^U8(p)); - end; - Out.int(sum); Out.ln; - i := 3; - a[i] := 1; - Out.str("not reached\n"); -end; - -end Through. diff --git a/test/libc/Through.raz b/test/libc/Through.raz new file mode 100644 index 0000000..7a61432 --- /dev/null +++ b/test/libc/Through.raz @@ -0,0 +1,33 @@ +(* The library over C's Sys, lib/Sys.raz, which this directory puts + first: output, memory from the heap, and a failed check that still + writes out what Out holds. *) +module Through; +import Out, Heap, Mem; + +type Node = record next: ^Node; n: I64; end; + +proc main*; +var p, list: ^Node; i, sum: I64; a: [3]I64; +begin + Out.str("through C\n"); + list := nil; + for i := 1 to 1000 do + NEW(p, Heap.heap); + p^.n := i; + p^.next := list; + list := p; + end; + sum := 0; + while list # nil do + sum := sum + list^.n; + p := list; + list := list^.next; + Mem.free(Heap.heap, ^U8(p)); + end; + Out.int(sum); Out.ln; + i := 3; + a[i] := 1; + Out.str("not reached\n"); +end; + +end Through. diff --git a/test/libc/mods/Sys.jed b/test/libc/mods/Sys.jed deleted file mode 120000 index 7979ce3..0000000 --- a/test/libc/mods/Sys.jed +++ /dev/null @@ -1 +0,0 @@ -../../../lib/Sys.jed \ No newline at end of file diff --git a/test/libc/mods/Sys.raz b/test/libc/mods/Sys.raz new file mode 120000 index 0000000..19371c0 --- /dev/null +++ b/test/libc/mods/Sys.raz @@ -0,0 +1 @@ +../../../lib/Sys.raz \ No newline at end of file diff --git a/test/pretty/Messy.jed b/test/pretty/Messy.jed deleted file mode 100644 index 7b38220..0000000 --- a/test/pretty/Messy.jed +++ /dev/null @@ -1,57 +0,0 @@ -(* A module laid out badly. *) - module Messy; -import Out,Rt; - -const -max* =10; - min=-1; - -type - Pair* = record - a*,b: I64; (* two numbers *) - end; - Shape = variant - circle(r: I64); - dot; - end; - - (* the bigger *) - proc max2*(a,b:I64):I64; -var m : I64; - begin -if a>b then m:=a; - elsif a=b then - m :=a ; - else - m:= b;end; - return m; - end; - -proc area(s: Shape): I64; -begin -match s of - | circle(r): return 3*r*r; -| dot: - return 0; - end; -end; - -proc main*; -var i,s:I64; p: Pair; -begin - s:=0; - for i:=-3 to max-1 do s:=s+i*2- -1;end; - repeat - s := s-1 ; - until s<0; - if (s # -1) or (max2(3,4) # 4) - or (area({dot}) # 0) then Rt.stop("Messy"); end; - p := {a: -s, b:2}; - Out.int(p.a); (* the first *) - Out.ln; - (* and done: - a comment that moves - with its line *) -end; - -end Messy. diff --git a/test/pretty/Messy.raz b/test/pretty/Messy.raz new file mode 100644 index 0000000..7b38220 --- /dev/null +++ b/test/pretty/Messy.raz @@ -0,0 +1,57 @@ +(* A module laid out badly. *) + module Messy; +import Out,Rt; + +const +max* =10; + min=-1; + +type + Pair* = record + a*,b: I64; (* two numbers *) + end; + Shape = variant + circle(r: I64); + dot; + end; + + (* the bigger *) + proc max2*(a,b:I64):I64; +var m : I64; + begin +if a>b then m:=a; + elsif a=b then + m :=a ; + else + m:= b;end; + return m; + end; + +proc area(s: Shape): I64; +begin +match s of + | circle(r): return 3*r*r; +| dot: + return 0; + end; +end; + +proc main*; +var i,s:I64; p: Pair; +begin + s:=0; + for i:=-3 to max-1 do s:=s+i*2- -1;end; + repeat + s := s-1 ; + until s<0; + if (s # -1) or (max2(3,4) # 4) + or (area({dot}) # 0) then Rt.stop("Messy"); end; + p := {a: -s, b:2}; + Out.int(p.a); (* the first *) + Out.ln; + (* and done: + a comment that moves + with its line *) +end; + +end Messy. diff --git a/test/run/Alloc.jed b/test/run/Alloc.jed deleted file mode 100644 index 6d5245c..0000000 --- a/test/run/Alloc.jed +++ /dev/null @@ -1,66 +0,0 @@ -module Alloc; -import Out, Mem, Arena, Heap; - -type - Node = record next: ^Node; val: I64; pad: [5]I64; end; - Big = record data: [1000]I64; end; - -proc build(a: ^Mem.Allocator; n: I64): ^Node; -var head, p: ^Node; i: I64; -begin - head := nil; - for i := 1 to n do - NEW(p, a); - if p = nil then return nil; end; - if p^.val # 0 then Out.str("not zeroed "); end; - p^.val := i; - p^.pad[4] := i; - p^.next := head; - head := p; - end; - return head; -end; - -proc sum(p: ^Node): I64; -var s: I64; -begin - s := 0; - while p # nil do s := s + p^.val + p^.pad[4]; p := p^.next; end; - return s; -end; - -proc release(a: ^Mem.Allocator; p: ^Node); -var next: ^Node; -begin - while p # nil do - next := p^.next; - Mem.free(a, ^U8(p)); - p := next; - end; -end; - -proc main*; -var ar: Arena.Arena; l, m: ^Node; b: ^Big; i: I64; small: ^U8; again: ^Node; -begin - l := build(Heap.heap, 1000); - Out.int(sum(l)); Out.ln; - release(Heap.heap, l); - m := build(Heap.heap, 1000); - Out.int(sum(m)); Out.ln; - NEW(b, Heap.heap); - b^.data[999] := 7; - Out.int(b^.data[999] + b^.data[0]); Out.ln; - Mem.free(Heap.heap, ^U8(b)); - if not Arena.init(ADR(ar), 8192) then Out.str("no arena"); end; - l := build(ADR(ar.base), 100); - Out.int(sum(l)); Out.ln; - l := build(ADR(ar.base), 1000); - if l = nil then Out.str("nil "); end; - Arena.reset(ADR(ar)); - NEW(again, ADR(ar.base)); - if again # nil then Out.str("again "); Out.int(again^.val); end; - Out.ln; - Arena.done(ADR(ar)); -end; - -end Alloc. diff --git a/test/run/Alloc.raz b/test/run/Alloc.raz new file mode 100644 index 0000000..6d5245c --- /dev/null +++ b/test/run/Alloc.raz @@ -0,0 +1,66 @@ +module Alloc; +import Out, Mem, Arena, Heap; + +type + Node = record next: ^Node; val: I64; pad: [5]I64; end; + Big = record data: [1000]I64; end; + +proc build(a: ^Mem.Allocator; n: I64): ^Node; +var head, p: ^Node; i: I64; +begin + head := nil; + for i := 1 to n do + NEW(p, a); + if p = nil then return nil; end; + if p^.val # 0 then Out.str("not zeroed "); end; + p^.val := i; + p^.pad[4] := i; + p^.next := head; + head := p; + end; + return head; +end; + +proc sum(p: ^Node): I64; +var s: I64; +begin + s := 0; + while p # nil do s := s + p^.val + p^.pad[4]; p := p^.next; end; + return s; +end; + +proc release(a: ^Mem.Allocator; p: ^Node); +var next: ^Node; +begin + while p # nil do + next := p^.next; + Mem.free(a, ^U8(p)); + p := next; + end; +end; + +proc main*; +var ar: Arena.Arena; l, m: ^Node; b: ^Big; i: I64; small: ^U8; again: ^Node; +begin + l := build(Heap.heap, 1000); + Out.int(sum(l)); Out.ln; + release(Heap.heap, l); + m := build(Heap.heap, 1000); + Out.int(sum(m)); Out.ln; + NEW(b, Heap.heap); + b^.data[999] := 7; + Out.int(b^.data[999] + b^.data[0]); Out.ln; + Mem.free(Heap.heap, ^U8(b)); + if not Arena.init(ADR(ar), 8192) then Out.str("no arena"); end; + l := build(ADR(ar.base), 100); + Out.int(sum(l)); Out.ln; + l := build(ADR(ar.base), 1000); + if l = nil then Out.str("nil "); end; + Arena.reset(ADR(ar)); + NEW(again, ADR(ar.base)); + if again # nil then Out.str("again "); Out.int(again^.val); end; + Out.ln; + Arena.done(ADR(ar)); +end; + +end Alloc. diff --git a/test/run/Args.jed b/test/run/Args.jed deleted file mode 100644 index f069599..0000000 --- a/test/run/Args.jed +++ /dev/null @@ -1,18 +0,0 @@ -module Args; -import Out; - -proc main*: I64; -var i, n: I64; a: ^^U8; s: ^U8; -begin - a := ARGV(); - for i := 1 to ARGC() - 1 do - s := a[i]; - n := 0; - while s[n] # 0 do n := n + 1; end; - Out.str(s[0..n]); - Out.ln; - end; - return ARGC(); -end; - -end Args. diff --git a/test/run/Args.raz b/test/run/Args.raz new file mode 100644 index 0000000..f069599 --- /dev/null +++ b/test/run/Args.raz @@ -0,0 +1,18 @@ +module Args; +import Out; + +proc main*: I64; +var i, n: I64; a: ^^U8; s: ^U8; +begin + a := ARGV(); + for i := 1 to ARGC() - 1 do + s := a[i]; + n := 0; + while s[n] # 0 do n := n + 1; end; + Out.str(s[0..n]); + Out.ln; + end; + return ARGC(); +end; + +end Args. diff --git a/test/run/Arith.jed b/test/run/Arith.jed deleted file mode 100644 index 8fe90cb..0000000 --- a/test/run/Arith.jed +++ /dev/null @@ -1,74 +0,0 @@ -module Arith; -import Out; - -const - K = 10; - M = K * 3 + 2; - Big = 0FFFFFFFFFFFFFFFFH; - -var g: I64; - -proc show(s: []U8; n: I64); -begin - Out.str(s); Out.str(" "); Out.int(n); Out.ln; -end; - -proc showb(s: []U8; t: BOOL); -begin - if t then show(s, 1); else show(s, 0); end; -end; - -proc main*; -var a, b: I64; u: U8; i8: I8; w: U32; x: U64; r: F64; t: BOOL; -begin - show("M", M); - a := 17; b := 5; - show("add", a + b); - show("sub", a - b); - show("mul", a * b); - show("div", -7 div 2); - show("mod", -7 mod 2); - show("divv", (0 - a) div b); - show("modv", (0 - a) mod b); - show("prec", 2 + 3 * 4); - show("neg", -a * b); - u := 200; - u := u + 100; - show("u8wrap", I64(u)); - i8 := 127; - i8 := i8 + 1; - show("i8wrap", I64(i8)); - w := 0FFFFFFFFH; - w := w + 2; - show("u32wrap", I64(w)); - x := Big; - showb("u64>i", x > 5); - showb("i64<", -1 < 5); - show("shl", 1 shl 10); - show("shr", -16 shr 2); - show("ushr", I64(U64(-16) shr 60)); - show("and", 12 and 10); - show("or", 12 or 3); - show("xor", 12 xor 10); - show("not", not 0); - r := F64(a) / 2.0; - show("real", I64(r * 10.0)); - r := -2.75; - show("trunc", I64(r)); - showb("nan", 0.0 / 0.0 = 0.0 / 0.0); - showb("rlt", 1.5 < 2.5); - show("u64real", I64(F64(x) / 1.0E18)); - t := (a > 3) and (b < 3); - if not t then show("bool", 1); end; - t := (a > 3) or (g div 0 = 1); - if t then show("shortcut", 1); end; - g := 42; - show("global", g); - show("char", 'A'); - show("utf8", 'é'); - show("hexconst", 0FFH); - show("cut", I64(U8(300))); - show("sext", I64(I8(U8(255)))); -end; - -end Arith. diff --git a/test/run/Arith.raz b/test/run/Arith.raz new file mode 100644 index 0000000..8fe90cb --- /dev/null +++ b/test/run/Arith.raz @@ -0,0 +1,74 @@ +module Arith; +import Out; + +const + K = 10; + M = K * 3 + 2; + Big = 0FFFFFFFFFFFFFFFFH; + +var g: I64; + +proc show(s: []U8; n: I64); +begin + Out.str(s); Out.str(" "); Out.int(n); Out.ln; +end; + +proc showb(s: []U8; t: BOOL); +begin + if t then show(s, 1); else show(s, 0); end; +end; + +proc main*; +var a, b: I64; u: U8; i8: I8; w: U32; x: U64; r: F64; t: BOOL; +begin + show("M", M); + a := 17; b := 5; + show("add", a + b); + show("sub", a - b); + show("mul", a * b); + show("div", -7 div 2); + show("mod", -7 mod 2); + show("divv", (0 - a) div b); + show("modv", (0 - a) mod b); + show("prec", 2 + 3 * 4); + show("neg", -a * b); + u := 200; + u := u + 100; + show("u8wrap", I64(u)); + i8 := 127; + i8 := i8 + 1; + show("i8wrap", I64(i8)); + w := 0FFFFFFFFH; + w := w + 2; + show("u32wrap", I64(w)); + x := Big; + showb("u64>i", x > 5); + showb("i64<", -1 < 5); + show("shl", 1 shl 10); + show("shr", -16 shr 2); + show("ushr", I64(U64(-16) shr 60)); + show("and", 12 and 10); + show("or", 12 or 3); + show("xor", 12 xor 10); + show("not", not 0); + r := F64(a) / 2.0; + show("real", I64(r * 10.0)); + r := -2.75; + show("trunc", I64(r)); + showb("nan", 0.0 / 0.0 = 0.0 / 0.0); + showb("rlt", 1.5 < 2.5); + show("u64real", I64(F64(x) / 1.0E18)); + t := (a > 3) and (b < 3); + if not t then show("bool", 1); end; + t := (a > 3) or (g div 0 = 1); + if t then show("shortcut", 1); end; + g := 42; + show("global", g); + show("char", 'A'); + show("utf8", 'é'); + show("hexconst", 0FFH); + show("cut", I64(U8(300))); + show("sext", I64(I8(U8(255)))); +end; + +end Arith. diff --git a/test/run/AtExit.jed b/test/run/AtExit.jed deleted file mode 100644 index 7abbb41..0000000 --- a/test/run/AtExit.jed +++ /dev/null @@ -1,41 +0,0 @@ -(* Rt.exit runs what Rt.atExit registered, the last first, each once, - then ends the program with main's status. *) -module AtExit; -import Out, Rt; - -proc first; -begin - Out.str("first\n"); -end; - -proc second; -begin - Out.str("second, which exits again\n"); - Rt.exit(5); (* the rest still run, once each; the status is now 5 *) -end; - -proc third; -begin - Out.str("third\n"); -end; - -proc nothing; -begin -end; - -proc main*: I64; -var i, full: I64; -begin - Rt.atExit(first); - Rt.atExit(second); - Rt.atExit(third); - full := 0; - for i := 1 to 40 do - if Rt.atExit(nothing) = Rt.Full then INC(full); end; - end; - Out.int(full); Out.str(" refused\n"); - Out.str("main ends\n"); - return 3; -end; - -end AtExit. diff --git a/test/run/AtExit.raz b/test/run/AtExit.raz new file mode 100644 index 0000000..7abbb41 --- /dev/null +++ b/test/run/AtExit.raz @@ -0,0 +1,41 @@ +(* Rt.exit runs what Rt.atExit registered, the last first, each once, + then ends the program with main's status. *) +module AtExit; +import Out, Rt; + +proc first; +begin + Out.str("first\n"); +end; + +proc second; +begin + Out.str("second, which exits again\n"); + Rt.exit(5); (* the rest still run, once each; the status is now 5 *) +end; + +proc third; +begin + Out.str("third\n"); +end; + +proc nothing; +begin +end; + +proc main*: I64; +var i, full: I64; +begin + Rt.atExit(first); + Rt.atExit(second); + Rt.atExit(third); + full := 0; + for i := 1 to 40 do + if Rt.atExit(nothing) = Rt.Full then INC(full); end; + end; + Out.int(full); Out.str(" refused\n"); + Out.str("main ends\n"); + return 3; +end; + +end AtExit. diff --git a/test/run/Atomic.jed b/test/run/Atomic.jed deleted file mode 100644 index 290df92..0000000 --- a/test/run/Atomic.jed +++ /dev/null @@ -1,35 +0,0 @@ -module Atomic; -import Out; - -var counter: I64; flag: U64; p: ^I64; - -proc add3*(a, b, c: I64): I64; -code 48H, 8DH, 04H, 37H, (* lea rax, [rdi+rsi] *) - 48H, 01H, 0D0H, (* add rax, rdx *) - 0C3H; (* ret *) - -proc main*; -var old: I64; ok: BOOL; v: ^VOLATILE I64; x: I64; -begin - old := XADD(ADR(counter), 5); - old := XADD(ADR(counter), 2); - Out.int(old); Out.str(" "); Out.int(counter); Out.ln; - ok := CAS(ADR(counter), 7, 100); - if ok then Out.str("cas1 "); end; - ok := CAS(ADR(counter), 7, 200); - if not ok then Out.str("cas2 "); end; - Out.int(counter); Out.ln; - Out.int(I64(XCHG(ADR(flag), 9))); Out.str(" "); - Out.int(I64(XCHG(ADR(flag), 3))); Out.ln; - FENCE; - FENCE(); - Out.int(add3(1, 20, 300)); Out.ln; - v := ADR(x); - v^ := 5; - v^ := v^ + 1; - Out.int(x); Out.ln; - v := ^VOLATILE I64(ADR(counter)); - Out.int(v^); Out.ln; -end; - -end Atomic. diff --git a/test/run/Atomic.raz b/test/run/Atomic.raz new file mode 100644 index 0000000..290df92 --- /dev/null +++ b/test/run/Atomic.raz @@ -0,0 +1,35 @@ +module Atomic; +import Out; + +var counter: I64; flag: U64; p: ^I64; + +proc add3*(a, b, c: I64): I64; +code 48H, 8DH, 04H, 37H, (* lea rax, [rdi+rsi] *) + 48H, 01H, 0D0H, (* add rax, rdx *) + 0C3H; (* ret *) + +proc main*; +var old: I64; ok: BOOL; v: ^VOLATILE I64; x: I64; +begin + old := XADD(ADR(counter), 5); + old := XADD(ADR(counter), 2); + Out.int(old); Out.str(" "); Out.int(counter); Out.ln; + ok := CAS(ADR(counter), 7, 100); + if ok then Out.str("cas1 "); end; + ok := CAS(ADR(counter), 7, 200); + if not ok then Out.str("cas2 "); end; + Out.int(counter); Out.ln; + Out.int(I64(XCHG(ADR(flag), 9))); Out.str(" "); + Out.int(I64(XCHG(ADR(flag), 3))); Out.ln; + FENCE; + FENCE(); + Out.int(add3(1, 20, 300)); Out.ln; + v := ADR(x); + v^ := 5; + v^ := v^ + 1; + Out.int(x); Out.ln; + v := ^VOLATILE I64(ADR(counter)); + Out.int(v^); Out.ln; +end; + +end Atomic. diff --git a/test/run/Bodies.jed b/test/run/Bodies.jed deleted file mode 100644 index aee922d..0000000 --- a/test/run/Bodies.jed +++ /dev/null @@ -1,11 +0,0 @@ -module Bodies; -import Out, A := First, Second; - -proc main*; -begin - Out.str("main "); Out.int(A.count); Out.int(Second.count); Out.ln; -end; - -begin - Out.str("Bodies "); -end Bodies. diff --git a/test/run/Bodies.raz b/test/run/Bodies.raz new file mode 100644 index 0000000..aee922d --- /dev/null +++ b/test/run/Bodies.raz @@ -0,0 +1,11 @@ +module Bodies; +import Out, A := First, Second; + +proc main*; +begin + Out.str("main "); Out.int(A.count); Out.int(Second.count); Out.ln; +end; + +begin + Out.str("Bodies "); +end Bodies. diff --git a/test/run/Bounds.jed b/test/run/Bounds.jed deleted file mode 100644 index 86210e2..0000000 --- a/test/run/Bounds.jed +++ /dev/null @@ -1,13 +0,0 @@ -module Bounds; -import Out; - -proc main*; -var a: [4]I64; i: I64; -begin - for i := 0 to 4 do - a[i] := i; - Out.int(a[i]); - end; -end; - -end Bounds. diff --git a/test/run/Bounds.raz b/test/run/Bounds.raz new file mode 100644 index 0000000..86210e2 --- /dev/null +++ b/test/run/Bounds.raz @@ -0,0 +1,13 @@ +module Bounds; +import Out; + +proc main*; +var a: [4]I64; i: I64; +begin + for i := 0 to 4 do + a[i] := i; + Out.int(a[i]); + end; +end; + +end Bounds. diff --git a/test/run/Control.jed b/test/run/Control.jed deleted file mode 100644 index 314101b..0000000 --- a/test/run/Control.jed +++ /dev/null @@ -1,42 +0,0 @@ -module Control; -import Out; - -proc main*; -var i, j, n: I64; u: U8; k: I8; -begin - for i := 1 to 5 do Out.int(i); end; Out.ln; - for i := 10 to 1 by -3 do Out.int(i); Out.str(" "); end; Out.ln; - for i := 0 to 10 by 4 do Out.int(i); Out.str(" "); end; Out.ln; - for i := 5 to 1 do Out.str("never"); end; - n := 0; - for u := 250 to 255 do n := n + 1; end; - Out.int(n); Out.ln; - n := 0; - for k := 120 to 127 by 3 do n := n + 1; end; - Out.int(n); Out.ln; - i := 0; - while i < 3 do - j := 0; - while true do - if j = 2 then break; end; - Out.int(i * 10 + j); Out.str(" "); - j := j + 1; - end; - i := i + 1; - end; - Out.ln; - i := 0; - repeat i := i + 1; if i = 4 then break; end; until i = 10; - Out.int(i); Out.ln; - for i := 1 to 4 do - if i = 1 then Out.str("one"); - elsif i = 2 then Out.str("two"); - elsif i = 3 then Out.str("three"); - else Out.str("many"); - end; - Out.str(" "); - end; - Out.ln; -end; - -end Control. diff --git a/test/run/Control.raz b/test/run/Control.raz new file mode 100644 index 0000000..314101b --- /dev/null +++ b/test/run/Control.raz @@ -0,0 +1,42 @@ +module Control; +import Out; + +proc main*; +var i, j, n: I64; u: U8; k: I8; +begin + for i := 1 to 5 do Out.int(i); end; Out.ln; + for i := 10 to 1 by -3 do Out.int(i); Out.str(" "); end; Out.ln; + for i := 0 to 10 by 4 do Out.int(i); Out.str(" "); end; Out.ln; + for i := 5 to 1 do Out.str("never"); end; + n := 0; + for u := 250 to 255 do n := n + 1; end; + Out.int(n); Out.ln; + n := 0; + for k := 120 to 127 by 3 do n := n + 1; end; + Out.int(n); Out.ln; + i := 0; + while i < 3 do + j := 0; + while true do + if j = 2 then break; end; + Out.int(i * 10 + j); Out.str(" "); + j := j + 1; + end; + i := i + 1; + end; + Out.ln; + i := 0; + repeat i := i + 1; if i = 4 then break; end; until i = 10; + Out.int(i); Out.ln; + for i := 1 to 4 do + if i = 1 then Out.str("one"); + elsif i = 2 then Out.str("two"); + elsif i = 3 then Out.str("three"); + else Out.str("many"); + end; + Out.str(" "); + end; + Out.ln; +end; + +end Control. diff --git a/test/run/Data.jed b/test/run/Data.jed deleted file mode 100644 index 2eb31b4..0000000 --- a/test/run/Data.jed +++ /dev/null @@ -1,72 +0,0 @@ -module Data; -import Out; - -type - Cell = record ch: U8; attr: U8; end; - Mixed = record a: U8; b: I64; c: U16; end; - Packed = packed record a: U8; b: I64; c: U16; end; - Node = record next: ^Node; val: I64; end; - Grid = [3][4]I32; - Pair = record x, y: I64; end; - -var - nodes: [5]Node; - grid: Grid; - gp: Pair; - -proc sum(p: ^Node): I64; -var s: I64; -begin - s := 0; - while p # nil do - s := s + p^.val; - p := p^.next; - end; - return s; -end; - -proc main*; -var - c: Cell; cells: [4]Cell; m: Mixed; i, j: I64; p, q: ^I64; arr: [8]I64; - s: []I64; pp: Pair; bp: ^U8; -begin - Out.int(SIZE(Cell)); Out.str(" "); - Out.int(SIZE(Mixed)); Out.str(" "); - Out.int(SIZE(Packed)); Out.str(" "); - Out.int(SIZE(Grid)); Out.str(" "); - Out.int(SIZE([]U8)); Out.ln; - c.ch := 'x'; c.attr := 7; - cells[2] := c; - Out.int(I64(cells[2].ch)); Out.str(" "); Out.int(I64(cells[2].attr)); Out.ln; - for i := 0 to 4 do - nodes[i].val := i * i; - if i < 4 then nodes[i].next := ADR(nodes[i + 1]); end; - end; - Out.int(sum(ADR(nodes[0]))); Out.ln; - for i := 0 to 2 do - for j := 0 to 3 do grid[i][j] := I32(i * 10 + j); end; - end; - Out.int(I64(grid[2][3])); Out.str(" "); Out.int(I64(grid[1][0])); Out.ln; - for i := 0 to 7 do arr[i] := i * 100; end; - p := ADR(arr[0]); - q := p + 5; - Out.int(q^); Out.str(" "); Out.int(q - p); Out.str(" "); Out.int(p[3]); Out.ln; - s := arr[2..6]; - Out.int(LEN(s)); Out.str(" "); Out.int(s[0]); Out.str(" "); Out.int(s[3]); Out.ln; - s := s[1..3]; - Out.int(LEN(s)); Out.str(" "); Out.int(s[0]); Out.ln; - s := p[1..3]; - Out.int(s[1]); Out.ln; - s := arr; - Out.int(LEN(s)); Out.ln; - pp.x := 3; pp.y := 4; - gp := pp; - pp.x := 99; - Out.int(gp.x); Out.str(" "); Out.int(gp.y); Out.ln; - m.a := 1; m.b := -2; m.c := 65535; - Out.int(m.b); Out.str(" "); Out.int(I64(m.c)); Out.ln; - bp := ^U8(ADR(m)); - Out.int(I64(ADR(m.c)) - I64(bp)); Out.ln; -end; - -end Data. diff --git a/test/run/Data.raz b/test/run/Data.raz new file mode 100644 index 0000000..2eb31b4 --- /dev/null +++ b/test/run/Data.raz @@ -0,0 +1,72 @@ +module Data; +import Out; + +type + Cell = record ch: U8; attr: U8; end; + Mixed = record a: U8; b: I64; c: U16; end; + Packed = packed record a: U8; b: I64; c: U16; end; + Node = record next: ^Node; val: I64; end; + Grid = [3][4]I32; + Pair = record x, y: I64; end; + +var + nodes: [5]Node; + grid: Grid; + gp: Pair; + +proc sum(p: ^Node): I64; +var s: I64; +begin + s := 0; + while p # nil do + s := s + p^.val; + p := p^.next; + end; + return s; +end; + +proc main*; +var + c: Cell; cells: [4]Cell; m: Mixed; i, j: I64; p, q: ^I64; arr: [8]I64; + s: []I64; pp: Pair; bp: ^U8; +begin + Out.int(SIZE(Cell)); Out.str(" "); + Out.int(SIZE(Mixed)); Out.str(" "); + Out.int(SIZE(Packed)); Out.str(" "); + Out.int(SIZE(Grid)); Out.str(" "); + Out.int(SIZE([]U8)); Out.ln; + c.ch := 'x'; c.attr := 7; + cells[2] := c; + Out.int(I64(cells[2].ch)); Out.str(" "); Out.int(I64(cells[2].attr)); Out.ln; + for i := 0 to 4 do + nodes[i].val := i * i; + if i < 4 then nodes[i].next := ADR(nodes[i + 1]); end; + end; + Out.int(sum(ADR(nodes[0]))); Out.ln; + for i := 0 to 2 do + for j := 0 to 3 do grid[i][j] := I32(i * 10 + j); end; + end; + Out.int(I64(grid[2][3])); Out.str(" "); Out.int(I64(grid[1][0])); Out.ln; + for i := 0 to 7 do arr[i] := i * 100; end; + p := ADR(arr[0]); + q := p + 5; + Out.int(q^); Out.str(" "); Out.int(q - p); Out.str(" "); Out.int(p[3]); Out.ln; + s := arr[2..6]; + Out.int(LEN(s)); Out.str(" "); Out.int(s[0]); Out.str(" "); Out.int(s[3]); Out.ln; + s := s[1..3]; + Out.int(LEN(s)); Out.str(" "); Out.int(s[0]); Out.ln; + s := p[1..3]; + Out.int(s[1]); Out.ln; + s := arr; + Out.int(LEN(s)); Out.ln; + pp.x := 3; pp.y := 4; + gp := pp; + pp.x := 99; + Out.int(gp.x); Out.str(" "); Out.int(gp.y); Out.ln; + m.a := 1; m.b := -2; m.c := 65535; + Out.int(m.b); Out.str(" "); Out.int(I64(m.c)); Out.ln; + bp := ^U8(ADR(m)); + Out.int(I64(ADR(m.c)) - I64(bp)); Out.ln; +end; + +end Data. diff --git a/test/run/Defers.jed b/test/run/Defers.jed deleted file mode 100644 index 388406b..0000000 --- a/test/run/Defers.jed +++ /dev/null @@ -1,71 +0,0 @@ -module Defers; -import Out; - -type Pair = record a, b: I64; end; - -var depth: I64; - -proc enter(s: []U8); -begin - Out.str(s); INC(depth); -end; - -proc leave(s: []U8); -begin - Out.str(s); DEC(depth); -end; - -proc real(x: F64): F64; -begin - enter("("); - defer leave(")"); - return x * 2.0; -end; - -proc pair(n: I64): Pair; -var p: Pair; -begin - defer p.a := 99; - p.a := n; p.b := n + 1; - return p; -end; - -proc begin_end(i: I64); -var k: I64; -begin - defer for k := 1 to i do Out.str("*"); end; - if i = 1 then return; end; - Out.str("+"); -end; - -proc nested; -var i, j: I64; -begin - for i := 1 to 2 do - enter("["); - defer leave("]"); - defer begin_end(i); - j := 0; - while true do - defer Out.str("."); - INC(j); - if j = 3 then break; end; - end; - end; -end; - -proc main*; -var p: Pair; -begin - Out.int(I64(real(1.5) * 10.0)); Out.ln; - p := pair(5); - Out.int(p.a); Out.int(p.b); Out.ln; - nested; - Out.ln; - Out.int(depth); Out.ln; -end; - -begin - defer Out.str("body done\n"); - Out.str("body "); -end Defers. diff --git a/test/run/Defers.raz b/test/run/Defers.raz new file mode 100644 index 0000000..388406b --- /dev/null +++ b/test/run/Defers.raz @@ -0,0 +1,71 @@ +module Defers; +import Out; + +type Pair = record a, b: I64; end; + +var depth: I64; + +proc enter(s: []U8); +begin + Out.str(s); INC(depth); +end; + +proc leave(s: []U8); +begin + Out.str(s); DEC(depth); +end; + +proc real(x: F64): F64; +begin + enter("("); + defer leave(")"); + return x * 2.0; +end; + +proc pair(n: I64): Pair; +var p: Pair; +begin + defer p.a := 99; + p.a := n; p.b := n + 1; + return p; +end; + +proc begin_end(i: I64); +var k: I64; +begin + defer for k := 1 to i do Out.str("*"); end; + if i = 1 then return; end; + Out.str("+"); +end; + +proc nested; +var i, j: I64; +begin + for i := 1 to 2 do + enter("["); + defer leave("]"); + defer begin_end(i); + j := 0; + while true do + defer Out.str("."); + INC(j); + if j = 3 then break; end; + end; + end; +end; + +proc main*; +var p: Pair; +begin + Out.int(I64(real(1.5) * 10.0)); Out.ln; + p := pair(5); + Out.int(p.a); Out.int(p.b); Out.ln; + nested; + Out.ln; + Out.int(depth); Out.ln; +end; + +begin + defer Out.str("body done\n"); + Out.str("body "); +end Defers. diff --git a/test/run/Edge.jed b/test/run/Edge.jed deleted file mode 100644 index 6870a5e..0000000 --- a/test/run/Edge.jed +++ /dev/null @@ -1,64 +0,0 @@ -module Edge; -import Out; - -type - Inner = record vals: [4]I64; name: []U8; end; - Outer = record items: [3]Inner; n: I64; end; - -var g: Outer; calls: I64; - -(* rsp mod 16 at the call, as the callee sees it after its return - address: always 8 when the caller keeps the stack aligned *) -proc rspmod: I64; -code 48H, 89H, 0E0H, (* mov rax, rsp *) - 48H, 83H, 0E0H, 0FH, (* and rax, 15 *) - 0C3H; - -proc next: I64; -begin - calls := calls + 1; - return calls; -end; - -proc setall(var o: Outer; v: I64); -var i, j: I64; -begin - for i := 0 to 2 do - for j := 0 to 3 do o.items[i].vals[j] := v + i * 10 + j; end; - o.items[i].name := "item"; - end; - o.n := 3; -end; - -proc sumInner(xs: []Inner): I64; -var i, j, s: I64; -begin - s := 0; - for i := 0 to LEN(xs) - 1 do - for j := 0 to 3 do s := s + xs[i].vals[j]; end; - end; - return s; -end; - -proc main*; -var a: [5]I64; i, r: I64; o: Outer; pa: ^[5]I64; -begin - r := rspmod() + (1 + (2 + (3 + rspmod()))); - Out.int(r); Out.ln; - a[next()] := next() * 10; - Out.int(a[1]); Out.str(" "); Out.int(calls); Out.ln; - setall(g, 100); - Out.int(g.items[2].vals[3]); Out.str(" "); Out.str(g.items[1].name); Out.ln; - o := g; - o.items[0].vals[0] := -1; - Out.int(g.items[0].vals[0]); Out.str(" "); Out.int(o.items[0].vals[0]); Out.ln; - Out.int(sumInner(g.items)); Out.str(" "); Out.int(sumInner(g.items[1..3])); Out.ln; - pa := ADR(a); - pa^[4] := 44; - Out.int(a[4]); Out.str(" "); Out.int(LEN(pa^)); Out.ln; - i := 2; - g.items[i].vals[i + 1] := g.items[i - 1].vals[i] + 1000; - Out.int(g.items[2].vals[3]); Out.ln; -end; - -end Edge. diff --git a/test/run/Edge.raz b/test/run/Edge.raz new file mode 100644 index 0000000..6870a5e --- /dev/null +++ b/test/run/Edge.raz @@ -0,0 +1,64 @@ +module Edge; +import Out; + +type + Inner = record vals: [4]I64; name: []U8; end; + Outer = record items: [3]Inner; n: I64; end; + +var g: Outer; calls: I64; + +(* rsp mod 16 at the call, as the callee sees it after its return + address: always 8 when the caller keeps the stack aligned *) +proc rspmod: I64; +code 48H, 89H, 0E0H, (* mov rax, rsp *) + 48H, 83H, 0E0H, 0FH, (* and rax, 15 *) + 0C3H; + +proc next: I64; +begin + calls := calls + 1; + return calls; +end; + +proc setall(var o: Outer; v: I64); +var i, j: I64; +begin + for i := 0 to 2 do + for j := 0 to 3 do o.items[i].vals[j] := v + i * 10 + j; end; + o.items[i].name := "item"; + end; + o.n := 3; +end; + +proc sumInner(xs: []Inner): I64; +var i, j, s: I64; +begin + s := 0; + for i := 0 to LEN(xs) - 1 do + for j := 0 to 3 do s := s + xs[i].vals[j]; end; + end; + return s; +end; + +proc main*; +var a: [5]I64; i, r: I64; o: Outer; pa: ^[5]I64; +begin + r := rspmod() + (1 + (2 + (3 + rspmod()))); + Out.int(r); Out.ln; + a[next()] := next() * 10; + Out.int(a[1]); Out.str(" "); Out.int(calls); Out.ln; + setall(g, 100); + Out.int(g.items[2].vals[3]); Out.str(" "); Out.str(g.items[1].name); Out.ln; + o := g; + o.items[0].vals[0] := -1; + Out.int(g.items[0].vals[0]); Out.str(" "); Out.int(o.items[0].vals[0]); Out.ln; + Out.int(sumInner(g.items)); Out.str(" "); Out.int(sumInner(g.items[1..3])); Out.ln; + pa := ADR(a); + pa^[4] := 44; + Out.int(a[4]); Out.str(" "); Out.int(LEN(pa^)); Out.ln; + i := 2; + g.items[i].vals[i + 1] := g.items[i - 1].vals[i] + 1000; + Out.int(g.items[2].vals[3]); Out.ln; +end; + +end Edge. diff --git a/test/run/Extern.jed b/test/run/Extern.jed deleted file mode 100644 index e8d56ba..0000000 --- a/test/run/Extern.jed +++ /dev/null @@ -1,65 +0,0 @@ -(* Calling C: arguments in registers and on the stack, reals, ..., - C variables, jed procedures as C's callbacks. *) -module Extern; -import Out, C; -link "libm.so.6"; - -extern proc strlen(s: ^U8): U64; -extern proc qsort(base: ^U8; n, size: U64; cmp: proc(a, b: ^I64): I32); -extern proc snprintf(buf: ^U8; n: U64; format: ^U8; ...): I32; -extern proc atoi(s: ^U8): I32; -extern proc abs(n: I32): I32; -extern proc sqrt(x: F64): F64; -extern proc getenv(name: ^U8): ^U8; -extern proc setenv(name, value: ^U8; overwrite: I32): I32; -extern var environ: ^^U8; -extern var optind: I32; - -var calls: I64; - -proc cmp(a, b: ^I64): I32; -begin - INC(calls); - if a^ < b^ then return -1; elsif a^ > b^ then return 1; end; - return 0; -end; - -proc main*; -var - a: [6]I64; i: I64; buf: [64]U8; n: I32; - len: proc(s: ^U8): U64; e: ^^U8; -begin - Out.int(I64(strlen("hello"))); Out.ln; - len := strlen; - Out.int(I64(len("hi there"))); Out.ln; - Out.int(I64(abs(-7)) + I64(atoi("35"))); Out.ln; - Out.int(I64(sqrt(2.0) * 1000.0)); Out.ln; - - a := [5, -3, 9, 0, 12, 1]; - qsort(^U8(ADR(a)), 6, 8, cmp); - for i := 0 to 5 do Out.int(a[i]); Out.char(' '); end; - Out.ln; - if calls > 0 then Out.str("cmp called\n"); end; - - (* nine arguments after the format: some go on the stack *) - n := snprintf(ADR(buf[0]), 64, "%d %d %d %d %d %d %d %s|%.3f %g", - 1, 2, 3, 4, 5, 6, 7, "eight", 3.14159, 0.5); - Out.str(buf[0..I64(n)]); Out.ln; - - setenv("JED_TEST", "yes", 1); - Out.int(I64(strlen(getenv("JED_TEST")))); Out.ln; - e := environ; - i := 0; - while e^ # nil do INC(i); e := e + 1; end; - if i > 0 then Out.str("environ has entries\n"); end; - Out.int(I64(optind)); Out.ln; - optind := 5; - Out.int(I64(optind)); Out.ln; - - Out.flush; - C.printf("printf %d %s %.1f\n", -42, "too", 2.5); - C.fflush(C.stdout); - Out.str("done\n"); -end; - -end Extern. diff --git a/test/run/Extern.raz b/test/run/Extern.raz new file mode 100644 index 0000000..cb47289 --- /dev/null +++ b/test/run/Extern.raz @@ -0,0 +1,65 @@ +(* Calling C: arguments in registers and on the stack, reals, ..., + C variables, raz procedures as C's callbacks. *) +module Extern; +import Out, C; +link "libm.so.6"; + +extern proc strlen(s: ^U8): U64; +extern proc qsort(base: ^U8; n, size: U64; cmp: proc(a, b: ^I64): I32); +extern proc snprintf(buf: ^U8; n: U64; format: ^U8; ...): I32; +extern proc atoi(s: ^U8): I32; +extern proc abs(n: I32): I32; +extern proc sqrt(x: F64): F64; +extern proc getenv(name: ^U8): ^U8; +extern proc setenv(name, value: ^U8; overwrite: I32): I32; +extern var environ: ^^U8; +extern var optind: I32; + +var calls: I64; + +proc cmp(a, b: ^I64): I32; +begin + INC(calls); + if a^ < b^ then return -1; elsif a^ > b^ then return 1; end; + return 0; +end; + +proc main*; +var + a: [6]I64; i: I64; buf: [64]U8; n: I32; + len: proc(s: ^U8): U64; e: ^^U8; +begin + Out.int(I64(strlen("hello"))); Out.ln; + len := strlen; + Out.int(I64(len("hi there"))); Out.ln; + Out.int(I64(abs(-7)) + I64(atoi("35"))); Out.ln; + Out.int(I64(sqrt(2.0) * 1000.0)); Out.ln; + + a := [5, -3, 9, 0, 12, 1]; + qsort(^U8(ADR(a)), 6, 8, cmp); + for i := 0 to 5 do Out.int(a[i]); Out.char(' '); end; + Out.ln; + if calls > 0 then Out.str("cmp called\n"); end; + + (* nine arguments after the format: some go on the stack *) + n := snprintf(ADR(buf[0]), 64, "%d %d %d %d %d %d %d %s|%.3f %g", + 1, 2, 3, 4, 5, 6, 7, "eight", 3.14159, 0.5); + Out.str(buf[0..I64(n)]); Out.ln; + + setenv("RAZ_TEST", "yes", 1); + Out.int(I64(strlen(getenv("RAZ_TEST")))); Out.ln; + e := environ; + i := 0; + while e^ # nil do INC(i); e := e + 1; end; + if i > 0 then Out.str("environ has entries\n"); end; + Out.int(I64(optind)); Out.ln; + optind := 5; + Out.int(I64(optind)); Out.ln; + + Out.flush; + C.printf("printf %d %s %.1f\n", -42, "too", 2.5); + C.fflush(C.stdout); + Out.str("done\n"); +end; + +end Extern. diff --git a/test/run/Generic.jed b/test/run/Generic.jed deleted file mode 100644 index e8a1bf0..0000000 --- a/test/run/Generic.jed +++ /dev/null @@ -1,30 +0,0 @@ -module Generic; -import Fmt, Buf, Str, Heap, Stack, Ints := List(I64), More := List(I64), Strs := List([]U8); - -proc twice(x: I64): I64; begin return x * 2; end; - -proc main*; -var l: Strs.List; v: I64; s: []U8; ok: BOOL; b: Buf.Buf; n: ^Ints.Node; -begin - ok := Ints.push(ADR(Stack.s), 7); - ok := More.push(ADR(Stack.s), 8); - Fmt.print("{} {} {}\n", [Fmt.int(Stack.top()), Fmt.int(Stack.s.len), Fmt.bool(ok)]); - n := Stack.s.head; - v, ok := Ints.pop(ADR(Stack.s)); - Fmt.print("{} {}\n", [Fmt.int(v), Fmt.int(Stack.s.len)]); - Strs.init(ADR(l), Heap.heap); - ok := Strs.push(ADR(l), "b"); - ok := Strs.push(ADR(l), "a"); - s, ok := Strs.pop(ADR(l)); - Fmt.print("{}{}{}\n", [Fmt.str(s), Fmt.str(l.head^.val), Fmt.bool(ok)]); - s, ok := Strs.pop(ADR(l)); - s, ok := Strs.pop(ADR(l)); - Fmt.print("[{}] {}\n", [Fmt.str(s), Fmt.bool(ok)]); - Buf.init(ADR(b), Heap.heap); - for v := 1 to 40 do Fmt.write(ADR(b), "{},", [Fmt.int(v * v)]); end; - Fmt.print("{} {} {}\n", [Fmt.int(b.len), Fmt.int(Str.find(Buf.bytes(ADR(b)), "1600")), Fmt.int(Str.cmp("ab", "b"))]); - Buf.done(ADR(b)); - Fmt.print("{{ {} }} {}{}\n", [Fmt.hex(48879), Fmt.char('x'), Fmt.uint(0FFFFFFFFFFFFFFFFH)]); -end; - -end Generic. diff --git a/test/run/Generic.raz b/test/run/Generic.raz new file mode 100644 index 0000000..e8a1bf0 --- /dev/null +++ b/test/run/Generic.raz @@ -0,0 +1,30 @@ +module Generic; +import Fmt, Buf, Str, Heap, Stack, Ints := List(I64), More := List(I64), Strs := List([]U8); + +proc twice(x: I64): I64; begin return x * 2; end; + +proc main*; +var l: Strs.List; v: I64; s: []U8; ok: BOOL; b: Buf.Buf; n: ^Ints.Node; +begin + ok := Ints.push(ADR(Stack.s), 7); + ok := More.push(ADR(Stack.s), 8); + Fmt.print("{} {} {}\n", [Fmt.int(Stack.top()), Fmt.int(Stack.s.len), Fmt.bool(ok)]); + n := Stack.s.head; + v, ok := Ints.pop(ADR(Stack.s)); + Fmt.print("{} {}\n", [Fmt.int(v), Fmt.int(Stack.s.len)]); + Strs.init(ADR(l), Heap.heap); + ok := Strs.push(ADR(l), "b"); + ok := Strs.push(ADR(l), "a"); + s, ok := Strs.pop(ADR(l)); + Fmt.print("{}{}{}\n", [Fmt.str(s), Fmt.str(l.head^.val), Fmt.bool(ok)]); + s, ok := Strs.pop(ADR(l)); + s, ok := Strs.pop(ADR(l)); + Fmt.print("[{}] {}\n", [Fmt.str(s), Fmt.bool(ok)]); + Buf.init(ADR(b), Heap.heap); + for v := 1 to 40 do Fmt.write(ADR(b), "{},", [Fmt.int(v * v)]); end; + Fmt.print("{} {} {}\n", [Fmt.int(b.len), Fmt.int(Str.find(Buf.bytes(ADR(b)), "1600")), Fmt.int(Str.cmp("ab", "b"))]); + Buf.done(ADR(b)); + Fmt.print("{{ {} }} {}{}\n", [Fmt.hex(48879), Fmt.char('x'), Fmt.uint(0FFFFFFFFFFFFFFFFH)]); +end; + +end Generic. diff --git a/test/run/HeapCheck.jed b/test/run/HeapCheck.jed deleted file mode 100644 index ac430ad..0000000 --- a/test/run/HeapCheck.jed +++ /dev/null @@ -1,34 +0,0 @@ -(* The heap refuses bad sizes and alignments, and stops the program - when a block is freed twice. *) -module HeapCheck; -import Out, Heap, Mem; - -proc show(p: ^U8); -begin - if p = nil then Out.str("nil\n"); else Out.str("a block\n"); end; -end; - -proc main*; -var p, q: ^U8; -begin - show(Mem.alloc(Heap.heap, -1, 8)); - show(Mem.alloc(Heap.heap, 1 shl 60, 8)); - show(Mem.alloc(Heap.heap, 7FFFFFFFFFFFFFF0H, 8)); - show(Mem.alloc(Heap.heap, 10, 3)); - show(Mem.alloc(Heap.heap, 10, 0)); - show(Mem.alloc(Heap.heap, 10, 8192)); - p := Mem.alloc(Heap.heap, 10, 64); - show(p); - if I64(p) mod 64 = 0 then Out.str("aligned\n"); end; - Mem.free(Heap.heap, p); - q := Mem.alloc(Heap.heap, 100000, 8); - show(q); - Mem.free(Heap.heap, q); - p := Mem.alloc(Heap.heap, 24, 8); - Mem.free(Heap.heap, p); - Out.str("freeing it again\n"); - Mem.free(Heap.heap, p); - Out.str("not reached\n"); -end; - -end HeapCheck. diff --git a/test/run/HeapCheck.raz b/test/run/HeapCheck.raz new file mode 100644 index 0000000..ac430ad --- /dev/null +++ b/test/run/HeapCheck.raz @@ -0,0 +1,34 @@ +(* The heap refuses bad sizes and alignments, and stops the program + when a block is freed twice. *) +module HeapCheck; +import Out, Heap, Mem; + +proc show(p: ^U8); +begin + if p = nil then Out.str("nil\n"); else Out.str("a block\n"); end; +end; + +proc main*; +var p, q: ^U8; +begin + show(Mem.alloc(Heap.heap, -1, 8)); + show(Mem.alloc(Heap.heap, 1 shl 60, 8)); + show(Mem.alloc(Heap.heap, 7FFFFFFFFFFFFFF0H, 8)); + show(Mem.alloc(Heap.heap, 10, 3)); + show(Mem.alloc(Heap.heap, 10, 0)); + show(Mem.alloc(Heap.heap, 10, 8192)); + p := Mem.alloc(Heap.heap, 10, 64); + show(p); + if I64(p) mod 64 = 0 then Out.str("aligned\n"); end; + Mem.free(Heap.heap, p); + q := Mem.alloc(Heap.heap, 100000, 8); + show(q); + Mem.free(Heap.heap, q); + p := Mem.alloc(Heap.heap, 24, 8); + Mem.free(Heap.heap, p); + Out.str("freeing it again\n"); + Mem.free(Heap.heap, p); + Out.str("not reached\n"); +end; + +end HeapCheck. diff --git a/test/run/HeapStray.jed b/test/run/HeapStray.jed deleted file mode 100644 index c8f69f9..0000000 --- a/test/run/HeapStray.jed +++ /dev/null @@ -1,14 +0,0 @@ -(* Freeing what the heap never gave out stops the program. *) -module HeapStray; -import Out, Heap, Mem; - -var a: [4]I64; - -proc main*; -begin - Out.str("freeing a stray pointer\n"); - Mem.free(Heap.heap, ^U8(ADR(a[2]))); - Out.str("not reached\n"); -end; - -end HeapStray. diff --git a/test/run/HeapStray.raz b/test/run/HeapStray.raz new file mode 100644 index 0000000..c8f69f9 --- /dev/null +++ b/test/run/HeapStray.raz @@ -0,0 +1,14 @@ +(* Freeing what the heap never gave out stops the program. *) +module HeapStray; +import Out, Heap, Mem; + +var a: [4]I64; + +proc main*; +begin + Out.str("freeing a stray pointer\n"); + Mem.free(Heap.heap, ^U8(ADR(a[2]))); + Out.str("not reached\n"); +end; + +end HeapStray. diff --git a/test/run/Kinds.jed b/test/run/Kinds.jed deleted file mode 100644 index c5c6d47..0000000 --- a/test/run/Kinds.jed +++ /dev/null @@ -1,95 +0,0 @@ -module Kinds; -import Out; - -type - Color* = (red, green, blue, black); - Colors* = set of Color; - Cell = record ch: U8; attr: U8; fg: Color; end; - Point = record x, y: I64; name: []U8; end; - Line = record a, b: Point; end; - -var log: [8]U8; nlog: I64; - -proc note(c: U8); -begin - log[nlog] := c; - INC(nlog); -end; - -proc show(s: Colors); -var c: Color; -begin - for c := red to black do - if c in s then Out.int(I64(c)); end; - end; - Out.str(" "); -end; - -proc name(c: Color): []U8; -begin - match c of - | red: return "red"; - | green: return "green"; - | else: return "other"; - end; -end; - -proc deferred(n: I64): I64; -var i: I64; -begin - defer note('A'); - defer note('B'); - for i := 1 to 3 do - defer note('L'); - if i = 2 then break; end; - end; - if n > 0 then - defer note('C'); - return n * 10; - end; - note('D'); - return -1; -end; - -proc mid(a, b: Point): Point; -begin - return {x: (a.x + b.x) div 2, y: (a.y + b.y) div 2, name: "mid"}; -end; - -proc main*; -var s, t: Colors; c: Color; cell: Cell; p: Point; l: Line; r: I64; one: Colors; -begin - s := {red, blue}; - t := {blue, black}; - show(s + t); show(s * t); show(s - t); show({}); - if red in s then Out.str("in "); end; - if not (green in s) then Out.str("out "); end; - if s * t <= t then Out.str("sub "); end; - if s + t >= s then Out.str("sup "); end; - if s # t then Out.str("ne "); end; - if s = {blue, red} then Out.str("eq"); end; - Out.ln; - c := green; - one := {c, black}; - show(one); - Out.int(I64(U8(one))); Out.str(" "); - Out.int(SIZE(Colors)); Out.str(" "); - Out.int(I64(Color(2))); Out.str(" "); - if c < blue then Out.str("lt "); end; - Out.str(name(c)); Out.str(" "); Out.str(name(black)); Out.ln; - cell := {ch: 'x', fg: blue}; - Out.int(I64(cell.ch)); Out.str(" "); Out.int(I64(cell.attr)); Out.str(" "); Out.int(I64(cell.fg)); Out.ln; - p := mid({x: 2, y: 4}, {y: 10, x: 6}); - Out.int(p.x); Out.int(p.y); Out.str(p.name); Out.ln; - l := {a: {x: 1, y: 2}, b: p}; - Out.int(l.a.y); Out.int(l.b.x); Out.ln; - r := deferred(5); - Out.int(r); Out.str(" "); Out.str(log[0..nlog]); Out.ln; - nlog := 0; - r := deferred(0); - Out.int(r); Out.str(" "); Out.str(log[0..nlog]); Out.ln; - Out.int(I64(Color(I64(c) + 2))); - c := Color(nlog); -end; - -end Kinds. diff --git a/test/run/Kinds.raz b/test/run/Kinds.raz new file mode 100644 index 0000000..c5c6d47 --- /dev/null +++ b/test/run/Kinds.raz @@ -0,0 +1,95 @@ +module Kinds; +import Out; + +type + Color* = (red, green, blue, black); + Colors* = set of Color; + Cell = record ch: U8; attr: U8; fg: Color; end; + Point = record x, y: I64; name: []U8; end; + Line = record a, b: Point; end; + +var log: [8]U8; nlog: I64; + +proc note(c: U8); +begin + log[nlog] := c; + INC(nlog); +end; + +proc show(s: Colors); +var c: Color; +begin + for c := red to black do + if c in s then Out.int(I64(c)); end; + end; + Out.str(" "); +end; + +proc name(c: Color): []U8; +begin + match c of + | red: return "red"; + | green: return "green"; + | else: return "other"; + end; +end; + +proc deferred(n: I64): I64; +var i: I64; +begin + defer note('A'); + defer note('B'); + for i := 1 to 3 do + defer note('L'); + if i = 2 then break; end; + end; + if n > 0 then + defer note('C'); + return n * 10; + end; + note('D'); + return -1; +end; + +proc mid(a, b: Point): Point; +begin + return {x: (a.x + b.x) div 2, y: (a.y + b.y) div 2, name: "mid"}; +end; + +proc main*; +var s, t: Colors; c: Color; cell: Cell; p: Point; l: Line; r: I64; one: Colors; +begin + s := {red, blue}; + t := {blue, black}; + show(s + t); show(s * t); show(s - t); show({}); + if red in s then Out.str("in "); end; + if not (green in s) then Out.str("out "); end; + if s * t <= t then Out.str("sub "); end; + if s + t >= s then Out.str("sup "); end; + if s # t then Out.str("ne "); end; + if s = {blue, red} then Out.str("eq"); end; + Out.ln; + c := green; + one := {c, black}; + show(one); + Out.int(I64(U8(one))); Out.str(" "); + Out.int(SIZE(Colors)); Out.str(" "); + Out.int(I64(Color(2))); Out.str(" "); + if c < blue then Out.str("lt "); end; + Out.str(name(c)); Out.str(" "); Out.str(name(black)); Out.ln; + cell := {ch: 'x', fg: blue}; + Out.int(I64(cell.ch)); Out.str(" "); Out.int(I64(cell.attr)); Out.str(" "); Out.int(I64(cell.fg)); Out.ln; + p := mid({x: 2, y: 4}, {y: 10, x: 6}); + Out.int(p.x); Out.int(p.y); Out.str(p.name); Out.ln; + l := {a: {x: 1, y: 2}, b: p}; + Out.int(l.a.y); Out.int(l.b.x); Out.ln; + r := deferred(5); + Out.int(r); Out.str(" "); Out.str(log[0..nlog]); Out.ln; + nlog := 0; + r := deferred(0); + Out.int(r); Out.str(" "); Out.str(log[0..nlog]); Out.ln; + Out.int(I64(Color(I64(c) + 2))); + c := Color(nlog); +end; + +end Kinds. diff --git a/test/run/Procs.jed b/test/run/Procs.jed deleted file mode 100644 index a5b8313..0000000 --- a/test/run/Procs.jed +++ /dev/null @@ -1,117 +0,0 @@ -module Procs; -import Out; - -type - Pair = record x, y: I64; end; - Op = proc(a, b: I64): I64; - Big = record a: [10]I64; end; - -proc even(n: I64): BOOL; forward; - -proc odd(n: I64): BOOL; -begin - if n = 0 then return false; end; - return even(n - 1); -end; - -proc even(n: I64): BOOL; -begin - if n = 0 then return true; end; - return odd(n - 1); -end; - -proc swap(var a, b: I64); -var t: I64; -begin - t := a; a := b; b := t; -end; - -proc bump(p: Pair): Pair; -begin - p.x := p.x + 1; - p.y := p.y + 1; - return p; -end; - -proc add(a, b: I64): I64; begin return a + b; end; -proc mul(a, b: I64): I64; begin return a * b; end; - -proc apply(f: Op; a, b: I64): I64; -begin - return f(a, b); -end; - -proc many(a, b, c, d, e, f, g, h: I64; x: F64; i: I64; y: F64): I64; -begin - return a + 2 * b + 3 * c + 4 * d + 5 * e + 6 * f + 7 * g + 8 * h + I64(x) * 100 + 9 * i + I64(y) * 1000; -end; - -proc fact(n: I64): I64; -begin - if n <= 1 then return 1; end; - return n * fact(n - 1); -end; - -proc fill(var b: Big; v: I64); -var i: I64; -begin - for i := 0 to 9 do b.a[i] := v + i; end; -end; - -proc total(b: Big): I64; -var i, s: I64; -begin - s := 0; - for i := 0 to 9 do s := s + b.a[i]; end; - b.a[0] := 1000; - return s; -end; - -proc noresult(n: I64): I64; -begin - if n > 100 then return 1; end; -end; - -proc mk(n: I64): Big; -var b: Big; -begin - fill(b, n); - return b; -end; - -proc mkzero(n: I64): Big; -begin -end; - -proc fsum(a, b: F64): F64; -begin - return a + b; -end; - -proc main*: I64; -var a, b: I64; p, q: Pair; f: Op; bg: Big; -begin - if even(10) and odd(7) and not even(3) then Out.str("parity ok"); Out.ln; end; - a := 1; b := 2; - swap(a, b); - Out.int(a); Out.int(b); Out.ln; - p.x := 10; p.y := 20; - q := bump(p); - Out.int(p.x); Out.str(" "); Out.int(q.x); Out.str(" "); Out.int(q.y); Out.ln; - Out.int(bump(bump(p)).y); Out.ln; - f := add; - Out.int(apply(f, 3, 4)); Out.str(" "); Out.int(apply(mul, 3, 4)); Out.ln; - if f = add then Out.str("same"); Out.ln; end; - f := nil; - if f = nil then Out.str("nil"); Out.ln; end; - Out.int(many(1, 1, 1, 1, 1, 1, 1, 1, 2.5, 1, 3.9)); Out.ln; - Out.int(fact(20)); Out.ln; - fill(bg, 5); - Out.int(total(bg)); Out.str(" "); Out.int(bg.a[0]); Out.ln; - Out.int(noresult(5)); Out.ln; - Out.int(mk(7).a[9]); Out.str(" "); Out.int(mkzero(1).a[3]); Out.ln; - Out.int(I64(fsum(1.25, 2.5) * 4.0)); Out.ln; - return 7; -end; - -end Procs. diff --git a/test/run/Procs.raz b/test/run/Procs.raz new file mode 100644 index 0000000..a5b8313 --- /dev/null +++ b/test/run/Procs.raz @@ -0,0 +1,117 @@ +module Procs; +import Out; + +type + Pair = record x, y: I64; end; + Op = proc(a, b: I64): I64; + Big = record a: [10]I64; end; + +proc even(n: I64): BOOL; forward; + +proc odd(n: I64): BOOL; +begin + if n = 0 then return false; end; + return even(n - 1); +end; + +proc even(n: I64): BOOL; +begin + if n = 0 then return true; end; + return odd(n - 1); +end; + +proc swap(var a, b: I64); +var t: I64; +begin + t := a; a := b; b := t; +end; + +proc bump(p: Pair): Pair; +begin + p.x := p.x + 1; + p.y := p.y + 1; + return p; +end; + +proc add(a, b: I64): I64; begin return a + b; end; +proc mul(a, b: I64): I64; begin return a * b; end; + +proc apply(f: Op; a, b: I64): I64; +begin + return f(a, b); +end; + +proc many(a, b, c, d, e, f, g, h: I64; x: F64; i: I64; y: F64): I64; +begin + return a + 2 * b + 3 * c + 4 * d + 5 * e + 6 * f + 7 * g + 8 * h + I64(x) * 100 + 9 * i + I64(y) * 1000; +end; + +proc fact(n: I64): I64; +begin + if n <= 1 then return 1; end; + return n * fact(n - 1); +end; + +proc fill(var b: Big; v: I64); +var i: I64; +begin + for i := 0 to 9 do b.a[i] := v + i; end; +end; + +proc total(b: Big): I64; +var i, s: I64; +begin + s := 0; + for i := 0 to 9 do s := s + b.a[i]; end; + b.a[0] := 1000; + return s; +end; + +proc noresult(n: I64): I64; +begin + if n > 100 then return 1; end; +end; + +proc mk(n: I64): Big; +var b: Big; +begin + fill(b, n); + return b; +end; + +proc mkzero(n: I64): Big; +begin +end; + +proc fsum(a, b: F64): F64; +begin + return a + b; +end; + +proc main*: I64; +var a, b: I64; p, q: Pair; f: Op; bg: Big; +begin + if even(10) and odd(7) and not even(3) then Out.str("parity ok"); Out.ln; end; + a := 1; b := 2; + swap(a, b); + Out.int(a); Out.int(b); Out.ln; + p.x := 10; p.y := 20; + q := bump(p); + Out.int(p.x); Out.str(" "); Out.int(q.x); Out.str(" "); Out.int(q.y); Out.ln; + Out.int(bump(bump(p)).y); Out.ln; + f := add; + Out.int(apply(f, 3, 4)); Out.str(" "); Out.int(apply(mul, 3, 4)); Out.ln; + if f = add then Out.str("same"); Out.ln; end; + f := nil; + if f = nil then Out.str("nil"); Out.ln; end; + Out.int(many(1, 1, 1, 1, 1, 1, 1, 1, 2.5, 1, 3.9)); Out.ln; + Out.int(fact(20)); Out.ln; + fill(bg, 5); + Out.int(total(bg)); Out.str(" "); Out.int(bg.a[0]); Out.ln; + Out.int(noresult(5)); Out.ln; + Out.int(mk(7).a[9]); Out.str(" "); Out.int(mkzero(1).a[3]); Out.ln; + Out.int(I64(fsum(1.25, 2.5) * 4.0)); Out.ln; + return 7; +end; + +end Procs. diff --git a/test/run/Results.jed b/test/run/Results.jed deleted file mode 100644 index ad3b514..0000000 --- a/test/run/Results.jed +++ /dev/null @@ -1,79 +0,0 @@ -module Results; -import Out; - -const - NotFound*: ERROR = "not found"; - Empty: ERROR = "empty"; - Other: ERROR = "not found"; - -type Pair = record a, b: I64; end; - -var table: [4]I64; g: Pair; - -proc divmod(a, b: I64): (I64, I64); -begin - return a div b, a mod b; -end; - -proc find(key: I64): (I64, ERROR); -var i: I64; -begin - for i := 0 to 3 do - if table[i] = key then return i, nil; end; - end; - return -1, NotFound; -end; - -proc mixed(x: F64): (F64, []U8, Pair, BOOL); -var p: Pair; -begin - p.a := 1; p.b := 2; - return x * 2.0, "two", p, true; -end; - -proc minmax(a, b: I64): (I64, I64); -code 48H, 89H, 0F8H, (* mov rax, rdi *) - 48H, 89H, 0F2H, (* mov rdx, rsi *) - 48H, 39H, 0F7H, (* cmp rdi, rsi *) - 7EH, 06H, (* jle +6 *) - 48H, 89H, 0F0H, (* mov rax, rsi *) - 48H, 89H, 0FAH, (* mov rdx, rdi *) - 0C3H; - -proc nothing: (I64, ERROR); -begin -end; - -proc main*; -var q, r, i: I64; e: ERROR; x: F64; s: []U8; p: Pair; ok: BOOL; a: [3]I64; u: U8; -begin - q, r := divmod(17, 5); - Out.int(q); Out.str(" "); Out.int(r); Out.ln; - table := [10, 20, 30, 40]; - i, e := find(30); - Out.int(i); if e = nil then Out.str(" nil"); end; Out.ln; - i, e := find(7); - Out.int(i); Out.str(" "); Out.str(MSG(e)); - if e = NotFound then Out.str(" is NotFound"); end; - if e # Other then Out.str(", not Other"); end; - if e # Empty then Out.str(", not Empty"); end; - Out.ln; - Out.str("["); Out.str(MSG(nil)); Out.str("]"); Out.ln; - x, s, p, ok := mixed(1.5); - Out.int(I64(x * 10.0)); Out.str(" "); Out.str(s); Out.str(" "); Out.int(p.b); - if ok then Out.str(" ok"); end; Out.ln; - a[1], g.b := divmod(9, 4); - Out.int(a[1]); Out.str(" "); Out.int(g.b); Out.ln; - q, r := minmax(9, 3); - Out.int(q); Out.int(r); Out.ln; - divmod(1, 1); - i, e := nothing(); - Out.int(i); if e = nil then Out.str(" zero"); end; Out.ln; - i := 5; - INC(i); INC(i, 10); DEC(i, 2); - a[2] := 7; DEC(a[2]); - u := 255; INC(u); - Out.int(i); Out.str(" "); Out.int(a[2]); Out.str(" "); Out.int(I64(u)); Out.ln; -end; - -end Results. diff --git a/test/run/Results.raz b/test/run/Results.raz new file mode 100644 index 0000000..ad3b514 --- /dev/null +++ b/test/run/Results.raz @@ -0,0 +1,79 @@ +module Results; +import Out; + +const + NotFound*: ERROR = "not found"; + Empty: ERROR = "empty"; + Other: ERROR = "not found"; + +type Pair = record a, b: I64; end; + +var table: [4]I64; g: Pair; + +proc divmod(a, b: I64): (I64, I64); +begin + return a div b, a mod b; +end; + +proc find(key: I64): (I64, ERROR); +var i: I64; +begin + for i := 0 to 3 do + if table[i] = key then return i, nil; end; + end; + return -1, NotFound; +end; + +proc mixed(x: F64): (F64, []U8, Pair, BOOL); +var p: Pair; +begin + p.a := 1; p.b := 2; + return x * 2.0, "two", p, true; +end; + +proc minmax(a, b: I64): (I64, I64); +code 48H, 89H, 0F8H, (* mov rax, rdi *) + 48H, 89H, 0F2H, (* mov rdx, rsi *) + 48H, 39H, 0F7H, (* cmp rdi, rsi *) + 7EH, 06H, (* jle +6 *) + 48H, 89H, 0F0H, (* mov rax, rsi *) + 48H, 89H, 0FAH, (* mov rdx, rdi *) + 0C3H; + +proc nothing: (I64, ERROR); +begin +end; + +proc main*; +var q, r, i: I64; e: ERROR; x: F64; s: []U8; p: Pair; ok: BOOL; a: [3]I64; u: U8; +begin + q, r := divmod(17, 5); + Out.int(q); Out.str(" "); Out.int(r); Out.ln; + table := [10, 20, 30, 40]; + i, e := find(30); + Out.int(i); if e = nil then Out.str(" nil"); end; Out.ln; + i, e := find(7); + Out.int(i); Out.str(" "); Out.str(MSG(e)); + if e = NotFound then Out.str(" is NotFound"); end; + if e # Other then Out.str(", not Other"); end; + if e # Empty then Out.str(", not Empty"); end; + Out.ln; + Out.str("["); Out.str(MSG(nil)); Out.str("]"); Out.ln; + x, s, p, ok := mixed(1.5); + Out.int(I64(x * 10.0)); Out.str(" "); Out.str(s); Out.str(" "); Out.int(p.b); + if ok then Out.str(" ok"); end; Out.ln; + a[1], g.b := divmod(9, 4); + Out.int(a[1]); Out.str(" "); Out.int(g.b); Out.ln; + q, r := minmax(9, 3); + Out.int(q); Out.int(r); Out.ln; + divmod(1, 1); + i, e := nothing(); + Out.int(i); if e = nil then Out.str(" zero"); end; Out.ln; + i := 5; + INC(i); INC(i, 10); DEC(i, 2); + a[2] := 7; DEC(a[2]); + u := 255; INC(u); + Out.int(i); Out.str(" "); Out.int(a[2]); Out.str(" "); Out.int(I64(u)); Out.ln; +end; + +end Results. diff --git a/test/run/Shapes.jed b/test/run/Shapes.jed deleted file mode 100644 index e4ba610..0000000 --- a/test/run/Shapes.jed +++ /dev/null @@ -1,63 +0,0 @@ -module Shapes; -import Out; - -type - Shape* = variant - circle(r: F64); - rect(w, h: F64); - label(text: []U8; size: I64); - dot; - end; - -proc area(s: Shape): I64; -var a: F64; -begin - match s of - | circle(r): a := 3.0 * r * r; - | rect(w, h): a := w * h; - | label: a := 0.0; - | dot: a := 1.0; - end; - return I64(a); -end; - -proc grow(var s: Shape); -begin - match s of - | rect(w, h): w := w * 2.0; - | else: - end; -end; - -proc main*; -var s, t: Shape; shapes: [4]Shape; i: I64; z: Shape; -begin - s := circle(2.0); - Out.int(area(s)); Out.ln; - s := rect(3.0, 4.0); - Out.int(area(s)); Out.ln; - grow(s); - Out.int(area(s)); Out.ln; - t := s; - s := dot; - Out.int(area(s)); Out.str(" "); Out.int(area(t)); Out.ln; - shapes[0] := circle(1.0); - shapes[1] := label("hi", 12); - shapes[2] := dot; - shapes[3] := rect(1.5, 2.0); - for i := 0 to 3 do - match shapes[i] of - | label(text, size): Out.str(text); Out.int(size); - | else: Out.int(area(shapes[i])); - end; - Out.str(" "); - end; - Out.ln; - match z of - | circle(r): Out.str("zero is a circle of "); Out.int(I64(r)); Out.ln; - | else: Out.str("?"); - end; - Out.int(SIZE(Shape)); Out.ln; -end; - -end Shapes. diff --git a/test/run/Shapes.raz b/test/run/Shapes.raz new file mode 100644 index 0000000..e4ba610 --- /dev/null +++ b/test/run/Shapes.raz @@ -0,0 +1,63 @@ +module Shapes; +import Out; + +type + Shape* = variant + circle(r: F64); + rect(w, h: F64); + label(text: []U8; size: I64); + dot; + end; + +proc area(s: Shape): I64; +var a: F64; +begin + match s of + | circle(r): a := 3.0 * r * r; + | rect(w, h): a := w * h; + | label: a := 0.0; + | dot: a := 1.0; + end; + return I64(a); +end; + +proc grow(var s: Shape); +begin + match s of + | rect(w, h): w := w * 2.0; + | else: + end; +end; + +proc main*; +var s, t: Shape; shapes: [4]Shape; i: I64; z: Shape; +begin + s := circle(2.0); + Out.int(area(s)); Out.ln; + s := rect(3.0, 4.0); + Out.int(area(s)); Out.ln; + grow(s); + Out.int(area(s)); Out.ln; + t := s; + s := dot; + Out.int(area(s)); Out.str(" "); Out.int(area(t)); Out.ln; + shapes[0] := circle(1.0); + shapes[1] := label("hi", 12); + shapes[2] := dot; + shapes[3] := rect(1.5, 2.0); + for i := 0 to 3 do + match shapes[i] of + | label(text, size): Out.str(text); Out.int(size); + | else: Out.int(area(shapes[i])); + end; + Out.str(" "); + end; + Out.ln; + match z of + | circle(r): Out.str("zero is a circle of "); Out.int(I64(r)); Out.ln; + | else: Out.str("?"); + end; + Out.int(SIZE(Shape)); Out.ln; +end; + +end Shapes. diff --git a/test/run/Single.jed b/test/run/Single.jed deleted file mode 100644 index 32ce2ab..0000000 --- a/test/run/Single.jed +++ /dev/null @@ -1,81 +0,0 @@ -(* F32: arithmetic rounded at each step, conversions, real constants - that take either type, calls to C and to code. *) -module Single; -import Out, C; -link "libm.so.6"; - -const - third = 1.0 / 3.0; (* in double precision, then rounded once *) - tenth = 0.1; - -type - Vec = record x, y, z: F32; end; - -extern proc sqrtf(x: F32): F32; -extern proc fabsf(x: F32): F32; -extern proc sqrt(x: F64): F64; - -(* addss xmm0, xmm0; ret *) -proc twice(x: F32): F32; -code 0F3H, 0FH, 58H, 0C0H, 0C3H; - -proc dot(a, b: Vec): F32; -begin - return a.x * b.x + a.y * b.y + a.z * b.z; -end; - -proc mix(a: F32; n: I64; b: F64; c: F32): F64; -begin - return F64(a) + F64(n) + b + F64(c); -end; - -proc show(name: ^U8; x: F64); -begin - Out.flush; - C.printf("%s %.9g\n", name, x); - C.fflush(C.stdout); -end; - -proc main*; -var - a, b, s: F32; d: F64; v, w: Vec; i: I64; big: U64; arr: [4]F32; -begin - Out.int(SIZE(F32)); Out.char(' '); Out.int(SIZE(Vec)); Out.ln; - a := tenth; - b := 0.2; - show("a+b", F64(a + b)); - d := tenth; - show("d+0.2", d + 0.2); - a := third; - show("third", F64(a)); - a := 1.0; - b := 3.0; - show("1/3", F64(a / b)); - s := 0.0; - for i := 1 to 10 do s := s + tenth; end; - show("ten tenths", F64(s)); - if s # 1.0 then Out.str("not one\n"); end; - if (s > 0.9) and (s <= 1.1) and not (s < 0.0) then Out.str("near one\n"); end; - a := -a; - show("negated", F64(a)); - show("I64(-2.75)", F64(I64(F32(-2.75)))); - Out.int(I64(F32(1.0E10))); Out.ln; - big := 0FFFFFFFFFFFFFFFFH; - show("U64 max", F64(F32(big))); - show("I32 big", F64(F32(I32(16777217)))); - show("F32(1E40)", F64(F32(d * 1.0E41))); - show("F32(1/3)", F64(F32(1.0 / 3.0))); - v := {x: 1.0, y: 2.0, z: 3.0}; - w := {x: 0.5, y: 0.25, z: 2.0}; - show("dot", F64(dot(v, w))); - show("sqrtf", F64(sqrtf(2.0))); - show("fabsf", F64(fabsf(-1.5))); - show("twice", F64(twice(1.25))); - show("mix", mix(1.5, 2, 0.25, 0.125)); - for i := 0 to 3 do arr[i] := F32(i) * 0.5; end; - show("arr", F64(arr[3])); - C.printf("%f %f\n", F64(arr[1]), 0.5); - C.fflush(C.stdout); -end; - -end Single. diff --git a/test/run/Single.raz b/test/run/Single.raz new file mode 100644 index 0000000..32ce2ab --- /dev/null +++ b/test/run/Single.raz @@ -0,0 +1,81 @@ +(* F32: arithmetic rounded at each step, conversions, real constants + that take either type, calls to C and to code. *) +module Single; +import Out, C; +link "libm.so.6"; + +const + third = 1.0 / 3.0; (* in double precision, then rounded once *) + tenth = 0.1; + +type + Vec = record x, y, z: F32; end; + +extern proc sqrtf(x: F32): F32; +extern proc fabsf(x: F32): F32; +extern proc sqrt(x: F64): F64; + +(* addss xmm0, xmm0; ret *) +proc twice(x: F32): F32; +code 0F3H, 0FH, 58H, 0C0H, 0C3H; + +proc dot(a, b: Vec): F32; +begin + return a.x * b.x + a.y * b.y + a.z * b.z; +end; + +proc mix(a: F32; n: I64; b: F64; c: F32): F64; +begin + return F64(a) + F64(n) + b + F64(c); +end; + +proc show(name: ^U8; x: F64); +begin + Out.flush; + C.printf("%s %.9g\n", name, x); + C.fflush(C.stdout); +end; + +proc main*; +var + a, b, s: F32; d: F64; v, w: Vec; i: I64; big: U64; arr: [4]F32; +begin + Out.int(SIZE(F32)); Out.char(' '); Out.int(SIZE(Vec)); Out.ln; + a := tenth; + b := 0.2; + show("a+b", F64(a + b)); + d := tenth; + show("d+0.2", d + 0.2); + a := third; + show("third", F64(a)); + a := 1.0; + b := 3.0; + show("1/3", F64(a / b)); + s := 0.0; + for i := 1 to 10 do s := s + tenth; end; + show("ten tenths", F64(s)); + if s # 1.0 then Out.str("not one\n"); end; + if (s > 0.9) and (s <= 1.1) and not (s < 0.0) then Out.str("near one\n"); end; + a := -a; + show("negated", F64(a)); + show("I64(-2.75)", F64(I64(F32(-2.75)))); + Out.int(I64(F32(1.0E10))); Out.ln; + big := 0FFFFFFFFFFFFFFFFH; + show("U64 max", F64(F32(big))); + show("I32 big", F64(F32(I32(16777217)))); + show("F32(1E40)", F64(F32(d * 1.0E41))); + show("F32(1/3)", F64(F32(1.0 / 3.0))); + v := {x: 1.0, y: 2.0, z: 3.0}; + w := {x: 0.5, y: 0.25, z: 2.0}; + show("dot", F64(dot(v, w))); + show("sqrtf", F64(sqrtf(2.0))); + show("fabsf", F64(fabsf(-1.5))); + show("twice", F64(twice(1.25))); + show("mix", mix(1.5, 2, 0.25, 0.125)); + for i := 0 to 3 do arr[i] := F32(i) * 0.5; end; + show("arr", F64(arr[3])); + C.printf("%f %f\n", F64(arr[1]), 0.5); + C.fflush(C.stdout); +end; + +end Single. diff --git a/test/run/Spawn.jed b/test/run/Spawn.jed deleted file mode 100644 index 22ccd7d..0000000 --- a/test/run/Spawn.jed +++ /dev/null @@ -1,50 +0,0 @@ -(* Native threads: a counter under a Mutex, the heap and Out used from - every thread at once, and join. *) -module Spawn; -import Out, Thread, Heap, Mem; - -const - Workers = 8; - Rounds = 20000; - -type Node = record next: ^Node; n: I64; end; - -var - m: Thread.Mutex; - count, atomic: I64; - -proc work(arg: ^U8); -var i: I64; p, list: ^Node; -begin - list := nil; - for i := 1 to Rounds do - Thread.lock(ADR(m)); - INC(count); - Thread.unlock(ADR(m)); - XADD(ADR(atomic), 1); - NEW(p, Heap.heap); - p^.next := list; - list := p; - if i mod 4 = 0 then - while list # nil do - p := list^.next; - Mem.free(Heap.heap, ^U8(list)); - list := p; - end; - end; - end; - for i := 1 to 25 do Out.str("the same line from every thread\n"); end; -end; - -proc main*; -var t: [Workers]^Thread.Thread; i: I64; err: ERROR; -begin - for i := 0 to Workers - 1 do - t[i], err := Thread.spawn(work, nil); - if err # nil then Out.str(MSG(err)); Out.ln; return; end; - end; - for i := 0 to Workers - 1 do Thread.join(t[i]); end; - Out.int(count); Out.char(' '); Out.int(atomic); Out.ln; -end; - -end Spawn. diff --git a/test/run/Spawn.raz b/test/run/Spawn.raz new file mode 100644 index 0000000..22ccd7d --- /dev/null +++ b/test/run/Spawn.raz @@ -0,0 +1,50 @@ +(* Native threads: a counter under a Mutex, the heap and Out used from + every thread at once, and join. *) +module Spawn; +import Out, Thread, Heap, Mem; + +const + Workers = 8; + Rounds = 20000; + +type Node = record next: ^Node; n: I64; end; + +var + m: Thread.Mutex; + count, atomic: I64; + +proc work(arg: ^U8); +var i: I64; p, list: ^Node; +begin + list := nil; + for i := 1 to Rounds do + Thread.lock(ADR(m)); + INC(count); + Thread.unlock(ADR(m)); + XADD(ADR(atomic), 1); + NEW(p, Heap.heap); + p^.next := list; + list := p; + if i mod 4 = 0 then + while list # nil do + p := list^.next; + Mem.free(Heap.heap, ^U8(list)); + list := p; + end; + end; + end; + for i := 1 to 25 do Out.str("the same line from every thread\n"); end; +end; + +proc main*; +var t: [Workers]^Thread.Thread; i: I64; err: ERROR; +begin + for i := 0 to Workers - 1 do + t[i], err := Thread.spawn(work, nil); + if err # nil then Out.str(MSG(err)); Out.ln; return; end; + end; + for i := 0 to Workers - 1 do Thread.join(t[i]); end; + Out.int(count); Out.char(' '); Out.int(atomic); Out.ln; +end; + +end Spawn. diff --git a/test/run/Strings.jed b/test/run/Strings.jed deleted file mode 100644 index ee9084b..0000000 --- a/test/run/Strings.jed +++ /dev/null @@ -1,39 +0,0 @@ -module Strings; -import Out; - -const greeting = "hello"; - -var buf: [8]U8; - -proc count(xs: []I64): I64; -var i, s: I64; -begin - s := 0; - for i := 0 to LEN(xs) - 1 do s := s + xs[i]; end; - return s; -end; - -proc main*; -var a: []U8; b: [5]U8; c: [3]I64; d: [][]U8; -begin - a := "hello"; - if a = greeting then Out.str("eq "); end; - if a # "help" then Out.str("ne "); end; - if "abc" = "abc" then Out.str("lit "); end; - b := "hello"; - if b = a then Out.str("arr "); end; - buf := "hi"; - if buf[0..2] = "hi" then Out.str("buf "); end; - Out.int(I64(buf[5])); Out.str(" "); - Out.int(LEN(greeting)); Out.str(" "); - Out.int(LEN(a[1..3])); Out.ln; - c := [1, 2, 3]; - Out.int(count(c)); Out.str(" "); - Out.int(count([10, 20, 30, 40])); Out.str(" "); - Out.int(count([])); Out.ln; - d := ["one", "two", "three"]; - Out.str(d[2]); Out.str(d[0]); Out.ln; - Out.str("é\u{263A}\x41\n"); -end; - -end Strings. diff --git a/test/run/Strings.raz b/test/run/Strings.raz new file mode 100644 index 0000000..ee9084b --- /dev/null +++ b/test/run/Strings.raz @@ -0,0 +1,39 @@ +module Strings; +import Out; + +const greeting = "hello"; + +var buf: [8]U8; + +proc count(xs: []I64): I64; +var i, s: I64; +begin + s := 0; + for i := 0 to LEN(xs) - 1 do s := s + xs[i]; end; + return s; +end; + +proc main*; +var a: []U8; b: [5]U8; c: [3]I64; d: [][]U8; +begin + a := "hello"; + if a = greeting then Out.str("eq "); end; + if a # "help" then Out.str("ne "); end; + if "abc" = "abc" then Out.str("lit "); end; + b := "hello"; + if b = a then Out.str("arr "); end; + buf := "hi"; + if buf[0..2] = "hi" then Out.str("buf "); end; + Out.int(I64(buf[5])); Out.str(" "); + Out.int(LEN(greeting)); Out.str(" "); + Out.int(LEN(a[1..3])); Out.ln; + c := [1, 2, 3]; + Out.int(count(c)); Out.str(" "); + Out.int(count([10, 20, 30, 40])); Out.str(" "); + Out.int(count([])); Out.ln; + d := ["one", "two", "three"]; + Out.str(d[2]); Out.str(d[0]); Out.ln; + Out.str("é\u{263A}\x41\n"); +end; + +end Strings. diff --git a/test/run/Target.jed b/test/run/Target.jed deleted file mode 100644 index 9f8c1a8..0000000 --- a/test/run/Target.jed +++ /dev/null @@ -1,11 +0,0 @@ -module Target; -import Out, Plat; - -proc main*; -var i: Plat.Info; -begin - i.kind := 41; - Out.str(Plat.name); Out.int(Plat.id(i.kind)); Out.ln; -end; - -end Target. diff --git a/test/run/Target.raz b/test/run/Target.raz new file mode 100644 index 0000000..9f8c1a8 --- /dev/null +++ b/test/run/Target.raz @@ -0,0 +1,11 @@ +module Target; +import Out, Plat; + +proc main*; +var i: Plat.Info; +begin + i.kind := 41; + Out.str(Plat.name); Out.int(Plat.id(i.kind)); Out.ln; +end; + +end Target. diff --git a/test/run/mods/First.jed b/test/run/mods/First.jed deleted file mode 100644 index fa9f69f..0000000 --- a/test/run/mods/First.jed +++ /dev/null @@ -1,14 +0,0 @@ -module First; -import Out; - -var count*: I64; - -proc main*; -begin - Out.str("First.main must not run"); -end; - -begin - count := 1; - Out.str("First "); -end First. diff --git a/test/run/mods/First.raz b/test/run/mods/First.raz new file mode 100644 index 0000000..fa9f69f --- /dev/null +++ b/test/run/mods/First.raz @@ -0,0 +1,14 @@ +module First; +import Out; + +var count*: I64; + +proc main*; +begin + Out.str("First.main must not run"); +end; + +begin + count := 1; + Out.str("First "); +end First. diff --git a/test/run/mods/Plat.linux-x86_64.jed b/test/run/mods/Plat.linux-x86_64.jed deleted file mode 100644 index 95996ae..0000000 --- a/test/run/mods/Plat.linux-x86_64.jed +++ /dev/null @@ -1,5 +0,0 @@ -module Plat; -const name* = "linux"; -type Info* = record kind*: I64; extra: I64; end; -proc id*(x: I64): I64; begin return x + 1; end; -end Plat. diff --git a/test/run/mods/Plat.linux-x86_64.raz b/test/run/mods/Plat.linux-x86_64.raz new file mode 100644 index 0000000..95996ae --- /dev/null +++ b/test/run/mods/Plat.linux-x86_64.raz @@ -0,0 +1,5 @@ +module Plat; +const name* = "linux"; +type Info* = record kind*: I64; extra: I64; end; +proc id*(x: I64): I64; begin return x + 1; end; +end Plat. diff --git a/test/run/mods/Plat.macos-aarch64.jed b/test/run/mods/Plat.macos-aarch64.jed deleted file mode 100644 index 7d7c615..0000000 --- a/test/run/mods/Plat.macos-aarch64.jed +++ /dev/null @@ -1,5 +0,0 @@ -module Plat; -const name* = "macos"; -type Info* = record kind*: I64; other: U8; end; -proc id*(x: I64): I64; begin return SOMETHING_UNKNOWN_HERE(x); end; -end Plat. diff --git a/test/run/mods/Plat.macos-aarch64.raz b/test/run/mods/Plat.macos-aarch64.raz new file mode 100644 index 0000000..7d7c615 --- /dev/null +++ b/test/run/mods/Plat.macos-aarch64.raz @@ -0,0 +1,5 @@ +module Plat; +const name* = "macos"; +type Info* = record kind*: I64; other: U8; end; +proc id*(x: I64): I64; begin return SOMETHING_UNKNOWN_HERE(x); end; +end Plat. diff --git a/test/run/mods/Second.jed b/test/run/mods/Second.jed deleted file mode 100644 index c9aecdc..0000000 --- a/test/run/mods/Second.jed +++ /dev/null @@ -1,11 +0,0 @@ -module Second; -import Out, First; - -var count*: I64; - -begin - count := First.count + 1; - Out.str("Second "); - if count = 2 then return; end; - Out.str("not reached"); -end Second. diff --git a/test/run/mods/Second.raz b/test/run/mods/Second.raz new file mode 100644 index 0000000..c9aecdc --- /dev/null +++ b/test/run/mods/Second.raz @@ -0,0 +1,11 @@ +module Second; +import Out, First; + +var count*: I64; + +begin + count := First.count + 1; + Out.str("Second "); + if count = 2 then return; end; + Out.str("not reached"); +end Second. diff --git a/test/run/mods/Stack.jed b/test/run/mods/Stack.jed deleted file mode 100644 index 6048ee4..0000000 --- a/test/run/mods/Stack.jed +++ /dev/null @@ -1,13 +0,0 @@ -module Stack; -import Ints := List(I64), Heap; - -var s*: Ints.List; - -proc top*(): I64; -begin - return s.head^.val; -end; - -begin - Ints.init(ADR(s), Heap.heap); -end Stack. diff --git a/test/run/mods/Stack.raz b/test/run/mods/Stack.raz new file mode 100644 index 0000000..6048ee4 --- /dev/null +++ b/test/run/mods/Stack.raz @@ -0,0 +1,13 @@ +module Stack; +import Ints := List(I64), Heap; + +var s*: Ints.List; + +proc top*(): I64; +begin + return s.head^.val; +end; + +begin + Ints.init(ADR(s), Heap.heap); +end Stack. diff --git a/tools/Doc.jed b/tools/Doc.jed deleted file mode 100644 index 419f878..0000000 --- a/tools/Doc.jed +++ /dev/null @@ -1,309 +0,0 @@ -(* Doc: what a module offers, from its source. - - Doc Module.jed - prints the module's own comment, the one just before module, then - each exported declaration as it is written, with the comment just - before it. - - Doc examples report.md dir - writes each example of the report that is a whole module, from - module to end, with no ... left out, to dir/Name.jed, and prints - the names, one a line. *) -module Doc; -import Out, Rt, Str, Buf, Heap, Scan, Files; - -var - sc: Scan.Scanner; (* the text being read, at the current symbol *) - src: []U8; - docStart, docEnd: I64; (* the comment just before it, or -1 *) - -(* On to the next symbol that isn't a comment, keeping where the last - comment that starts a line was: one after code on its line belongs - to that code. *) -proc next; -var newLine: BOOL; -begin - docStart := -1; - newLine := false; - repeat - Scan.next(ADR(sc)); - newLine := newLine or sc.lineBreak; - if (sc.kind = Scan.comment) and newLine then - docStart := sc.start; docEnd := sc.stop; - end; - until sc.kind # Scan.comment; -end; - -proc text: []U8; -begin - return Scan.text(ADR(sc)); -end; - -proc is(s: []U8): BOOL; -begin - return text() = s; -end; - -(* Whether the current word starts a declaration, a section or the end. *) -proc reserved: BOOL; -begin - return is("const") or is("type") or is("var") or is("proc") or is("extern") - or is("import") or is("link") or is("begin") or is("end"); -end; - -(* On to the ; that ends what starts here, past anything bracketed and - any record or variant; returns where it ends. *) -proc toSemicolon: I64; -var depth: I64; -begin - depth := 0; - while sc.kind # Scan.eof do - if is("(") or is("[") or is("{") or is("record") or is("variant") then INC(depth); - elsif is(")") or is("]") or is("}") or is("end") then DEC(depth); - elsif is(";") and (depth <= 0) then return sc.stop; - end; - next; - end; - return sc.pos; -end; - -(* stop, or the end of a comment that follows it on its line. *) -proc trailing(stop: I64): I64; -var t: Scan.Scanner; -begin - while (stop < LEN(src)) and ((src[stop] = ' ') or (src[stop] = 9)) do INC(stop); end; - t := sc; - t.pos := stop; - Scan.next(ADR(t)); - if (t.kind = Scan.comment) and (t.start = stop) then return t.stop; end; - return stop; -end; - -(* Where the line holding p starts. *) -proc lineStart(p: I64): I64; -begin - while (p > 0) and (src[p - 1] # 10) do DEC(p); end; - return p; -end; - -(* src[start..stop] as written, each line after the first moved left as - far as the first one's column. *) -proc block(start, stop: I64); -var col, i, n: I64; -begin - col := start - lineStart(start); - i := start; - while i < stop do - Out.char(src[i]); - if src[i] = 10 then - n := 0; - while (n < col) and (i + 1 < stop) and (src[i + 1] = ' ') do INC(i); INC(n); end; - end; - INC(i); - end; - Out.ln; -end; - -(* The comment from start to stop, without its brackets, each line - indented by four. *) -proc comment(start, stop: I64); -var i, j: I64; atLine: BOOL; -begin - if start < 0 then return; end; - i := start + 2; - j := stop - 2; - while (i < j) and Scan.isSpace(src[i]) do INC(i); end; - while (j > i) and Scan.isSpace(src[j - 1]) do DEC(j); end; - atLine := true; - while i < j do - if atLine then Out.str(" "); atLine := false; end; - Out.char(src[i]); - if src[i] = 10 then - atLine := true; - while (i + 1 < j) and (src[i + 1] = ' ') do INC(i); end; - end; - INC(i); - end; - Out.ln; -end; - -(* One declaration, from its first token, the comment before it kept. *) -proc declaration(prefix: []U8; exported: BOOL; start, ds, de, stop: I64); -begin - if not exported then return; end; - Out.ln; - Out.str(prefix); - block(start, trailing(stop)); - comment(ds, de); -end; - -(* name, and whether a * follows it; leaves the token after them. *) -proc name: BOOL; -begin - next; - next; - if is("*") then next; return true; end; - return false; -end; - -(* A procedure's body: to the end that closes its begin, the procedure - name after it and its ;. *) -proc skipBody; -var depth: I64; sawBegin: BOOL; -begin - depth := 0; - sawBegin := false; - while sc.kind # Scan.eof do - if is("begin") then - if depth = 0 then sawBegin := true; end; - INC(depth); - elsif is("if") or is("while") or is("for") or is("match") or is("record") or is("variant") then - INC(depth); - elsif is("end") then - DEC(depth); - if (depth = 0) and sawBegin then - next; - if sc.kind = Scan.word then next; end; - return; - end; - end; - next; - end; -end; - -proc procedure; -var start, ds, de, stop: I64; exp: BOOL; -begin - start := sc.start; ds := docStart; de := docEnd; - exp := name(); - stop := toSemicolon(); - next; - if is("forward") or is("code") then toSemicolon(); - else skipBody; - end; - declaration("", exp, start, ds, de, stop); - next; -end; - -proc section; -var word: []U8; start, ds, de, stop: I64; exp: BOOL; -begin - word := text(); - next; - while (sc.kind = Scan.word) and not reserved() do - start := sc.start; ds := docStart; de := docEnd; - sc.pos := sc.start; (* name reads the name again *) - exp := name(); - stop := toSemicolon(); - if exp then - Out.ln; - Out.str(word); Out.str(" "); - block(start, trailing(stop)); - comment(ds, de); - end; - next; - end; -end; - -proc external; -var start, ds, de, stop: I64; exp: BOOL; -begin - start := sc.start; ds := docStart; de := docEnd; - next; - exp := name(); - stop := toSemicolon(); - declaration("", exp, start, ds, de, stop); - next; -end; - -proc document(path: []U8); -var b: Buf.Buf; start, ds, de: I64; -begin - Buf.init(ADR(b), Heap.heap); - if not Files.read(path, ADR(b)) then Rt.stop("Doc: can't read the file"); end; - src := Buf.bytes(ADR(b)); - Scan.init(ADR(sc), src); - next; - while (sc.kind # Scan.eof) and not is("module") do next; end; - if sc.kind = Scan.eof then Rt.stop("Doc: no module"); end; - start := sc.start; - ds := docStart; de := docEnd; - block(start, toSemicolon()); - comment(ds, de); - next; - while (sc.kind # Scan.eof) and not is("begin") and not is("end") do - if is("const") or is("type") or is("var") then section; - elsif is("proc") then procedure; - elsif is("extern") then external; - elsif is("import") or is("link") then toSemicolon(); next; - else next; - end; - end; -end; - -(* line, without the spaces at its ends *) -proc trim(line: []U8): []U8; -var i, j: I64; -begin - i := 0; - j := LEN(line); - while (i < j) and Scan.isSpace(line[i]) do INC(i); end; - while (j > i) and Scan.isSpace(line[j - 1]) do DEC(j); end; - return line[i..j]; -end; - -(* The report's examples that are whole modules, each to dir. *) -proc examples(path, dir: []U8); -var - b, out: Buf.Buf; s, line, first, last, name: []U8; i, start, k, n: I64; - inBlock, whole: BOOL; -begin - Buf.init(ADR(b), Heap.heap); - Buf.init(ADR(out), Heap.heap); - if not Files.read(path, ADR(b)) then Rt.stop("Doc: can't read the report"); end; - s := Buf.bytes(ADR(b)); - inBlock := false; - start := 0; - i := 0; - while i < LEN(s) do - k := i; - while (k < LEN(s)) and (s[k] # 10) do INC(k); end; - line := s[i..k]; - if trim(line) = "```" then - if inBlock and whole and Str.hasPrefix(first, "module ") and Str.hasPrefix(last, "end ") then - name := first[7..LEN(first)]; - n := 0; - while (n < LEN(name)) and Scan.isWord(name[n]) do INC(n); end; - name := name[0..n]; - Buf.reset(ADR(out)); - Buf.str(ADR(out), dir); Buf.str(ADR(out), "/"); Buf.str(ADR(out), name); - Buf.str(ADR(out), ".jed"); - if not Files.write(Buf.bytes(ADR(out)), s[start..i]) then - Rt.stop("Doc: can't write an example"); - end; - Out.str(name); Out.ln; - end; - inBlock := not inBlock; - start := k + 1; - first := ""; last := ""; - whole := true; - elsif inBlock then - if trim(line) = "..." then whole := false; end; - if LEN(trim(line)) > 0 then - if LEN(first) = 0 then first := trim(line); end; - last := trim(line); - end; - end; - i := k + 1; - end; -end; - -proc main*; -begin - if (ARGC() = 4) and (Files.arg(1) = "examples") then examples(Files.arg(2), Files.arg(3)); - elsif ARGC() = 2 then document(Files.arg(1)); - else Rt.stop("usage: Doc Module.jed, or Doc examples report.md dir"); - end; -end; - -end Doc. diff --git a/tools/Doc.raz b/tools/Doc.raz new file mode 100644 index 0000000..a6bf77b --- /dev/null +++ b/tools/Doc.raz @@ -0,0 +1,309 @@ +(* Doc: what a module offers, from its source. + + Doc Module.raz + prints the module's own comment, the one just before module, then + each exported declaration as it is written, with the comment just + before it. + + Doc examples report.md dir + writes each example of the report that is a whole module, from + module to end, with no ... left out, to dir/Name.raz, and prints + the names, one a line. *) +module Doc; +import Out, Rt, Str, Buf, Heap, Scan, Files; + +var + sc: Scan.Scanner; (* the text being read, at the current symbol *) + src: []U8; + docStart, docEnd: I64; (* the comment just before it, or -1 *) + +(* On to the next symbol that isn't a comment, keeping where the last + comment that starts a line was: one after code on its line belongs + to that code. *) +proc next; +var newLine: BOOL; +begin + docStart := -1; + newLine := false; + repeat + Scan.next(ADR(sc)); + newLine := newLine or sc.lineBreak; + if (sc.kind = Scan.comment) and newLine then + docStart := sc.start; docEnd := sc.stop; + end; + until sc.kind # Scan.comment; +end; + +proc text: []U8; +begin + return Scan.text(ADR(sc)); +end; + +proc is(s: []U8): BOOL; +begin + return text() = s; +end; + +(* Whether the current word starts a declaration, a section or the end. *) +proc reserved: BOOL; +begin + return is("const") or is("type") or is("var") or is("proc") or is("extern") + or is("import") or is("link") or is("begin") or is("end"); +end; + +(* On to the ; that ends what starts here, past anything bracketed and + any record or variant; returns where it ends. *) +proc toSemicolon: I64; +var depth: I64; +begin + depth := 0; + while sc.kind # Scan.eof do + if is("(") or is("[") or is("{") or is("record") or is("variant") then INC(depth); + elsif is(")") or is("]") or is("}") or is("end") then DEC(depth); + elsif is(";") and (depth <= 0) then return sc.stop; + end; + next; + end; + return sc.pos; +end; + +(* stop, or the end of a comment that follows it on its line. *) +proc trailing(stop: I64): I64; +var t: Scan.Scanner; +begin + while (stop < LEN(src)) and ((src[stop] = ' ') or (src[stop] = 9)) do INC(stop); end; + t := sc; + t.pos := stop; + Scan.next(ADR(t)); + if (t.kind = Scan.comment) and (t.start = stop) then return t.stop; end; + return stop; +end; + +(* Where the line holding p starts. *) +proc lineStart(p: I64): I64; +begin + while (p > 0) and (src[p - 1] # 10) do DEC(p); end; + return p; +end; + +(* src[start..stop] as written, each line after the first moved left as + far as the first one's column. *) +proc block(start, stop: I64); +var col, i, n: I64; +begin + col := start - lineStart(start); + i := start; + while i < stop do + Out.char(src[i]); + if src[i] = 10 then + n := 0; + while (n < col) and (i + 1 < stop) and (src[i + 1] = ' ') do INC(i); INC(n); end; + end; + INC(i); + end; + Out.ln; +end; + +(* The comment from start to stop, without its brackets, each line + indented by four. *) +proc comment(start, stop: I64); +var i, j: I64; atLine: BOOL; +begin + if start < 0 then return; end; + i := start + 2; + j := stop - 2; + while (i < j) and Scan.isSpace(src[i]) do INC(i); end; + while (j > i) and Scan.isSpace(src[j - 1]) do DEC(j); end; + atLine := true; + while i < j do + if atLine then Out.str(" "); atLine := false; end; + Out.char(src[i]); + if src[i] = 10 then + atLine := true; + while (i + 1 < j) and (src[i + 1] = ' ') do INC(i); end; + end; + INC(i); + end; + Out.ln; +end; + +(* One declaration, from its first token, the comment before it kept. *) +proc declaration(prefix: []U8; exported: BOOL; start, ds, de, stop: I64); +begin + if not exported then return; end; + Out.ln; + Out.str(prefix); + block(start, trailing(stop)); + comment(ds, de); +end; + +(* name, and whether a * follows it; leaves the token after them. *) +proc name: BOOL; +begin + next; + next; + if is("*") then next; return true; end; + return false; +end; + +(* A procedure's body: to the end that closes its begin, the procedure + name after it and its ;. *) +proc skipBody; +var depth: I64; sawBegin: BOOL; +begin + depth := 0; + sawBegin := false; + while sc.kind # Scan.eof do + if is("begin") then + if depth = 0 then sawBegin := true; end; + INC(depth); + elsif is("if") or is("while") or is("for") or is("match") or is("record") or is("variant") then + INC(depth); + elsif is("end") then + DEC(depth); + if (depth = 0) and sawBegin then + next; + if sc.kind = Scan.word then next; end; + return; + end; + end; + next; + end; +end; + +proc procedure; +var start, ds, de, stop: I64; exp: BOOL; +begin + start := sc.start; ds := docStart; de := docEnd; + exp := name(); + stop := toSemicolon(); + next; + if is("forward") or is("code") then toSemicolon(); + else skipBody; + end; + declaration("", exp, start, ds, de, stop); + next; +end; + +proc section; +var word: []U8; start, ds, de, stop: I64; exp: BOOL; +begin + word := text(); + next; + while (sc.kind = Scan.word) and not reserved() do + start := sc.start; ds := docStart; de := docEnd; + sc.pos := sc.start; (* name reads the name again *) + exp := name(); + stop := toSemicolon(); + if exp then + Out.ln; + Out.str(word); Out.str(" "); + block(start, trailing(stop)); + comment(ds, de); + end; + next; + end; +end; + +proc external; +var start, ds, de, stop: I64; exp: BOOL; +begin + start := sc.start; ds := docStart; de := docEnd; + next; + exp := name(); + stop := toSemicolon(); + declaration("", exp, start, ds, de, stop); + next; +end; + +proc document(path: []U8); +var b: Buf.Buf; start, ds, de: I64; +begin + Buf.init(ADR(b), Heap.heap); + if not Files.read(path, ADR(b)) then Rt.stop("Doc: can't read the file"); end; + src := Buf.bytes(ADR(b)); + Scan.init(ADR(sc), src); + next; + while (sc.kind # Scan.eof) and not is("module") do next; end; + if sc.kind = Scan.eof then Rt.stop("Doc: no module"); end; + start := sc.start; + ds := docStart; de := docEnd; + block(start, toSemicolon()); + comment(ds, de); + next; + while (sc.kind # Scan.eof) and not is("begin") and not is("end") do + if is("const") or is("type") or is("var") then section; + elsif is("proc") then procedure; + elsif is("extern") then external; + elsif is("import") or is("link") then toSemicolon(); next; + else next; + end; + end; +end; + +(* line, without the spaces at its ends *) +proc trim(line: []U8): []U8; +var i, j: I64; +begin + i := 0; + j := LEN(line); + while (i < j) and Scan.isSpace(line[i]) do INC(i); end; + while (j > i) and Scan.isSpace(line[j - 1]) do DEC(j); end; + return line[i..j]; +end; + +(* The report's examples that are whole modules, each to dir. *) +proc examples(path, dir: []U8); +var + b, out: Buf.Buf; s, line, first, last, name: []U8; i, start, k, n: I64; + inBlock, whole: BOOL; +begin + Buf.init(ADR(b), Heap.heap); + Buf.init(ADR(out), Heap.heap); + if not Files.read(path, ADR(b)) then Rt.stop("Doc: can't read the report"); end; + s := Buf.bytes(ADR(b)); + inBlock := false; + start := 0; + i := 0; + while i < LEN(s) do + k := i; + while (k < LEN(s)) and (s[k] # 10) do INC(k); end; + line := s[i..k]; + if trim(line) = "```" then + if inBlock and whole and Str.hasPrefix(first, "module ") and Str.hasPrefix(last, "end ") then + name := first[7..LEN(first)]; + n := 0; + while (n < LEN(name)) and Scan.isWord(name[n]) do INC(n); end; + name := name[0..n]; + Buf.reset(ADR(out)); + Buf.str(ADR(out), dir); Buf.str(ADR(out), "/"); Buf.str(ADR(out), name); + Buf.str(ADR(out), ".raz"); + if not Files.write(Buf.bytes(ADR(out)), s[start..i]) then + Rt.stop("Doc: can't write an example"); + end; + Out.str(name); Out.ln; + end; + inBlock := not inBlock; + start := k + 1; + first := ""; last := ""; + whole := true; + elsif inBlock then + if trim(line) = "..." then whole := false; end; + if LEN(trim(line)) > 0 then + if LEN(first) = 0 then first := trim(line); end; + last := trim(line); + end; + end; + i := k + 1; + end; +end; + +proc main*; +begin + if (ARGC() = 4) and (Files.arg(1) = "examples") then examples(Files.arg(2), Files.arg(3)); + elsif ARGC() = 2 then document(Files.arg(1)); + else Rt.stop("usage: Doc Module.raz, or Doc examples report.md dir"); + end; +end; + +end Doc. diff --git a/tools/Files.jed b/tools/Files.jed deleted file mode 100644 index 3306d5f..0000000 --- a/tools/Files.jed +++ /dev/null @@ -1,46 +0,0 @@ -(* Files: what the tools need of the command line and of files: an - argument as a string, and a whole file read or written. *) -module Files; -import Sys, Buf; - -(* Argument i, a C string, as a slice. *) -proc arg*(i: I64): []U8; -var s: ^U8; n: I64; -begin - s := ARGV()[i]; - n := 0; - while s[n] # 0 do INC(n); end; - return s[0..n]; -end; - -(* Adds the file at path to b; false if it can't be read. *) -proc read*(path: []U8; b: ^Buf.Buf): BOOL; -var fd, n: I64; chunk: [4096]U8; -begin - fd := Sys.openRead(path); - if fd < 0 then return false; end; - repeat - n := Sys.read(fd, chunk); - if n > 0 then Buf.str(b, chunk[0..n]); end; - until n <= 0; - Sys.close(fd); - return n = 0; -end; - -(* Makes the file at path hold data; false if it can't be written. *) -proc write*(path, data: []U8): BOOL; -var fd, n, at: I64; -begin - fd := Sys.create(path); - if fd < 0 then return false; end; - at := 0; - while at < LEN(data) do - n := Sys.write(fd, data[at..LEN(data)]); - if n <= 0 then Sys.close(fd); return false; end; - at := at + n; - end; - Sys.close(fd); - return true; -end; - -end Files. diff --git a/tools/Files.raz b/tools/Files.raz new file mode 100644 index 0000000..3306d5f --- /dev/null +++ b/tools/Files.raz @@ -0,0 +1,46 @@ +(* Files: what the tools need of the command line and of files: an + argument as a string, and a whole file read or written. *) +module Files; +import Sys, Buf; + +(* Argument i, a C string, as a slice. *) +proc arg*(i: I64): []U8; +var s: ^U8; n: I64; +begin + s := ARGV()[i]; + n := 0; + while s[n] # 0 do INC(n); end; + return s[0..n]; +end; + +(* Adds the file at path to b; false if it can't be read. *) +proc read*(path: []U8; b: ^Buf.Buf): BOOL; +var fd, n: I64; chunk: [4096]U8; +begin + fd := Sys.openRead(path); + if fd < 0 then return false; end; + repeat + n := Sys.read(fd, chunk); + if n > 0 then Buf.str(b, chunk[0..n]); end; + until n <= 0; + Sys.close(fd); + return n = 0; +end; + +(* Makes the file at path hold data; false if it can't be written. *) +proc write*(path, data: []U8): BOOL; +var fd, n, at: I64; +begin + fd := Sys.create(path); + if fd < 0 then return false; end; + at := 0; + while at < LEN(data) do + n := Sys.write(fd, data[at..LEN(data)]); + if n <= 0 then Sys.close(fd); return false; end; + at := at + n; + end; + Sys.close(fd); + return true; +end; + +end Files. diff --git a/tools/Pretty.jed b/tools/Pretty.jed deleted file mode 100644 index fb8b343..0000000 --- a/tools/Pretty.jed +++ /dev/null @@ -1,339 +0,0 @@ -(* Pretty: jed source laid out the one way. - - Pretty Module.jed - prints the module, formatted. - - Pretty -w File.jed... - rewrites each file that isn't formatted already. - - Every line break and comment stays where it is. A line is indented - 4 spaces for each block it stands in: the statements of if, while, - for, repeat and begin, the fields of a record or variant, the - declarations of const, type and var. end, until, else, elsif and a - match's arms stand at the level of the statement that opened them; - module, import, proc, the sections and begin at the margin, with the - comment just before them. A line that goes on with the expression of - the line before keeps its indent, moved as far as the statement's - first line moved; so does the text of a comment. - - Within a line, a binary operator has one space on each side, a unary - minus none after it, and , and ; none before them and one after. A - comment after code keeps its column. Other spaces stay as written, - so that lined-up match arms stay lined up. No line ends in spaces. *) -module Pretty; -import Out, Rt, Buf, Heap, Scan, Files; - -const - width = 4; (* the spaces of a level *) - openers = "if while for match record variant begin repeat"; - declarations = "module import link extern proc const type var begin code"; - binaryWords = "div mod and or xor shl shr in"; - binarySymbols = "+ - * / = # < <= > >= :="; - -var - sc: Scan.Scanner; (* the source, at the symbol being written *) - src: []U8; - out: Buf.Buf; - lineAt: I64; (* where the line being written starts in out *) - lineDelta: I64; (* how far this line's indent moved *) - - (* the blocks open, each with the indent of the statement that - opened it *) - bases: [100]I64; - depth: I64; - brackets: I64; (* brackets open *) - inSection: BOOL; (* among the declarations of const, type or var *) - stmtIndent: I64; (* the indent of the current statement's first line *) - stmtDelta: I64; (* and how far that moved *) - - (* the last symbol that wasn't a comment, and the one before it *) - prev, prev2: Scan.Scanner; - prevBinary, prevUnary: BOOL; - afterComment: BOOL; (* the last symbol written was a comment *) - last: I64; (* where the last symbol written ends in src *) - -proc spaces(n: I64); -begin - while n > 0 do Buf.add(ADR(out), ' '); DEC(n); end; -end; - -(* Drops the spaces at the end of the line in out. *) -proc trim; -var s: []U8; -begin - s := Buf.bytes(ADR(out)); - while (out.len > lineAt) and ((s[out.len - 1] = ' ') or (s[out.len - 1] = '\t')) do - DEC(out.len); - end; -end; - -proc newLine; -begin - trim; - Buf.add(ADR(out), '\n'); - lineAt := out.len; -end; - -(* Where the line holding p starts in src. *) -proc lineStart(p: I64): I64; -begin - while (p > 0) and (src[p - 1] # '\n') do DEC(p); end; - return p; -end; - -(* The column src[p] is at, a tab going on to the next multiple of 8. *) -proc column(p: I64): I64; -var i, col: I64; -begin - col := 0; - for i := lineStart(p) to p - 1 do - if src[i] = '\t' then col := (col div 8 + 1) * 8; else INC(col); end; - end; - return col; -end; - -(* Whether s ends an operand, so that a - after it subtracts. *) -proc endsOperand(s: ^Scan.Scanner): BOOL; -begin - if s^.kind = Scan.word then return not Scan.reserved(Scan.text(s)); end; - return (s^.kind = Scan.number) or (s^.kind = Scan.literal) - or Scan.is(s, ")") or Scan.is(s, "]") or Scan.is(s, "}") or Scan.is(s, "^"); -end; - -(* The symbol after the current one that isn't a comment. *) -proc following: Scan.Scanner; -var s: Scan.Scanner; -begin - s := sc; - repeat Scan.next(ADR(s)); until s.kind # Scan.comment; - return s; -end; - -(* Whether the current symbol is a binary operator. A * after a name - and before ; , : = ) or a procedure's parameters exports the name. *) -proc binary: BOOL; -var n: Scan.Scanner; -begin - if sc.kind = Scan.word then return Scan.among(Scan.text(ADR(sc)), binaryWords); end; - if (sc.kind # Scan.symbol) or not Scan.among(Scan.text(ADR(sc)), binarySymbols) then - return false; - end; - if Scan.is(ADR(sc), "-") or Scan.is(ADR(sc), "+") then return endsOperand(ADR(prev)); end; - if Scan.is(ADR(sc), "*") and (prev.kind = Scan.word) then - n := following(); - if Scan.among(Scan.text(ADR(n)), "; , : = )") then return false; end; - if Scan.is(ADR(n), "(") and Scan.is(ADR(prev2), "proc") then return false; end; - end; - return true; -end; - -(* Whether the current symbol, first on its line, goes on with the - expression of the line before. *) -proc continues: BOOL; -var t: []U8; -begin - if (brackets > 0) or prevBinary or Scan.is(ADR(prev), ",") then return true; end; - t := Scan.text(ADR(sc)); - if sc.kind = Scan.word then return Scan.among(t, binaryWords) or Scan.among(t, "then do of"); end; - return (sc.kind = Scan.symbol) and Scan.among(t, binarySymbols); -end; - -(* Whether s starts a declaration at the margin: proc( starts a - procedure type. *) -proc declaration(s: Scan.Scanner): BOOL; -begin - if (s.kind # Scan.word) or not Scan.among(Scan.text(ADR(s)), declarations) then return false; end; - if not Scan.is(ADR(s), "proc") then return true; end; - Scan.next(ADR(s)); - return not Scan.is(ADR(s), "("); -end; - -(* The indent of the block's own lines, or of its end. *) -proc inner: I64; -begin - if depth > 0 then return bases[depth - 1] + width; end; - if inSection then return width; end; - return 0; -end; - -proc outer: I64; -begin - if depth > 0 then return bases[depth - 1]; end; - return 0; -end; - -(* The indent of the line the current symbol starts, which was at old. *) -proc indent(old: I64): I64; -var n: Scan.Scanner; -begin - if continues() then - if old + stmtDelta < 0 then return 0; end; - return old + stmtDelta; - end; - if sc.kind = Scan.comment then - n := following(); - if n.lineBreak and declaration(n) then return 0; end; - return inner(); - end; - if declaration(sc) then - depth := 0; - inSection := Scan.among(Scan.text(ADR(sc)), "const type var"); - return 0; - end; - if Scan.among(Scan.text(ADR(sc)), "end until else elsif |") then - return outer(); - end; - return inner(); -end; - -(* Starts the line of the current symbol, at its indent. *) -proc startLine; -var old, new: I64; -begin - old := column(sc.start); - new := indent(old); - lineDelta := new - old; - if (sc.kind # Scan.comment) and not continues() then - stmtIndent := new; - stmtDelta := lineDelta; - end; - spaces(new); -end; - -(* The spaces between the last symbol written and the current one, on - the same line. *) -proc gap(binaryNow: BOOL); -var n: I64; -begin - if sc.kind = Scan.comment then - n := column(sc.start) + lineDelta - (out.len - lineAt); - if (n < 1) and (sc.start > last) then n := 1; end; - spaces(n); - elsif afterComment then - Buf.str(ADR(out), src[last..sc.start]); - elsif Scan.is(ADR(sc), ",") or Scan.is(ADR(sc), ";") then - elsif Scan.is(ADR(prev), ",") or Scan.is(ADR(prev), ";") or binaryNow or prevBinary then - if not prevUnary then spaces(1); end; - elsif not prevUnary then - Buf.str(ADR(out), src[last..sc.start]); - end; -end; - -(* The current symbol as written; each line of a comment after its - first is moved as far as the line the comment starts on. *) -proc write; -var i, k: I64; -begin - i := sc.start; - while i < sc.stop do - if src[i] = '\n' then - newLine; - k := i + 1; - while (k < sc.stop) and (src[k] = ' ') do INC(k); end; - if (k < sc.stop) and (src[k] # '\n') then spaces(k - (i + 1) + lineDelta); end; - i := k; - else - Buf.add(ADR(out), src[i]); - INC(i); - end; - end; -end; - -(* After a symbol that isn't a comment: the blocks and brackets it opens - or closes. *) -proc track(binaryNow: BOOL); -var t: []U8; -begin - t := Scan.text(ADR(sc)); - if sc.kind = Scan.word then - if Scan.among(t, openers) then - if depth = LEN(bases) then Rt.stop("Pretty: blocks nested too deep"); end; - bases[depth] := stmtIndent; - INC(depth); - elsif ((t = "end") or (t = "until")) and (depth > 0) then - DEC(depth); - end; - elsif sc.kind = Scan.symbol then - if Scan.among(t, "( [ {") then INC(brackets); - elsif Scan.among(t, ") ] }") and (brackets > 0) then DEC(brackets); - end; - end; - prevUnary := (Scan.is(ADR(sc), "-") or Scan.is(ADR(sc), "+")) and not binaryNow; - prevBinary := binaryNow; - prev2 := prev; - prev := sc; -end; - -(* The line breaks in src[from..upto]. *) -proc lineBreaks(from, upto: I64); -var i: I64; -begin - for i := from to upto - 1 do - if src[i] = '\n' then newLine; end; - end; -end; - -(* src, formatted, into out. *) -proc format(text: []U8); -var b: BOOL; -begin - src := text; - Buf.reset(ADR(out)); - lineAt := 0; - depth := 0; - brackets := 0; - inSection := false; - stmtIndent := 0; - stmtDelta := 0; - Scan.init(ADR(sc), src); - prev := sc; - prev2 := sc; - prevBinary := false; - prevUnary := false; - afterComment := false; - last := 0; - Scan.next(ADR(sc)); - while sc.kind # Scan.eof do - b := (sc.kind # Scan.comment) and binary(); - if sc.lineBreak then - lineBreaks(last, sc.start); - startLine; - else - gap(b); - end; - write; - afterComment := sc.kind = Scan.comment; - if not afterComment then track(b); end; - last := sc.stop; - Scan.next(ADR(sc)); - end; - lineBreaks(last, LEN(src)); - trim; -end; - -proc main*; -var b: Buf.Buf; i: I64; path: []U8; -begin - Buf.init(ADR(b), Heap.heap); - Buf.init(ADR(out), Heap.heap); - if (ARGC() >= 3) and (Files.arg(1) = "-w") then - for i := 2 to ARGC() - 1 do - path := Files.arg(i); - Buf.reset(ADR(b)); - if not Files.read(path, ADR(b)) then Rt.stop("Pretty: can't read a file"); end; - format(Buf.bytes(ADR(b))); - if Buf.bytes(ADR(out)) # Buf.bytes(ADR(b)) then - if not Files.write(path, Buf.bytes(ADR(out))) then Rt.stop("Pretty: can't write a file"); end; - Out.str(path); Out.ln; - end; - end; - elsif ARGC() = 2 then - if not Files.read(Files.arg(1), ADR(b)) then Rt.stop("Pretty: can't read the file"); end; - format(Buf.bytes(ADR(b))); - Out.str(Buf.bytes(ADR(out))); - else - Rt.stop("usage: Pretty Module.jed, or Pretty -w File.jed..."); - end; -end; - -end Pretty. diff --git a/tools/Pretty.raz b/tools/Pretty.raz new file mode 100644 index 0000000..83c78ab --- /dev/null +++ b/tools/Pretty.raz @@ -0,0 +1,339 @@ +(* Pretty: raz source laid out the one way. + + Pretty Module.raz + prints the module, formatted. + + Pretty -w File.raz... + rewrites each file that isn't formatted already. + + Every line break and comment stays where it is. A line is indented + 4 spaces for each block it stands in: the statements of if, while, + for, repeat and begin, the fields of a record or variant, the + declarations of const, type and var. end, until, else, elsif and a + match's arms stand at the level of the statement that opened them; + module, import, proc, the sections and begin at the margin, with the + comment just before them. A line that goes on with the expression of + the line before keeps its indent, moved as far as the statement's + first line moved; so does the text of a comment. + + Within a line, a binary operator has one space on each side, a unary + minus none after it, and , and ; none before them and one after. A + comment after code keeps its column. Other spaces stay as written, + so that lined-up match arms stay lined up. No line ends in spaces. *) +module Pretty; +import Out, Rt, Buf, Heap, Scan, Files; + +const + width = 4; (* the spaces of a level *) + openers = "if while for match record variant begin repeat"; + declarations = "module import link extern proc const type var begin code"; + binaryWords = "div mod and or xor shl shr in"; + binarySymbols = "+ - * / = # < <= > >= :="; + +var + sc: Scan.Scanner; (* the source, at the symbol being written *) + src: []U8; + out: Buf.Buf; + lineAt: I64; (* where the line being written starts in out *) + lineDelta: I64; (* how far this line's indent moved *) + + (* the blocks open, each with the indent of the statement that + opened it *) + bases: [100]I64; + depth: I64; + brackets: I64; (* brackets open *) + inSection: BOOL; (* among the declarations of const, type or var *) + stmtIndent: I64; (* the indent of the current statement's first line *) + stmtDelta: I64; (* and how far that moved *) + + (* the last symbol that wasn't a comment, and the one before it *) + prev, prev2: Scan.Scanner; + prevBinary, prevUnary: BOOL; + afterComment: BOOL; (* the last symbol written was a comment *) + last: I64; (* where the last symbol written ends in src *) + +proc spaces(n: I64); +begin + while n > 0 do Buf.add(ADR(out), ' '); DEC(n); end; +end; + +(* Drops the spaces at the end of the line in out. *) +proc trim; +var s: []U8; +begin + s := Buf.bytes(ADR(out)); + while (out.len > lineAt) and ((s[out.len - 1] = ' ') or (s[out.len - 1] = '\t')) do + DEC(out.len); + end; +end; + +proc newLine; +begin + trim; + Buf.add(ADR(out), '\n'); + lineAt := out.len; +end; + +(* Where the line holding p starts in src. *) +proc lineStart(p: I64): I64; +begin + while (p > 0) and (src[p - 1] # '\n') do DEC(p); end; + return p; +end; + +(* The column src[p] is at, a tab going on to the next multiple of 8. *) +proc column(p: I64): I64; +var i, col: I64; +begin + col := 0; + for i := lineStart(p) to p - 1 do + if src[i] = '\t' then col := (col div 8 + 1) * 8; else INC(col); end; + end; + return col; +end; + +(* Whether s ends an operand, so that a - after it subtracts. *) +proc endsOperand(s: ^Scan.Scanner): BOOL; +begin + if s^.kind = Scan.word then return not Scan.reserved(Scan.text(s)); end; + return (s^.kind = Scan.number) or (s^.kind = Scan.literal) + or Scan.is(s, ")") or Scan.is(s, "]") or Scan.is(s, "}") or Scan.is(s, "^"); +end; + +(* The symbol after the current one that isn't a comment. *) +proc following: Scan.Scanner; +var s: Scan.Scanner; +begin + s := sc; + repeat Scan.next(ADR(s)); until s.kind # Scan.comment; + return s; +end; + +(* Whether the current symbol is a binary operator. A * after a name + and before ; , : = ) or a procedure's parameters exports the name. *) +proc binary: BOOL; +var n: Scan.Scanner; +begin + if sc.kind = Scan.word then return Scan.among(Scan.text(ADR(sc)), binaryWords); end; + if (sc.kind # Scan.symbol) or not Scan.among(Scan.text(ADR(sc)), binarySymbols) then + return false; + end; + if Scan.is(ADR(sc), "-") or Scan.is(ADR(sc), "+") then return endsOperand(ADR(prev)); end; + if Scan.is(ADR(sc), "*") and (prev.kind = Scan.word) then + n := following(); + if Scan.among(Scan.text(ADR(n)), "; , : = )") then return false; end; + if Scan.is(ADR(n), "(") and Scan.is(ADR(prev2), "proc") then return false; end; + end; + return true; +end; + +(* Whether the current symbol, first on its line, goes on with the + expression of the line before. *) +proc continues: BOOL; +var t: []U8; +begin + if (brackets > 0) or prevBinary or Scan.is(ADR(prev), ",") then return true; end; + t := Scan.text(ADR(sc)); + if sc.kind = Scan.word then return Scan.among(t, binaryWords) or Scan.among(t, "then do of"); end; + return (sc.kind = Scan.symbol) and Scan.among(t, binarySymbols); +end; + +(* Whether s starts a declaration at the margin: proc( starts a + procedure type. *) +proc declaration(s: Scan.Scanner): BOOL; +begin + if (s.kind # Scan.word) or not Scan.among(Scan.text(ADR(s)), declarations) then return false; end; + if not Scan.is(ADR(s), "proc") then return true; end; + Scan.next(ADR(s)); + return not Scan.is(ADR(s), "("); +end; + +(* The indent of the block's own lines, or of its end. *) +proc inner: I64; +begin + if depth > 0 then return bases[depth - 1] + width; end; + if inSection then return width; end; + return 0; +end; + +proc outer: I64; +begin + if depth > 0 then return bases[depth - 1]; end; + return 0; +end; + +(* The indent of the line the current symbol starts, which was at old. *) +proc indent(old: I64): I64; +var n: Scan.Scanner; +begin + if continues() then + if old + stmtDelta < 0 then return 0; end; + return old + stmtDelta; + end; + if sc.kind = Scan.comment then + n := following(); + if n.lineBreak and declaration(n) then return 0; end; + return inner(); + end; + if declaration(sc) then + depth := 0; + inSection := Scan.among(Scan.text(ADR(sc)), "const type var"); + return 0; + end; + if Scan.among(Scan.text(ADR(sc)), "end until else elsif |") then + return outer(); + end; + return inner(); +end; + +(* Starts the line of the current symbol, at its indent. *) +proc startLine; +var old, new: I64; +begin + old := column(sc.start); + new := indent(old); + lineDelta := new - old; + if (sc.kind # Scan.comment) and not continues() then + stmtIndent := new; + stmtDelta := lineDelta; + end; + spaces(new); +end; + +(* The spaces between the last symbol written and the current one, on + the same line. *) +proc gap(binaryNow: BOOL); +var n: I64; +begin + if sc.kind = Scan.comment then + n := column(sc.start) + lineDelta - (out.len - lineAt); + if (n < 1) and (sc.start > last) then n := 1; end; + spaces(n); + elsif afterComment then + Buf.str(ADR(out), src[last..sc.start]); + elsif Scan.is(ADR(sc), ",") or Scan.is(ADR(sc), ";") then + elsif Scan.is(ADR(prev), ",") or Scan.is(ADR(prev), ";") or binaryNow or prevBinary then + if not prevUnary then spaces(1); end; + elsif not prevUnary then + Buf.str(ADR(out), src[last..sc.start]); + end; +end; + +(* The current symbol as written; each line of a comment after its + first is moved as far as the line the comment starts on. *) +proc write; +var i, k: I64; +begin + i := sc.start; + while i < sc.stop do + if src[i] = '\n' then + newLine; + k := i + 1; + while (k < sc.stop) and (src[k] = ' ') do INC(k); end; + if (k < sc.stop) and (src[k] # '\n') then spaces(k - (i + 1) + lineDelta); end; + i := k; + else + Buf.add(ADR(out), src[i]); + INC(i); + end; + end; +end; + +(* After a symbol that isn't a comment: the blocks and brackets it opens + or closes. *) +proc track(binaryNow: BOOL); +var t: []U8; +begin + t := Scan.text(ADR(sc)); + if sc.kind = Scan.word then + if Scan.among(t, openers) then + if depth = LEN(bases) then Rt.stop("Pretty: blocks nested too deep"); end; + bases[depth] := stmtIndent; + INC(depth); + elsif ((t = "end") or (t = "until")) and (depth > 0) then + DEC(depth); + end; + elsif sc.kind = Scan.symbol then + if Scan.among(t, "( [ {") then INC(brackets); + elsif Scan.among(t, ") ] }") and (brackets > 0) then DEC(brackets); + end; + end; + prevUnary := (Scan.is(ADR(sc), "-") or Scan.is(ADR(sc), "+")) and not binaryNow; + prevBinary := binaryNow; + prev2 := prev; + prev := sc; +end; + +(* The line breaks in src[from..upto]. *) +proc lineBreaks(from, upto: I64); +var i: I64; +begin + for i := from to upto - 1 do + if src[i] = '\n' then newLine; end; + end; +end; + +(* src, formatted, into out. *) +proc format(text: []U8); +var b: BOOL; +begin + src := text; + Buf.reset(ADR(out)); + lineAt := 0; + depth := 0; + brackets := 0; + inSection := false; + stmtIndent := 0; + stmtDelta := 0; + Scan.init(ADR(sc), src); + prev := sc; + prev2 := sc; + prevBinary := false; + prevUnary := false; + afterComment := false; + last := 0; + Scan.next(ADR(sc)); + while sc.kind # Scan.eof do + b := (sc.kind # Scan.comment) and binary(); + if sc.lineBreak then + lineBreaks(last, sc.start); + startLine; + else + gap(b); + end; + write; + afterComment := sc.kind = Scan.comment; + if not afterComment then track(b); end; + last := sc.stop; + Scan.next(ADR(sc)); + end; + lineBreaks(last, LEN(src)); + trim; +end; + +proc main*; +var b: Buf.Buf; i: I64; path: []U8; +begin + Buf.init(ADR(b), Heap.heap); + Buf.init(ADR(out), Heap.heap); + if (ARGC() >= 3) and (Files.arg(1) = "-w") then + for i := 2 to ARGC() - 1 do + path := Files.arg(i); + Buf.reset(ADR(b)); + if not Files.read(path, ADR(b)) then Rt.stop("Pretty: can't read a file"); end; + format(Buf.bytes(ADR(b))); + if Buf.bytes(ADR(out)) # Buf.bytes(ADR(b)) then + if not Files.write(path, Buf.bytes(ADR(out))) then Rt.stop("Pretty: can't write a file"); end; + Out.str(path); Out.ln; + end; + end; + elsif ARGC() = 2 then + if not Files.read(Files.arg(1), ADR(b)) then Rt.stop("Pretty: can't read the file"); end; + format(Buf.bytes(ADR(b))); + Out.str(Buf.bytes(ADR(out))); + else + Rt.stop("usage: Pretty Module.raz, or Pretty -w File.raz..."); + end; +end; + +end Pretty. diff --git a/tools/Scan.jed b/tools/Scan.jed deleted file mode 100644 index 8d67ee0..0000000 --- a/tools/Scan.jed +++ /dev/null @@ -1,171 +0,0 @@ -(* Scan: the symbols of jed source, for the tools. Unlike the - compiler's scanner it keeps comments, as symbols of their own, and - says where each symbol is in the text and whether a line break comes - before it. It doesn't check what it reads: a malformed number is - read as far as it goes, and a string, character or comment left open - ends with its line or the text. *) -module Scan; - -type - Kind* = (word, number, literal, symbol, comment, eof); - - (* word is an identifier or a reserved word; literal a string or a - character; symbol an operator or delimiter. *) - Scanner* = record - src*: []U8; - pos*: I64; (* where the next symbol is looked for *) - kind*: Kind; (* the current symbol *) - start*, stop*: I64; (* its text: src[start..stop] *) - lineBreak*: BOOL; (* a line break comes before it, or it is the first *) - end; - -const - 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"; - -proc isSpace*(c: U8): BOOL; -begin - return (c = ' ') or (c = '\t') or (c = '\n') or (c = '\r'); -end; - -proc isWord*(c: U8): BOOL; -begin - return (c >= 'a') and (c <= 'z') or (c >= 'A') and (c <= 'Z') - or (c >= '0') and (c <= '9') or (c = '_'); -end; - -proc isDigit(c: U8): BOOL; -begin - return (c >= '0') and (c <= '9'); -end; - -(* Whether w is one of the words of list, which are separated by - single spaces. *) -proc among*(w, list: []U8): BOOL; -var i, j: I64; -begin - i := 0; - while i < LEN(list) do - j := i; - while (j < LEN(list)) and (list[j] # ' ') do INC(j); end; - if list[i..j] = w then return true; end; - i := j + 1; - end; - return false; -end; - -(* Whether w is one of the report's reserved words. *) -proc reserved*(w: []U8): BOOL; -begin - return among(w, words); -end; - -(* The scanner at the start of src; next gives the first symbol. *) -proc init*(s: ^Scanner; src: []U8); -begin - s^ := {src: src, kind: eof}; -end; - -(* Past the comment that starts at p, its nested comments with it. *) -proc pastComment(src: []U8; p: I64): I64; -var depth: I64; -begin - depth := 0; - repeat - if (src[p] = '(') and (p + 1 < LEN(src)) and (src[p + 1] = '*') then - INC(depth); INC(p, 2); - elsif (src[p] = '*') and (p + 1 < LEN(src)) and (src[p + 1] = ')') then - DEC(depth); INC(p, 2); - else - INC(p); - end; - until (depth = 0) or (p >= LEN(src)); - return p; -end; - -(* Past the number that starts at p: digits and letters, then a real's - point, digits and exponent, as in 0FFH and 2.0E-3. *) -proc pastNumber(src: []U8; p: I64): I64; -begin - while (p < LEN(src)) and isWord(src[p]) do INC(p); end; - if (p + 1 < LEN(src)) and (src[p] = '.') and isDigit(src[p + 1]) then - INC(p); - while (p < LEN(src)) and isWord(src[p]) do INC(p); end; - if (src[p - 1] = 'E') and (p < LEN(src)) and ((src[p] = '-') or (src[p] = '+')) then - INC(p); - while (p < LEN(src)) and isWord(src[p]) do INC(p); end; - end; - end; - return p; -end; - -(* Past the string or character that starts at p, or to its line's end. *) -proc pastLiteral(src: []U8; p: I64): I64; -var q: U8; -begin - q := src[p]; - INC(p); - while (p < LEN(src)) and (src[p] # q) and (src[p] # '\n') do - if (src[p] = '\\') and (p + 1 < LEN(src)) then INC(p); end; - INC(p); - end; - if (p < LEN(src)) and (src[p] = q) then INC(p); end; - return p; -end; - -(* Whether src[p..] starts with the symbol t. *) -proc at(src: []U8; p: I64; t: []U8): BOOL; -begin - return (p + LEN(t) <= LEN(src)) and (src[p..p + LEN(t)] = t); -end; - -(* On to the next symbol. *) -proc next*(s: ^Scanner); -var src: []U8; p: I64; c: U8; -begin - src := s^.src; - p := s^.pos; - s^.lineBreak := p = 0; - while (p < LEN(src)) and isSpace(src[p]) do - if src[p] = '\n' then s^.lineBreak := true; end; - INC(p); - end; - s^.start := p; - if p >= LEN(src) then - s^.kind := eof; - else - c := src[p]; - if at(src, p, "(*") then - s^.kind := comment; p := pastComment(src, p); - elsif isDigit(c) then - s^.kind := number; p := pastNumber(src, p); - elsif isWord(c) then - s^.kind := word; - while (p < LEN(src)) and isWord(src[p]) do INC(p); end; - elsif (c = '"') or (c = '\'') then - s^.kind := literal; p := pastLiteral(src, p); - else - s^.kind := symbol; - if at(src, p, "...") then INC(p, 3); - elsif at(src, p, ":=") or at(src, p, "<=") or at(src, p, ">=") or at(src, p, "..") then - INC(p, 2); - else - INC(p); - end; - end; - end; - s^.stop := p; - s^.pos := p; -end; - -proc text*(s: ^Scanner): []U8; -begin - return s^.src[s^.start..s^.stop]; -end; - -(* Whether the current symbol is t. *) -proc is*(s: ^Scanner; t: []U8): BOOL; -begin - return text(s) = t; -end; - -end Scan. diff --git a/tools/Scan.raz b/tools/Scan.raz new file mode 100644 index 0000000..aad4c50 --- /dev/null +++ b/tools/Scan.raz @@ -0,0 +1,171 @@ +(* Scan: the symbols of raz source, for the tools. Unlike the + compiler's scanner it keeps comments, as symbols of their own, and + says where each symbol is in the text and whether a line break comes + before it. It doesn't check what it reads: a malformed number is + read as far as it goes, and a string, character or comment left open + ends with its line or the text. *) +module Scan; + +type + Kind* = (word, number, literal, symbol, comment, eof); + + (* word is an identifier or a reserved word; literal a string or a + character; symbol an operator or delimiter. *) + Scanner* = record + src*: []U8; + pos*: I64; (* where the next symbol is looked for *) + kind*: Kind; (* the current symbol *) + start*, stop*: I64; (* its text: src[start..stop] *) + lineBreak*: BOOL; (* a line break comes before it, or it is the first *) + end; + +const + 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"; + +proc isSpace*(c: U8): BOOL; +begin + return (c = ' ') or (c = '\t') or (c = '\n') or (c = '\r'); +end; + +proc isWord*(c: U8): BOOL; +begin + return (c >= 'a') and (c <= 'z') or (c >= 'A') and (c <= 'Z') + or (c >= '0') and (c <= '9') or (c = '_'); +end; + +proc isDigit(c: U8): BOOL; +begin + return (c >= '0') and (c <= '9'); +end; + +(* Whether w is one of the words of list, which are separated by + single spaces. *) +proc among*(w, list: []U8): BOOL; +var i, j: I64; +begin + i := 0; + while i < LEN(list) do + j := i; + while (j < LEN(list)) and (list[j] # ' ') do INC(j); end; + if list[i..j] = w then return true; end; + i := j + 1; + end; + return false; +end; + +(* Whether w is one of the report's reserved words. *) +proc reserved*(w: []U8): BOOL; +begin + return among(w, words); +end; + +(* The scanner at the start of src; next gives the first symbol. *) +proc init*(s: ^Scanner; src: []U8); +begin + s^ := {src: src, kind: eof}; +end; + +(* Past the comment that starts at p, its nested comments with it. *) +proc pastComment(src: []U8; p: I64): I64; +var depth: I64; +begin + depth := 0; + repeat + if (src[p] = '(') and (p + 1 < LEN(src)) and (src[p + 1] = '*') then + INC(depth); INC(p, 2); + elsif (src[p] = '*') and (p + 1 < LEN(src)) and (src[p + 1] = ')') then + DEC(depth); INC(p, 2); + else + INC(p); + end; + until (depth = 0) or (p >= LEN(src)); + return p; +end; + +(* Past the number that starts at p: digits and letters, then a real's + point, digits and exponent, as in 0FFH and 2.0E-3. *) +proc pastNumber(src: []U8; p: I64): I64; +begin + while (p < LEN(src)) and isWord(src[p]) do INC(p); end; + if (p + 1 < LEN(src)) and (src[p] = '.') and isDigit(src[p + 1]) then + INC(p); + while (p < LEN(src)) and isWord(src[p]) do INC(p); end; + if (src[p - 1] = 'E') and (p < LEN(src)) and ((src[p] = '-') or (src[p] = '+')) then + INC(p); + while (p < LEN(src)) and isWord(src[p]) do INC(p); end; + end; + end; + return p; +end; + +(* Past the string or character that starts at p, or to its line's end. *) +proc pastLiteral(src: []U8; p: I64): I64; +var q: U8; +begin + q := src[p]; + INC(p); + while (p < LEN(src)) and (src[p] # q) and (src[p] # '\n') do + if (src[p] = '\\') and (p + 1 < LEN(src)) then INC(p); end; + INC(p); + end; + if (p < LEN(src)) and (src[p] = q) then INC(p); end; + return p; +end; + +(* Whether src[p..] starts with the symbol t. *) +proc at(src: []U8; p: I64; t: []U8): BOOL; +begin + return (p + LEN(t) <= LEN(src)) and (src[p..p + LEN(t)] = t); +end; + +(* On to the next symbol. *) +proc next*(s: ^Scanner); +var src: []U8; p: I64; c: U8; +begin + src := s^.src; + p := s^.pos; + s^.lineBreak := p = 0; + while (p < LEN(src)) and isSpace(src[p]) do + if src[p] = '\n' then s^.lineBreak := true; end; + INC(p); + end; + s^.start := p; + if p >= LEN(src) then + s^.kind := eof; + else + c := src[p]; + if at(src, p, "(*") then + s^.kind := comment; p := pastComment(src, p); + elsif isDigit(c) then + s^.kind := number; p := pastNumber(src, p); + elsif isWord(c) then + s^.kind := word; + while (p < LEN(src)) and isWord(src[p]) do INC(p); end; + elsif (c = '"') or (c = '\'') then + s^.kind := literal; p := pastLiteral(src, p); + else + s^.kind := symbol; + if at(src, p, "...") then INC(p, 3); + elsif at(src, p, ":=") or at(src, p, "<=") or at(src, p, ">=") or at(src, p, "..") then + INC(p, 2); + else + INC(p); + end; + end; + end; + s^.stop := p; + s^.pos := p; +end; + +proc text*(s: ^Scanner): []U8; +begin + return s^.src[s^.start..s^.stop]; +end; + +(* Whether the current symbol is t. *) +proc is*(s: ^Scanner; t: []U8): BOOL; +begin + return text(s) = t; +end; + +end Scan.