raz / commit ab022b0b

commit
ab022b0bd9f4e7aa301367381effc27b784533d7
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
6fafd396
Revise the report after the first review

Module bodies and an exported main in any module; zero values spelled
out and no undefined behaviour outside pointers; ERROR constants
compared by identity; string = and #; packed records; enumerations and
sets; record literals; NEW(p, a) only; break.

patch · log

2 files changed, +161 -56

PLAN.md (history) modified +7 -6

@@ -3,7 +3,7 @@
33 jed (Polish *jeden*, one) is a small systems language in Wirth's
44 tradition: full control of memory, volatile access, atomics, calls into
55 C, generic modules. Its compiler is meant to be read in a long weekend:
6-about 4,000 lines of Free Pascal, one pass, no IR, no optimizer, writing
6+about 4,300 lines of Free Pascal, one pass, no IR, no optimizer, writing
77 x86-64 machine code and the ELF file itself.
88
99 The language is defined by `doc/jed.md`. Where this plan and the report
@@ -44,17 +44,18 @@
4444 literals reachable from the entry point.
4545 9. Variadic arguments exist only to call C. jed code gets the same
4646 effect from a slice of a variant (`Fmt.print`).
47-10. Strings are a library over `[]U8`, not part of the language.
47+10. Strings are `[]U8`. The language compares them with `=`; the rest
48+ is a library.
4849
4950 ## The compiler, in reading order
5051
5152 | File | Lines | What |
5253 |---|---|---|
53-| `src/scan.pas` | ~350 | Symbols, literals, comments, error messages |
54-| `src/sym.pas` | ~350 | Types, objects, scopes, layout |
54+| `src/scan.pas` | ~360 | Symbols, literals, comments, error messages |
55+| `src/sym.pas` | ~390 | Types, objects, scopes, layout |
5556 | `src/x64.pas` | ~400 | Code buffer, chunks, fixups, instruction encoder |
56-| `src/gen.pas` | ~600 | Items: loading, storing, copying, frames, calls |
57-| `src/parse.pas` | ~1,500 | Declarations, statements, expressions, built-ins |
57+| `src/gen.pas` | ~660 | Items: loading, storing, copying, frames, calls |
58+| `src/parse.pas` | ~1,750 | Declarations, statements, expressions, built-ins |
5859 | `src/link.pas` | ~200 | Tree shaking, layout, patching |
5960 | `src/elf.pas` | ~450 | Static and dynamic ELF, symbol table |
6061 | `src/jed.pas` | ~100 | The command line |

doc/jed.md modified +154 -50

@@ -23,9 +23,11 @@
2323 end Hello.
2424 ```
2525
26-A program is a set of modules. One of them, the main module, has a
27-procedure `main`; the program starts there. Saved as `Hello.jed`, it is
28-compiled with `jed Hello.jed`, which writes the executable `Hello`.
26+A program is a set of modules. The one named on the command line is
27+the main module, and it exports a procedure `main`; the program starts
28+there, once every module's body has run (section 3). Saved as
29+`Hello.jed`, it is compiled with `jed Hello.jed`, which writes the
30+executable `Hello`.
2931
3032 ## 2. Words and symbols
3133
@@ -39,9 +41,9 @@
3941 **Reserved words** are lowercase, except `VOLATILE`:
4042
4143 ```
42-and begin by const div do else elsif end extern for forward if import
43-link match mod module not of or proc record repeat return shl shr then
44-to type until var variant VOLATILE while xor
44+and begin break by const div do else elsif end extern for forward if
45+import in link match mod module not of or packed proc record repeat
46+return set shl shr then to type until var variant VOLATILE while xor
4547 ```
4648
4749 **Numbers.** `123` is decimal. `0FFH` is hexadecimal: it starts with a
@@ -60,14 +62,15 @@
6062 **Operators and delimiters:**
6163
6264 ```
63-+ - * / = # < <= > >= := : ; , . .. ... ( ) [ ] ^ |
65++ - * / = # < <= > >= := : ; , . .. ... ( ) [ ] { } ^ |
6466 ```
6567
6668 ## 3. Modules
6769
6870 ```
6971 Module = "module" ident [ "(" ident { "," ident } ")" ] ";"
70- { Import } { Link } { Declaration } "end" ident "." .
72+ { Import } { Link } { Declaration }
73+ [ "begin" Statements ] "end" ident "." .
7174 Import = "import" ImportItem { "," ImportItem } ";" .
7275 ImportItem = ident [ ":=" ident [ "(" Type { "," Type } ")" ] ] .
7376 Link = "link" string ";" .
@@ -105,9 +108,12 @@
105108 module's directory, then in each directory given with `-I`, then in the
106109 `lib` directory beside the compiler.
107110
108-**No module bodies.** Module variables start at zero, and there is no
109-code that runs when a module starts. A module that needs setting up
110-does it on first use.
111+**Module bodies.** A module may end with `begin` and statements, its
112+body. Every module's body runs once, before the main module's `main`:
113+a module's body runs after the bodies of the modules it imports, in the
114+order of its `import`s, and once however many modules import it. Each
115+instance of a generic module has its body run once. Module variables
116+are zero before any body runs. `return;` ends a body early.
111117
112118 **`link "libX11.so.6";`** names a shared library to load at run time,
113119 for the `extern` procedures of section 9.
@@ -115,7 +121,7 @@
115121 ## 4. Declarations
116122
117123 ```
118-Declaration = "const" { IdentDef "=" Expr ";" }
124+Declaration = "const" { IdentDef [ ":" "ERROR" ] "=" Expr ";" }
119125 | "type" { IdentDef "=" Type ";" }
120126 | "var" { IdentList ":" Type ";" }
121127 | ProcDeclaration ";"
@@ -133,7 +139,12 @@
133139 literals, other constants, operators, `SIZE` and the `LEN` of arrays.
134140
135141 **Variables** of a module live as long as the program; variables of a
136-procedure live as long as its call. Both start at zero.
142+procedure live as long as its call. Both start at zero: every byte of
143+them is zero. So a number starts as `0` (`0.0` for `F64`), a `BOOL` as
144+`false`, a pointer, procedure or `ERROR` as `nil`, a slice as the empty
145+slice (`ptr` is `nil`, `len` is 0), a variant as its first case with
146+its fields zero, a set as the empty set, and an enumeration as its
147+first name. No variable is ever read before it has a value.
137148
138149 ## 5. Types
139150
@@ -142,8 +153,10 @@
142153 | "[" Expr "]" Type (* array *)
143154 | "[" "]" Type (* slice *)
144155 | "^" [ "VOLATILE" ] Type (* pointer *)
145- | "record" { IdentList ":" Type ";" } "end"
156+ | [ "packed" ] "record" { IdentList ":" Type ";" } "end"
146157 | "variant" { Case ";" } "end"
158+ | "(" ident { "," ident } ")" (* enumeration *)
159+ | "set" "of" QualIdent
147160 | "proc" Signature .
148161 Case = ident [ "(" FieldList { ";" FieldList } ")" ] .
149162 FieldList = ident { "," ident } ":" Type .
@@ -196,6 +209,12 @@
196209 multiple of its largest alignment. A record declared like a C struct
197210 has the same layout as that struct.
198211
212+A `packed record` has no padding: each field starts at the byte after
213+the field before it, and the record's alignment is 1. A field of a
214+packed record may be misaligned. x86-64 reads and writes it anyway, but
215+an atomic operation on it is slow, and a volatile access to it is one
216+instruction that needn't be atomic.
217+
199218 ### 5.6 Variants
200219
201220 A variant holds one of several cases, each with its own fields:
@@ -217,17 +236,59 @@
217236
218237 Layout: an `I64` tag (0 for the first case, 1 for the second, and so
219238 on) followed by the fields of the largest case, laid out as a record.
239+A variant that starts at zero therefore holds its first case.
220240
221-### 5.7 Procedure types
241+### 5.7 Enumerations and sets
222242
223243 ```
244+type
245+ Color* = (red, green, blue);
246+ Colors* = set of Color;
247+```
248+
249+An enumeration is a list of names, in order. Like the cases of a
250+variant, the names are declared in the scope around the type. An
251+enumeration has at most 256 names and takes 1 byte; the first name is
252+0, the next 1, and so on.
253+
254+`set of E`, for an enumeration `E` of at most 64 names, holds any
255+choice of `E`'s names: bit `i` stands for the name at position `i`. It
256+takes the smallest of 1, 2, 4 and 8 bytes that has a bit for each name,
257+so a set can stand for a C flags word.
258+
259+### 5.8 Errors
260+
261+```
262+const NotFound*: ERROR = "not found";
263+```
264+
265+`ERROR` is a basic type of 8 bytes. A value of it is made only by a
266+constant declared as above, and each such declaration makes an error
267+different from every other, whatever its message: two modules that
268+both declare `"not found"` have two different errors. A generic module
269+makes its errors once per instance. `nil` is no error.
270+
271+Errors compare with `=` and `#` only, by which declaration made them,
272+never by their message. `MSG(e)` is the message, a `[]U8`; `MSG(nil)`
273+is `""`.
274+
275+```
276+proc find*(key: I64): (^Node, ERROR);
277+...
278+n, err := Table.find(7);
279+if err = Table.NotFound then ... end;
280+```
281+
282+### 5.9 Procedure types
283+
284+```
224285 type Compare = proc(a, b: I64): BOOL;
225286 ```
226287
227288 A value of a procedure type is the address of a procedure with that
228289 signature, 8 bytes, or `nil`.
229290
230-### 5.8 Same and assignable
291+### 5.10 Same and assignable
231292
232293 Two named types are the same only if they are the same declaration.
233294 Two anonymous types are the same if they are built alike: `^I64` is
@@ -238,7 +299,7 @@
238299 the same type, or if:
239300
240301 - `A` is an integer constant whose value fits in the integer type `B`;
241-- `A` is `nil` and `B` is a pointer or procedure type;
302+- `A` is `nil` and `B` is a pointer, procedure or `ERROR` type;
242303 - `A` is `^T` and `B` is `^VOLATILE T`;
243304 - `A` is `[n]T` and `B` is `[]T`;
244305 - `A` is a string literal and `B` is `[]U8`, `^U8` (a pointer to the
@@ -248,13 +309,13 @@
248309
249310 Nothing else converts silently. In particular, there is no conversion
250311 between integer types, or between integers and `F64`, without a written
251-conversion (section 6.6).
312+conversion (section 6.7).
252313
253314 ## 6. Expressions
254315
255316 ```
256317 Expr = SimpleExpr [ Relation SimpleExpr ] .
257-Relation = "=" | "#" | "<" | "<=" | ">" | ">=" .
318+Relation = "=" | "#" | "<" | "<=" | ">" | ">=" | "in" .
258319 SimpleExpr = [ "-" ] Term { AddOp Term } .
259320 AddOp = "+" | "-" | "or" | "xor" .
260321 Term = Factor { MulOp Factor } .
@@ -262,7 +323,9 @@
262323 Factor = number | char | string | Designator | "(" Expr ")"
263324 | "not" Factor
264325 | "[" [ Expr { "," Expr } ] "]"
326+ | "{" [ Element { "," Element } ] "}"
265327 | "^" [ "VOLATILE" ] Type "(" Expr ")" .
328+Element = Expr | ident ":" Expr .
266329 Designator = QualIdent { Selector } .
267330 Selector = "." ident | "^" | "[" Expr [ ".." Expr ] "]"
268331 | "(" [ Expr { "," Expr } ] ")" .
@@ -281,11 +344,11 @@
281344 `200 + 100` is `44`.
282345
283346 `div` rounds toward zero and `mod` takes the sign of the dividend, as
284-in C: `-7 div 2` is `-3`, `-7 mod 2` is `-1`. Dividing by zero stops
285-the program (`SIGFPE`).
347+in C: `-7 div 2` is `-3`, `-7 mod 2` is `-1`. Dividing by zero, and
348+dividing the smallest `I64` by `-1`, stop the program (`SIGFPE`).
286349
287350 `and`, `or`, `xor` and `not` work on every bit. `x shl n` and
288-`x shr n` shift by `n mod 64`; `shr` brings in copies of the sign bit
351+`x shr n` shift by `n and 63`; `shr` brings in copies of the sign bit
289352 for signed types and zeros for unsigned ones.
290353
291354 Relations compare as signed or unsigned according to the type.
@@ -321,14 +384,39 @@
321384 A check that fails prints the file and line to standard error and stops
322385 the program with status 2.
323386
324-`[e1, e2, ...]` builds an array where the type it must have is known:
325-assigned to an array or slice variable, passed to such a parameter, or
326-returned as one. Its elements must be assignable to the element type.
387+**Literals.** `[e1, e2, ...]` builds an array, and `{f: e, g: e, ...}`
388+a record, where the type it must have is known: assigned to a variable,
389+passed to a parameter, returned, compared with a value of that type, or
390+an element of a bigger literal. The elements must be assignable to the
391+element type, and an array literal for `[n]T` has exactly `n` of them.
392+A record literal names its fields, in any order, each at most once; the
393+fields it leaves out are zero. An array literal used as a slice is a
394+hidden variable of the procedure, and lives as long as its call.
395+
396+```
397+c := {ch: 'A', attr: 7};
398+Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)]);
399+```
400+
401+**Strings compare.** Two operands that are each a `[]U8`, a `[n]U8` or
402+a string literal are `=` when they have the same length and the same
403+bytes, and `#` otherwise. Other arrays and slices, records and variants
404+can't be compared; write a loop. Ordering strings is the library's
405+`Str.cmp`.
406+
407+### 6.6 Enumerations and sets
408+
409+Enumerations compare with all six relations, by position, and an
410+enumeration can be the variable of a `for` loop and the expression of a
411+`match` (section 7.4).
327412
328-Arrays, slices, records and variants can't be compared; write a loop,
329-or use the library's `Str.eq` for strings.
413+`{red, blue}` is a set, of the set type of its names' enumeration;
414+`{}` is the empty set, where the type it must have is known. On two sets
415+of the same type, `+` is union, `*` intersection and `-` difference;
416+`=` and `#` compare, and `<=` and `>=` are "is a subset of" and "is a
417+superset of". `x in s` is `true` if the name `x` is in the set `s`.
330418
331-### 6.6 Conversions
419+### 6.7 Conversions
332420
333421 A type name applied like a procedure converts: `I32(x)`, `F64(n)`,
334422 `^Cell(addr)`. A pointer type written out uses the `^` form of the
@@ -338,20 +426,24 @@
338426 |---|---|---|
339427 | integer | integer | the value cut to the new width, or extended by its sign (signed) or zeros (unsigned) |
340428 | integer | `F64` | the nearest real |
341-| `F64` | integer | rounded toward zero |
429+| `F64` | integer | rounded toward zero; a NaN, or a real out of the range of `I64`, gives the smallest `I64`, then cut |
430+| enumeration | integer | its position |
431+| integer | enumeration | the name at that position; a position out of range is a failed check (6.5) |
432+| set | integer | its bits |
433+| integer | set | the low bits, as many as the set has |
342434 | integer | pointer, procedure | the address |
343435 | pointer, procedure | integer | the address |
344436 | pointer, procedure | pointer, procedure | the same address, seen as the new type |
345437
346-### 6.7 Built-in procedures
438+### 6.8 Built-in procedures
347439
348440 | Call | Result |
349441 |---|---|
350442 | `SIZE(T)` | the size of type `T` in bytes, a constant |
351443 | `ADR(x)` | the address of variable `x`, a `^T` |
352444 | `LEN(a)` | the number of elements of an array (a constant) or a slice, an `I64` |
353-| `NEW(p)` | sets `p: ^T` to a fresh, zeroed `T` from `Heap`; the module must import `Heap` |
354-| `NEW(p, a)` | the same, from the allocator `a: ^Mem.Allocator` |
445+| `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 |
446+| `MSG(e)` | the message of the error `e`, a `[]U8` |
355447 | `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`) |
356448 | `CODE(b1, b2, ...)` | puts the constant bytes in the code, see 7.7 |
357449 | `FENCE` | a full memory barrier |
@@ -377,7 +469,8 @@
377469 | "repeat" Statements "until" Expr
378470 | "for" ident ":=" Expr "to" Expr [ "by" Expr ] "do" Statements "end"
379471 | "match" Expr "of" { "|" Arm } "end"
380- | "return" [ Expr { "," Expr } ] .
472+ | "return" [ Expr { "," Expr } ]
473+ | "break" .
381474 Arm = ( ident [ "(" ident { "," ident } ")" ] | "else" ) ":" Statements .
382475 ```
383476
@@ -403,14 +496,15 @@
403496 negative). `s` is 1 if left out. `b` is evaluated once, before the
404497 first round.
405498
406-There is no `break` or `goto`. A loop that must stop early tests a
407-condition, or its body is a procedure that returns.
499+`break` ends the innermost `while`, `repeat` or `for` it stands in,
500+and the program goes on after it. There is no `goto`.
408501
409502 ### 7.3 Return
410503
411504 `return e;` ends the procedure with the result `e`; `return a, b;` with
412505 several results; `return;` from a procedure without results. A
413-procedure with results that runs off its end returns an undefined value.
506+procedure with results that runs off its end returns zeros, each result
507+as a variable of its type starts (section 4).
414508
415509 ### 7.4 Match
416510
@@ -428,6 +522,9 @@
428522 fields unnamed. Every case must have an arm, unless there is an
429523 `| else:` arm, which must come last.
430524
525+`match` on an enumeration works the same way: each arm names one of the
526+enumeration's names.
527+
431528 ### 7.5 Order of evaluation
432529
433530 Operands, arguments and the designators of an assignment are evaluated
@@ -437,9 +534,9 @@
437534
438535 A variable reached through a `^VOLATILE T` is volatile, and so is any
439536 field or element of it. Each read or write of a volatile variable of a
440-basic or pointer type is exactly one memory access, of exactly its
441-size, and volatile accesses happen in the order the program writes
442-them. Copying a whole record or array through a volatile pointer is
537+basic, enumeration, set or pointer type is exactly one memory access,
538+of exactly its size, and volatile accesses happen in the order the
539+program writes them. Copying a whole record or array through a volatile pointer is
443540 not allowed, since it can't be one access.
444541
445542 A `^VOLATILE T` doesn't convert to `^T` without a written conversion.
@@ -466,7 +563,7 @@
466563 ```
467564 ProcDeclaration = "proc" IdentDef Signature ";"
468565 ( "forward" | { LocalDeclaration } "begin" Statements "end" [ ident ] ) .
469-LocalDeclaration = "const" { ident "=" Expr ";" }
566+LocalDeclaration = "const" { ident [ ":" "ERROR" ] "=" Expr ";" }
470567 | "type" { ident "=" Type ";" }
471568 | "var" { ident { "," ident } ":" Type ";" } .
472569 Signature = "(" [ Params { ";" Params } [ ";" "..." ] ] ")" [ ":" Results ]
@@ -529,19 +626,26 @@
529626
530627 ## 10. Programs
531628
532-The main module declares `proc main;` or `proc main: I64;`. The program
533-runs `main`, and ends with status 0, or with the status `main` returns.
629+Any module may export a procedure `main`, declared `proc main*;` or
630+`proc main*: I64;`. The program runs the bodies of all its modules
631+(section 3), then the main module's `main`, if it has one, and ends
632+with status 0, or with the status `main` returns. The `main` of an
633+imported module is an ordinary procedure, which runs only if something
634+calls it; so a library module can carry a `main` that tests it.
534635 A program that calls no C is a static executable with no run time
535636 besides the code it uses. One that does is linked dynamically and
536637 starts through the C library, so that C's own set-up and clean-up run.
537638
538-Only what can be reached from `main` goes into the executable: unused
539-procedures, variables and strings are left out.
639+Only what can be reached from `main` and the module bodies goes into
640+the executable: unused procedures, variables and strings are left out.
540641
541-**Not checked.** Dereferencing `nil` or a stale pointer, indexing
542-through a pointer, integer overflow (it wraps), and a missing `return`
543-in a procedure with results. Dividing by zero and dereferencing `nil`
544-stop the program with a signal.
642+**Defined behaviour.** Every variable starts at zero, integers wrap,
643+and indexing arrays and slices is checked, so a program's behaviour is
644+defined by this report, with one exception: memory reached through a
645+pointer. Dereferencing a stale or made-up pointer, indexing through a
646+pointer, `CODE` that breaks its rules, and C code can read or write any
647+memory, and what follows isn't defined. Dereferencing `nil`, dividing
648+by zero and calling a `nil` procedure stop the program with a signal.
545649
546650 ## 11. The library
547651
@@ -549,10 +653,10 @@
549653
550654 | Module | What |
551655 |---|---|
552-| `Rt` | what the compiler's checks call when they fail |
656+| `Rt` | what the compiler's checks call when they fail, and string comparison |
553657 | `Out` | writing text and numbers to standard output |
554658 | `Mem` | `mmap`, and `Allocator`, the interface of every allocator |
555-| `Heap` | a general allocator; what `NEW(p)` uses |
659+| `Heap` | a general allocator |
556660 | `Arena` | an allocator that frees everything at once |
557661 | `Str` | operations on `[]U8` strings |
558662 | `Buf` | a growable byte buffer |