raz / commit 39edff85

commit
39edff85dacb63f9eeaa95390c5e8c113f7c6d68
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
30b3c516
Step 17: README.md and doc/compiler.md

README.md: what jed is, building, the checks, using the compiler, the
language in brief, the library, the tools and editors, versions, and
what it leaves out.

doc/compiler.md: a guide to reading the compiler file by file, in the
order to read it: the shape of it (one pass, items, a stack machine
through rax, chunks and fixups, tree shaking), one program followed
from the command line to the file, a procedure's code shown
instruction by instruction, each unit's data and the routines to read
first, and where to start changing it.

patch · log

4 files changed, +488 -3

CLAUDE.md modified +4 -2

@@ -44,8 +44,10 @@
4444
4545 ## Where things stand
4646
47-Stages 1 to 4 are done (steps 1-16), waiting for review. Next is step
48-17, `README.md` and `doc/compiler.md`, on the owner's go-ahead. Left
47+Steps 1-17 are done: the language, the tools, `README.md` and the
48+guide to the compiler, `doc/compiler.md`. Next, only on the owner's
49+word, is step 18, the formatter. Keep `doc/compiler.md`'s table of
50+lines and its routine names true when the compiler changes. Left
4951 for later at the owner's word: tagging versions, and a rewrite of var
5052 parameters.
5153

PLAN.md (history) modified +1 -1

@@ -158,7 +158,7 @@
158158
159159 Wrap up
160160
161-- [ ] 17. `README.md` and `doc/compiler.md`, a guide to reading the
161+- [x] 17. `README.md` and `doc/compiler.md`, a guide to reading the
162162 compiler file by file.
163163
164164 Later

README.md (history) added +132 -0

@@ -0,0 +1,132 @@
1+# jed
2+
3+jed (Polish *jeden*, one) is a small systems language in Wirth's
4+tradition, for x86-64 Linux. A jed program can lay a record over a
5+device's registers, read and write memory exactly as written, take part
6+in lock-free algorithms, make system calls and call C libraries. It has
7+no garbage collector and no hidden run time: what the program does is
8+what its text says.
9+
10+```
11+module Hello;
12+import Out;
13+
14+proc main*;
15+begin
16+ Out.str("hello, world\n");
17+end;
18+
19+end Hello.
20+```
21+
22+ $ make
23+ $ ./jed examples/Hello.jed
24+ $ examples/Hello
25+ hello, world
26+
27+The compiler is under 5,000 lines of Free Pascal: one pass, no
28+intermediate form, no optimizer. It writes x86-64 machine code and the
29+ELF executable itself, with no assembler or linker, and compiles about
30+a million lines a second.
31+
32+## What's here
33+
34+| Path | What |
35+|---|---|
36+| `doc/jed.md` | The language report: the definition of jed |
37+| `doc/compiler.md` | A guide to reading the compiler, file by file |
38+| `src/` | The compiler, in Free Pascal |
39+| `lib/` | The library, in jed; the compiler finds it beside itself |
40+| `examples/` | Small programs, each with the output it should give |
41+| `tools/Doc.jed` | Prints what a module exports, with its comments |
42+| `editor/` | Support for vim and emacs |
43+| `test/` | Tests, and the scripts that run them |
44+| `PLAN.md` | How the compiler was built, step by step |
45+
46+## Building
47+
48+The compiler needs Free Pascal 3.2.2 (`apt-get install fp-compiler`)
49+and builds into the repository's root:
50+
51+ make # ./jed
52+
53+The tests need a shell and Python 3; the editor checks run if vim or
54+emacs is installed.
55+
56+ make check # every example and test, against what it should give
57+ make bench # the compiler's speed on a program of 350,000 lines
58+ make stress # 40,000 threads, started and joined
59+ make gdb # gdb stops at a line of jed and names it
60+ make loc # the compiler's lines
61+ make tests # tests of the scanner, encoder and linker on their own
62+
63+## Using it
64+
65+ jed [-I dir]... [-o file] Main.jed
66+ jed --version
67+
68+`jed Main.jed` compiles module `Main` and every module it imports, and
69+writes the executable `Main`. A module `Name` lives in `Name.jed`, found
70+in the main module's directory, then in each `-I` directory, then in
71+`lib`. A module whose code depends on the system comes in one file per
72+target, `Name.linux-x86_64.jed` before `Name.jed`; the compiler checks
73+that all of them export the same things.
74+
75+A program that calls no C is a static executable of a few kilobytes,
76+holding only the code it reaches. One that declares an `extern`
77+procedure is linked dynamically against the C library, and starts
78+through it. Either way, gdb finds its procedures by name and its lines
79+by number.
80+
81+## The language, briefly
82+
83+- Integers of 8 to 64 bits, signed and unsigned, which wrap; `BOOL`,
84+ `F32`, `F64`. No conversion happens unless it is written.
85+- Arrays, slices (`[]T`, checked), pointers (unchecked), records laid
86+ out as C lays them out, packed records, variants with `match`,
87+ enumerations and sets, procedure types.
88+- `^VOLATILE T`: every access through it is one instruction of its
89+ size, in the order written. `CAS`, `XCHG`, `XADD`, `FENCE`.
90+- Several results, `ERROR` values compared by identity, `defer`.
91+- Modules with bodies; generic modules with type and procedure
92+ arguments, `Map(K, V; hash, eq)`.
93+- Every variable starts at zero, and behaviour is defined everywhere
94+ but through pointers.
95+- `extern` procedures and variables from C; code procedures written as
96+ bytes of machine code; `SYSCALL`.
97+
98+The report, `doc/jed.md`, says all of it in about 900 lines.
99+
100+## The library
101+
102+`Rt` (ending the program, checks), `Sys` (system calls), `Out`
103+(buffered output), `C`, `Lock`, `Thread` (threads without C), `Mem`,
104+`Heap`, `Arena`, `Str`, `Buf`, `Fmt`, `List(T)` and `Map(K, V; hash,
105+eq)`. `tools/Doc.jed` prints any of them:
106+
107+ $ ./jed -o Doc tools/Doc.jed && ./Doc lib/Str.jed
108+
109+Each library module's `main` is its test, which `make check` runs.
110+
111+## Editors
112+
113+`editor/vim` holds a syntax file, an indent file and file type
114+detection: add it to `runtimepath`. `editor/emacs/jed-mode.el` is a
115+major mode: put it on `load-path` and `(require 'jed-mode)`. Both
116+colour the language and indent it as the examples are indented.
117+
118+## Versions
119+
120+The compiler says which version of the report it follows:
121+
122+ $ ./jed --version
123+ jed 0.3.0, report 2026-10.0
124+
125+A version of the report is named by its month and a count; the report's
126+last section says what each version changed.
127+
128+## Not here
129+
130+Other systems and processors (Mach-O, PE, aarch64), an optimizer,
131+separate compilation, records passed to C by value, thread-local
132+variables, and type information for debuggers.

doc/compiler.md (history) added +351 -0

@@ -0,0 +1,351 @@
1+# Reading the jed compiler
2+
3+The compiler is eight files of Free Pascal, under 5,000 lines of code.
4+This guide walks through them in the order they are best read: from the
5+characters of a source file to the bytes of an executable. It assumes
6+you know the language from `doc/jed.md`, and enough x86-64 to read a
7+disassembly.
8+
9+| File | Lines | Code | What |
10+|---|---|---|---|
11+| `src/scan.pas` | 548 | 471 | Symbols, literals, comments, error messages |
12+| `src/sym.pas` | 508 | 422 | Types, objects, scopes, layout |
13+| `src/x64.pas` | 680 | 546 | Code buffer, chunks, fixups, line notes, instruction encoder |
14+| `src/gen.pas` | 1,414 | 1,240 | Items: loading, storing, copying, frames, calls |
15+| `src/parse.pas` | 1,816 | 1,685 | Declarations, statements, expressions, built-ins |
16+| `src/link.pas` | 131 | 95 | Tree shaking, layout, patching |
17+| `src/elf.pas` | 425 | 351 | Static and dynamic ELF, symbol table, line numbers |
18+| `src/jed.pas` | 191 | 151 | The command line, the entry points |
19+
20+Every file opens with a comment that says what it is, what it depends
21+on and what it leaves out. Read those first; they are the map.
22+
23+## The shape of it
24+
25+There is one pass and no tree. The parser reads a construct and, in
26+the same breath, has the code generator emit its machine code. Nothing
27+is kept to be looked at again, except the declarations, which live in
28+the symbol table for as long as the compiler runs.
29+
30+The code generator is a stack machine through `rax`. An expression's
31+value is computed into `rax`; when a second operand has to be computed,
32+the first is pushed, and popped into `rcx` when both are ready. No
33+register is ever allocated, so there is no register allocator, and
34+every access the program writes is one instruction, in the order
35+written. That is also why `VOLATILE` costs the compiler nothing: it
36+never does anything clever to begin with.
37+
38+The output is a set of *chunks*: one for each procedure, each module
39+variable, each string. Code refers to other chunks through *fixups*,
40+which aren't resolved until the end. When everything is compiled, the
41+linker marks the chunks the entry point can reach, gives each an
42+address, patches the fixups, and the ELF writer puts them in a file.
43+Whatever nothing reaches never makes it into the executable.
44+
45+All modules are compiled in one run, from source: there are no object
46+files, no symbol files, and nothing to keep up to date.
47+
48+## Following one program
49+
50+`jed Hello.jed` does this:
51+
52+1. `jed.pas` reads the command line and calls `CompileMain`
53+ (`parse.pas`).
54+2. `CompileMain` imports `Rt` first, since every program needs it, and
55+ then compiles `Hello.jed` with `CompileFile`.
56+3. `CompileFile` opens the file in the scanner and parses the module.
57+ At `import Out;` it calls `ImportModule`, which finds `Out.jed` and
58+ compiles it there and then, saving and restoring the scanner and the
59+ scopes around it. So modules are finished in an order where each
60+ comes after those it imports; that is the order their bodies run.
61+4. Each procedure becomes a chunk of code; `Out.str("hello, world\n")`
62+ becomes a string chunk, a call, and a fixup to `Out.str`'s chunk.
63+5. Back in `jed.pas`, `Use` marks the modules the program uses; the
64+ entry point, `_start`, is written as one more chunk: save `argc` and
65+ `argv`, call every used module's body, call `main`, call `Rt.exit`.
66+6. `WriteElf` (`elf.pas`) has `link.pas` mark what `_start` reaches,
67+ place it and patch it, then writes headers, code, data, symbols and
68+ line numbers.
69+
70+## A procedure, compiled
71+
72+```
73+proc scale(a, b: I64): I64;
74+begin
75+ return a + b * 2;
76+end;
77+```
78+
79+comes out as this (from `objdump -d -M intel`):
80+
81+```
82+push rbp ; EnterBody: the frame
83+mov rbp,rsp
84+sub rsp,0x10 ; its size, patched in by EndProc
85+mov r10,0xfffffffffffffffe ; zero the frame, a quadword at a
86+xor eax,eax ; time, r10 counting up to zero
87+mov QWORD PTR [rbp+r10*8+0x0],rax
88+add r10,0x1
89+jne <back to the mov>
90+mov QWORD PTR [rbp-0x8],rdi ; the parameters, into their slots
91+mov QWORD PTR [rbp-0x10],rsi
92+mov rax,QWORD PTR [rbp-0x8] ; a
93+push rax ; kept while b * 2 is computed
94+mov rax,QWORD PTR [rbp-0x10] ; b
95+push rax ; kept while 2 is read
96+pop rax
97+mov ecx,0x2 ; the constant goes straight to rcx
98+imul rax,rcx
99+mov rcx,rax
100+pop rax ; a again
101+add rax,rcx
102+jmp <leave> ; return
103+xor eax,eax ; running off the end returns zero
104+movq xmm0,rax
105+leave
106+ret
107+```
108+
109+Every line of it can be traced to a routine in `gen.pas`; the pushes
110+and pops are `Op1` and `Op2`, the frame `EnterBody` and `EndProc`. It
111+is not fast code. It is code whose every instruction you can account
112+for, which is the point.
113+
114+## scan.pas: the scanner
115+
116+The scanner turns bytes into symbols (`TSym`). The current symbol is in
117+`tok`, with its value in `ival` (integers and characters), `rval`
118+(reals), `id` (identifiers) or `sbuf` and `slen` (strings, already
119+decoded).
120+
121+Read `Next` first: it skips white space and comments (`Comment`, which
122+counts nesting), then dispatches on the first character. `Number`
123+handles decimal, `0FFH`-style hexadecimal and reals; `LitChar` handles
124+one character of a literal, escapes included.
125+
126+Identifiers are *interned*: `Intern` puts each distinct name once in a
127+pool and hands back a small integer, so every later comparison of names
128+is a comparison of integers. The reserved words are interned first, in
129+the order of `TSym`, so a name's number tells at once whether it is a
130+reserved word.
131+
132+Source is UTF-8, checked by `Utf8` wherever a byte above 127 appears:
133+in strings, characters and comments. Anywhere else it is an error.
134+
135+Errors go through `Mark`, which prints `file:line:column` (the column
136+counted in characters, by `Column`) and stops. There is no recovery:
137+the first error ends the compilation. `SaveScan` and `RestoreScan` keep
138+the scanner's state while an imported module is compiled.
139+
140+## sym.pas: types, objects and scopes
141+
142+Two records hold everything the compiler knows about a program.
143+
144+`TType` is a type. Its `form` says what kind (`fInt`, `fPtr`, `fArray`,
145+`fRecord`, `fVariant`, `fProc`, and so on), and the other fields mean
146+what that form needs: `base` is what a pointer points at, an array or
147+slice holds, or a procedure returns; `fields` lists a record's fields,
148+a variant's cases, a procedure's parameters; `len` counts an array's
149+elements. `size` and `align` are worked out when the type is built, by
150+the C rules. `obj` is the declaration that named the type, if any.
151+
152+`TObj` is anything a name can stand for: a constant, type, variable,
153+procedure, module, field, variant case or built-in (`cls`). Where it
154+lives is decided here too: a module variable's chunk, a local's frame
155+offset in `val`, a procedure's chunk.
156+
157+Scopes are numbers. The universe is 0; each module, procedure, record
158+and match arm gets a new one from `NewScope`. All objects of all scopes
159+sit in one open-addressed hash table, keyed by scope and name: `Find`
160+looks in one scope, `Lookup` in each open scope from the innermost out.
161+A lookup costs the same however big a program grows, which matters at
162+a million lines a second.
163+
164+`Same` and `Alike` decide whether two types are the same: one
165+declaration for named types, built alike otherwise. `Fingerprint`
166+hashes what a declaration exports, for the check that a module's files
167+for different targets agree. The universe, the basic types and built-in
168+procedures, is set up in the unit's `initialization`.
169+
170+## x64.pas: machine code
171+
172+Code is written into one growing buffer, `code`, with `pc` its length;
173+strings go to `rodata`. A chunk (`TChunk`) records its section, where
174+its bytes start, how many, and the fixups it makes. `BeginChunk` and
175+`EndChunk` bracket a procedure; `SetData` and `SetBss` make data
176+chunks.
177+
178+A *fixup* (`TFixup`) is a 32-bit field in the code that will hold the
179+distance to another chunk: a call's target, or a rip-relative address.
180+`AddFixup` records one; `link.pas` fills them in.
181+
182+Jumps within a procedure don't wait for the linker. A label not yet
183+placed is a chain of the jumps to it, each jump's 32-bit field holding
184+the position of the one before (`Jmp`, `Jcc`); `FixLink` walks the
185+chain and patches each once the label's position is known. This is the
186+trick from Wirth's compilers, and it means a label is one integer.
187+
188+The encoder is `OpM` and `OpR`: a prefix, the REX byte, the opcode, the
189+ModRM and SIB bytes and the displacement, for a register and a memory
190+operand (`TMem`) or two registers. Everything else (`MovRR`, `Load`,
191+`Store`, `Alu`, `Sse`, ...) is a line or two that calls them with the
192+right opcode. Only the instructions the code generator uses are here.
193+`test/enctest.pas` emits one of each for `objdump` to check.
194+
195+Two more things live here because they are tied to code positions:
196+`NoteLine` records which source line the code from `pc` on belongs to,
197+for gdb; `ExternChunk` makes, once per C symbol, the quadword the
198+dynamic loader will fill with that symbol's address.
199+
200+## gen.pas: the code generator
201+
202+This is the heart, and the file to read slowly.
203+
204+An operand is an *item* (`TItem`), as in Wirth's compilers. Its `mode`
205+says what it is now:
206+
207+- `mConst`: a value known to the compiler, in `val`;
208+- `mVar`: a variable at an address the code can name: relative to
209+ `rbp` (`bFrame`), to a chunk (`bGlobal`), to a register (`bReg`), to
210+ an address pushed on the stack (`bStack`), or kept in a frame slot
211+ (`bSlot`); plus `off`;
212+- `mReg`: a value in `rax`; `mStack`: a value pushed on the stack;
213+- `mProc`, `mType`, `mStr`, and a few more the parser needs.
214+
215+Three routines move items towards the machine. `Value` brings a value
216+into `rax`, loading it with the one instruction its size needs.
217+`Address` brings a variable's address into a register. `Save` pushes
218+whatever an item has in a register, so that another expression can be
219+computed; the item remembers that it's on the stack. Read these three,
220+then `MemOf`, which turns an `mVar` into an x64 memory operand, popping
221+its address first if it was pushed.
222+
223+Expressions: `Op1` is called when the parser has seen an operator and
224+its left operand, `Op2` when it has the right one. `Op1` saves the left
225+operand (or, for `and` and `or`, emits the test that skips the right
226+one). `Op2` checks the types, folds constants (`FoldInt`, `FoldReal`),
227+and otherwise puts the left operand in `rax`, the right in `rcx`, and
228+emits the operation. Narrow integers are brought back to their width
229+after each operation (`Norm`), which is how `U8` arithmetic wraps.
230+
231+Variables: `Deref`, `Field`, `Index` and `Slice` turn an item for a
232+variable into an item for part of it, mostly by adding to `off`.
233+`Index` and `Slice` emit the bounds checks; `Check` jumps over a call
234+to `Rt.fail` with the file and line when the check holds.
235+
236+Assignment and conversion: `Coerce` makes a value fit the type it's
237+going to, or reports that it can't; it's where a string literal becomes
238+a slice, an array a slice, an untyped constant a typed one. `Assign`
239+stores, copying records and arrays with `rep movsb`. `Convert` is the
240+written conversion, `T(x)`.
241+
242+Calls: `BeginCall`, then `PassArg` for each argument, then `EndCall`.
243+Each argument is computed into a frame slot of its own, left to right;
244+only in `EndCall` are they loaded into the registers System V wants,
245+and the stack aligned for the call. A record passed by value goes as
246+the address of a copy; one returned comes back through a hidden pointer
247+in `rdi`, as C's structs do, and so do several results.
248+
249+Frames: `BeginProc` gives the parameters their slots; `EnterBody`
250+writes the prologue, including the loop that zeroes the frame;
251+`EndProc` writes the epilogue and patches the frame's size in. Within
252+a statement, scratch space comes from `AllocTemp` and is given back by
253+`ReleaseTemps`; `AllocPerm` reserves space for the whole procedure.
254+
255+## parse.pas: the parser
256+
257+A recursive descent parser, one routine for each rule of the grammar in
258+the report, calling `gen.pas` as it goes.
259+
260+Start with expressions, bottom up: `Factor`, `Term`, `SimpleExpr`,
261+`Expression`. Then `Designator`, which reads a name and what follows
262+it: `.field`, `^`, `[i]`, `[lo..hi]`, a call, a conversion. Each step
263+calls the matching routine in `gen.pas` on the item it has. The
264+`want` parameter carries the type an expression must have, where it is
265+known, so that `[1, 2, 3]`, `{x: 1}` and `{red}` know what to build.
266+
267+Then statements: `Statement` dispatches; `IfStatement`,
268+`WhileStatement`, `ForStatement` and `MatchStatement` emit their jumps
269+with `x64.pas`'s labels. `Defer` is worth reading: a deferred statement
270+is compiled where it stands, as a little subroutine of the procedure
271+that the code jumps over, and `RunDefers` emits a call to it at every
272+way out of its statement list: the end, `return` and `break`.
273+
274+Then declarations: `Declarations` reads `const`, `type`, `var`, `proc`
275+and `extern`. `ProcDecl` handles forward declarations, code procedures
276+(`CodeBody`, which just copies the bytes) and bodies (`Body`).
277+`ParseType` and its helpers (`RecordType`, `VariantType`, `Signature`,
278+`EnumType`) build `TType`s.
279+
280+Last, modules, at the end of the file. `CompileFile` reads one module.
281+`ImportModule` finds a module's file, trying the target's names first,
282+and compiles it if it isn't yet; `CheckSiblings` then reads the files
283+for other targets beside it, declarations only, and `CompareIface`
284+holds them to the same exports by their fingerprints. A generic module
285+is compiled once per distinct list of arguments: `ParseArgs` reads
286+them at the import, `Params` binds them to the module's parameters, and
287+`IsModule` decides whether an instance already exists.
288+
289+The built-in procedures are in `Builtin` (and `New_`, `Atomic`): each
290+parses its own arguments, since `SIZE` takes a type and `INC` a
291+variable.
292+
293+## link.pas: tree shaking and layout
294+
295+`MarkLive` starts from the entry chunk and follows fixups, marking each
296+chunk it reaches; nothing else goes into the executable. `LinkAll`
297+places the live chunks section by section (`Place`), each at its
298+alignment, then copies their bytes into the images of text and rodata,
299+patching every fixup with the distance from the end of its field to its
300+target.
301+
302+The layout is chosen so the file can be mapped as it lies: text just
303+after the headers, rodata on the next page, then a writable page that
304+begins with the dynamic loader's table (in a program that uses C) and
305+goes on as bss.
306+
307+## elf.pas: the executable
308+
309+`WriteElf` writes the ELF header, the program headers, the text and
310+rodata images, and then what isn't loaded: section headers, a symbol
311+table with every live procedure and variable by `Module.name`, and the
312+line table.
313+
314+A program that uses C is linked dynamically, in the least way the
315+loader accepts: an interpreter header naming the loader; a dynamic
316+section naming the libraries; and, for each C symbol the program uses,
317+a symbol and a `GLOB_DAT` relocation that has the loader write the
318+symbol's address into the quadword `ExternChunk` made. Code calls C
319+through that quadword. There is no PLT and no lazy binding.
320+`SizeTables` and `PutTables` lay these out in the room `link.pas` left
321+at the end of rodata.
322+
323+Line numbers are DWARF 4: `PutDebug` writes a line table with one
324+sequence per procedure, from the notes `NoteLine` made, and the single
325+compile unit gdb needs to find it. There are no types or variables in
326+it; gdb can stop at a line and show where it is, not print a variable.
327+
328+## jed.pas: the command line
329+
330+`jed.pas` parses the arguments, calls `CompileMain`, and works out what
331+the program uses: `Use` marks the modules imported from the main module
332+and `Rt`; `UsesC` decides whether the program is dynamic, refusing one
333+that both uses C and has a module saying `link static`. Then it writes
334+the entry point. A static program starts at `_start` itself. A dynamic
335+one starts at a `_start` that calls `__libc_start_main` the way C's own
336+start-up does, which sets C up and calls back a `main` that runs the
337+module bodies and the program's `main`.
338+
339+## Where to start changing it
340+
341+- **A built-in procedure:** an entry in `sym.pas`'s universe, a case in
342+ `Builtin` in `parse.pas`, and the code, in `gen.pas` or right there.
343+- **An instruction:** a routine in `x64.pas` built on `OpM` or `OpR`,
344+ and a line in `test/enctest.pas` to check its encoding.
345+- **A statement:** a reserved word in `scan.pas` (in `TSym` and `Words`,
346+ in the same order), a case in `Statement`, and a routine beside the
347+ others.
348+- **A check that fails:** `Check` in `gen.pas`, and the message in
349+ `lib/Rt.jed`'s `fail`.
350+
351+After any change: `make check`, `make bench`, `make loc`.