raz / commit 5afc418b

commit
5afc418b2ce7d02bbf448ac9db1b9d8dbe3456f3
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
553f16e8
raz -q: check and words, for an editor's language server

raz -q check Main.raz reads the main module's text from stdin and
writes each error, warning and note as a tab-split row on stdout
(file, line, col, end line, end col, kind, message); no program.
raz -q words Main.raz:LINE:COL reads on to the cursor, past any
errors, and writes the names that can be typed there: in scope, or
a module's exports after its dot.

Scan: setStdin, and the cursor as a symbol, atCursor, with what is
typed of it in prefix (one compare in next). Diag: Form, rows or
silent. Sym: offer, over reaches, shared with closest. Parse:
qualIdent calls complete at the cursor. Raz: -q, forEditor.
Tests in test/query; raz(1) FOR AN EDITOR; doc/compiler.md.

patch · log

14 files changed, +478 -56

README.md (history) modified +2 -0

@@ -93,6 +93,8 @@
9393
9494 raz [-I dir]... [-o file] [-Werror] [-S] [-s] [-noprofile] [-libc glibc|musl] [-base addr] [-bare] Main.raz
9595 raz run [option]... Main.raz [arg]...
96+ raz -q check [option]... Main.raz
97+ raz -q words [option]... Main.raz:LINE:COL
9698 raz -h
9799 raz --version
98100

doc/compiler.md (history) modified +53 -11

@@ -1,6 +1,6 @@
11 # Reading the raz compiler
22
3-The compiler is twelve files of raz, about 12,900 lines of code (the
3+The compiler is twelve files of raz, about 13,100 lines of code (the
44 budget is 14,000). It is its own compiler: a release of it, the one
55 `BOOT` names, builds `src/`, and `make fixpoint` checks that what it
66 makes makes itself again, byte for byte. Each release was built by the
@@ -16,18 +16,18 @@
1616
1717 | File | Lines | Code | What |
1818 |---|---|---|---|
19-| `src/Diag.raz` | 423 | 325 | Messages: positions, source excerpts, colour, counts |
20-| `src/Scan.raz` | 1,170 | 966 | Symbols, literals, comments, positions |
21-| `src/Sym.raz` | 815 | 652 | Types, objects, scopes, layout |
19+| `src/Diag.raz` | 472 | 358 | Messages: positions, source excerpts, colour, counts |
20+| `src/Scan.raz` | 1,260 | 1,036 | Symbols, literals, comments, positions |
21+| `src/Sym.raz` | 856 | 682 | Types, objects, scopes, layout |
2222 | `src/Chunk.raz` | 364 | 280 | The compiled program: chunks, fixups, line notes |
2323 | `src/X64.raz` | 1,777 | 1,450 | The instruction encoder, jumps within a procedure, the assembler |
2424 | `src/Gen.raz` | 2,846 | 1,989 | The stack machine, for x86-64: values, operations, checks, calls, frames |
2525 | `src/Item.raz` | 2,553 | 2,051 | Items: types, constants, variables, operators, conversions, calls |
26-| `src/Parse.raz` | 4,877 | 4,143 | Declarations, statements, expressions, built-ins, recovery, warnings |
26+| `src/Parse.raz` | 4,892 | 4,154 | Declarations, statements, expressions, built-ins, recovery, warnings |
2727 | `src/Link.raz` | 411 | 317 | Tree shaking, layout, patching, the places |
2828 | `src/Elf.raz` | 450 | 356 | Static and dynamic ELF, symbol table, line numbers |
2929 | `src/Host.raz` | 103 | 52 | The system running the compiler |
30-| `src/Raz.raz` | 439 | 343 | The command line |
30+| `src/Raz.raz` | 488 | 381 | The command line, and `-q` for an editor |
3131
3232 Every file opens with a comment that says what it is, what it depends
3333 on and what it leaves out. Read those first; they are the map.
@@ -2338,6 +2338,47 @@
23382338 the library last, after `-I` and `RAZ_PATH`, and the duplicate check
23392339 (a symbolic link to one of the two files chooses it) is as before.
23402340
2341+## raz -q: for an editor
2342+
2343+`raz -q` answers an editor's language server about the text it holds,
2344+saved or not, with the compiler itself, so that there is one grammar
2345+and one set of rules. It is a compile that writes no program, with
2346+three changes, each in the unit it concerns.
2347+
2348+- **The text from standard input.** `Raz.forEditor` gives `Scan` the
2349+ main module's path (`Scan.setStdin`); `Scan.open`, asked for that
2350+ path, reads standard input instead of the file. Imports are found
2351+ and read as ever.
2352+- **Messages as rows.** `Diag.form` is `pretty`, the messages a
2353+ person reads; `rows`, for `-q check`, where `show` writes each
2354+ error, warning and note as a line of tab-split fields on standard
2355+ output (`Diag.row`), and help, counts and the stop after
2356+ `MaxErrors` say nothing; or `silent`, for `-q words`, which says no
2357+ message at all and reads on past any number of errors, to reach the
2358+ cursor. After the main module is checked, `Raz.main` returns before
2359+ linking.
2360+- **The cursor is a symbol.** For `-q words`, `Scan` knows the byte
2361+ the cursor is at (`State.cursor`, `MAX(INT)` when there is none,
2362+ so that `next` pays one compare for it). When `next` comes to the
2363+ cursor, it makes the symbol there a name, `Scan.atCursor`, which no
2364+ source can spell (`(cursor)`), and keeps what is typed of the name
2365+ in `Scan.prefix`: the bytes from the start of the name the cursor is
2366+ in or just after, or none if it is between symbols. The parser reads
2367+ on as for any name; where `qualIdent` would look a name up, it
2368+ meets `atCursor` and calls `complete` instead, which writes the
2369+ names that reach there (`Sym.offer`, over the same test as
2370+ `closest`'s, `Sym.reaches`) and ends the compile. After `M.`, the
2371+ names are what `M` exports. A cursor inside a comment or a string
2372+ is dropped, so that it gives no names. Since `cursor` is part of the
2373+ scanner's state, a recovery or a read ahead that puts the state back
2374+ puts the cursor back too, and it is met again.
2375+
2376+What it leaves out: a record's fields after `r.`, which would need the
2377+type of an expression cut short; names declared further down, which a
2378+one-pass compiler hasn't met yet; and a
2379+main module that `Rt` imports already, as a module of `lib/` being
2380+edited, whose text is then the file's.
2381+
23412382 ## A program with its own Rt
23422383
23432384 A hosted program uses `lib/Rt.raz`. A freestanding one, a kernel's
@@ -2668,19 +2709,20 @@
26682709 | `Sys.close` | `Scan` and `Parse`: closes a source or `RAZ-VERSION` file after reading |
26692710 | `Sys.closeDir`, `Sys.openDir`, `Sys.nextEntry`, `Sys.Dir` | `Parse`: the files of a directory, to find a module's other files for the one-module-of-each-name check |
26702711 | `Sys.env`, `Sys.envAt` | `Diag` (`NO_COLOR`) and `Raz.userLibraries` (`RAZ_PATH`, `HOME`; `envAt` tells unset from empty) |
2671-| `Sys.errDenied`, `Sys.errNoEntry` | `Scan`: "permission denied" and "there is no such file" in a message |
2712+| `Sys.errDenied`, `Sys.errNoEntry`, `Sys.errIntr` | `Scan`: "permission denied" and "there is no such file" in a message; a read of standard input a signal broke into, tried again |
26722713 | `Sys.info`, `Sys.Info` | `Scan` and `Parse`: whether a path is a file (`file`) and its length (`size`) |
26732714 | `Sys.isTerminal` | `Diag`: colour only when standard error is a terminal |
26742715 | `Sys.openRead`, `Sys.read` | `Scan`: reads a source file whole; `Parse`: the library's `RAZ-VERSION` |
2716+| `Sys.stdin` | `Scan`: `raz -q`'s source, read from standard input |
26752717 | `Sys.readLink` | `Host.libraryDir`: `/proc/self/exe`, to find the library beside the compiler |
2676-| `Sys.stderr`, `Sys.write` | `Diag`: its messages |
2718+| `Sys.stderr`, `Sys.stdout`, `Sys.write` | `Diag`: its messages, or `raz -q check`'s rows on standard output |
26772719 | `Sys.workDir` | `Diag`: shows a path relative to the working directory; `Elf`: the compilation directory of the line table |
26782720
26792721 `Rt`, the run time, besides `fail`, `exit` and the places (above):
26802722
26812723 | Name | What for |
26822724 |---|---|
2683-| `Rt.exit` | `Diag`: ends the compiler, with status 1, after an error that stops it |
2725+| `Rt.exit` | `Diag`: ends the compiler, with status 1, after an error that stops it; `Parse`: with 0, once `raz -q words` has written its names |
26842726
26852727 `Files`, whole files and the command line:
26862728
@@ -2697,8 +2739,8 @@
26972739 |---|---|
26982740 | `Buf.Buf`, `Buf.init`, `Buf.add`, `Buf.str`, `Buf.bytes`, `Buf.reset`, `Buf.done` | A growing buffer: `Diag`'s message and working directory, a type's name in `Sym`, an instruction's text in `X64`, a name made in `Parse` |
26992741 | `Fmt.write`, `Fmt.Arg`, `Fmt.str`, `Fmt.int`, `Fmt.char`, `Fmt.hex` | Formatting: `Diag.say`'s `{}` messages and a type's name |
2700-| `Out.str`, `Out.ln`, `Out.flush` | Standard output: the `-S` listing, `-h` and `--version` |
2701-| `Str.copy`, `Str.find`, `Str.hasPrefix`, `Str.hexVal` | A kept copy of a path (`Diag`), the one-character operators (`Scan`), a prefix of a path, a file name or a mnemonic (`Diag`, `Parse`, `X64`), and a hex digit (`Parse`) |
2742+| `Out.str`, `Out.ln`, `Out.flush` | Standard output: the `-S` listing, `-h`, `--version` and `raz -q words`' names |
2743+| `Str.copy`, `Str.find`, `Str.findLast`, `Str.hasPrefix`, `Str.hexVal`, `Str.toInt` | A kept copy of a path (`Diag`), the one-character operators (`Scan`), a prefix of a path, a file name or a mnemonic (`Diag`, `Parse`, `X64`), and a hex digit (`Parse`); `-q words`' `FILE:LINE:COL` (`Raz`) |
27022744 | `Heap.heap`, `Mem.alloc`, `Mem.free` | The allocator that `NEW`, `Buf.init` and `Str.copy` are given, and the blocks of `Scan`'s tables and `Diag`'s lists |
27032745
27042746 ## This compiler's choices

doc/raz.1 (history) modified +84 -0

@@ -14,6 +14,14 @@
1414 .Op Ar option ...
1515 .Ar Main.raz
1616 .Op Ar arg ...
17+.Nm
18+.Fl q Cm check
19+.Op Ar option ...
20+.Ar Main.raz
21+.Nm
22+.Fl q Cm words
23+.Op Ar option ...
24+.Ar Main.raz : Ns Ar LINE : Ns Ar COL
1725 .Sh DESCRIPTION
1826 .Nm
1927 compiles the module in
@@ -167,6 +175,20 @@
167175 .Pa /lib/ld-musl-x86_64.so.1 ,
168176 and not glibc's, as Alpine has.
169177 A program without C needs no C library, and runs on either.
178+.It Fl q Cm check
179+For an editor: check
180+.Ar Main.raz ,
181+reading its text from standard input, as the editor holds it, and
182+write no program.
183+Each message is a row on standard output; see
184+.Sx FOR AN EDITOR .
185+.It Fl q Cm words
186+For an editor: with
187+.Ar Main.raz : Ns Ar LINE : Ns Ar COL
188+in place of
189+.Ar Main.raz ,
190+write the names that can be typed at that cursor, a row each, and
191+nothing else.
170192 .It Fl h , Fl \-help
171193 Say the options.
172194 .It Fl \-version
@@ -223,6 +245,68 @@
223245 .Nm
224246 .Cm run
225247 exits as the program does.
248+.Sh FOR AN EDITOR
249+.Fl q
250+is for an editor's language server, which asks of the text it holds,
251+saved or not.
252+The text of the main module comes from standard input; the modules it
253+imports are read from their files, found as for a compile.
254+Every row is fields split by tabs.
255+.Pp
256+.Fl q Cm check
257+gives a row for each error, warning and note:
258+.Bd -literal -offset indent
259+FILE LINE COL ENDLINE ENDCOL KIND MESSAGE
260+.Ed
261+.Pp
262+where the place runs from
263+.Ar LINE
264+and
265+.Ar COL
266+up to, not including,
267+.Ar ENDLINE
268+and
269+.Ar ENDCOL ,
270+lines and bytes in a line counted from 1, and
271+.Ar KIND
272+is
273+.Cm error ,
274+.Cm warning
275+or
276+.Cm note .
277+.Ar FILE
278+may be another module's, as for a note.
279+An error about no place in a file, as a module not found, has an empty
280+.Ar FILE
281+and zeros.
282+It exits 1 if there was an error, else 0.
283+.Pp
284+.Fl q Cm words
285+reads the module up to the cursor, past any errors, and gives a row for
286+each name that can be typed there and starts with what is typed of the
287+name the cursor is in or just after:
288+.Bd -literal -offset indent
289+KIND NAME TYPE
290+.Ed
291+.Pp
292+where
293+.Ar KIND
294+is
295+.Cm const ,
296+.Cm type ,
297+.Cm var ,
298+.Cm proc ,
299+.Cm module ,
300+.Cm field
301+or
302+.Cm builtin .
303+After a module's name and a dot, the names are those the module
304+exports; elsewhere, every name in scope there, a local hiding a global
305+of its name.
306+The rows come in no order.
307+Inside a comment or a string, after a record's dot, or where a name is
308+declared, there are none.
309+It exits 0.
226310 .Sh LISTING
227311 The listing of
228312 .Fl S

src/Diag.raz (history) modified +63 -14

@@ -8,6 +8,9 @@
88 NO_COLOR isn't set. Diag keeps every source file it is given, so
99 that a note can show a line of a module compiled earlier.
1010
11+ For an editor (raz -q), messages are rows on standard output
12+ instead, or not given at all (form).
13+
1114 Depends on: Sys, to write and to ask about the terminal; Buf and Fmt,
1215 to build what it writes.
1316 Leaves out: wording. The callers say what is wrong, with say; a
@@ -23,6 +26,11 @@
2326 a = b marks the place between two characters. *)
2427 Pos* = record f*, a*, b*: INT; end;
2528
29+ (* How messages are given: shown to a person on standard error; as
30+ rows on standard output, for an editor (raz -q check); or not at
31+ all (raz -q words, which says only names) *)
32+ Form* = (pretty, rows, silent);
33+
2634 File = record
2735 path: []const U8;
2836 buf: ^U8;
@@ -45,6 +53,7 @@
4553 (* The construct being read uses a name already reported as not
4654 declared: its errors follow from that one, and aren't shown. *)
4755 quiet*: BOOL;
56+ form*: Form;
4857
4958 files: ^File; (* numFiles of them, in room for cap *)
5059 numFiles, cap: INT;
@@ -65,6 +74,11 @@
6574 quiet := yes;
6675 end;
6776
77+proc setForm*(f: Form);
78+begin
79+ form := f;
80+end;
81+
6882 (* Paths are shown from the working directory where they are under it,
6983 so messages read the same wherever the compiler or its library is. *)
7084 proc shownPath*(path: []const U8): []const U8;
@@ -177,13 +191,15 @@
177191 paintOn(Plain);
178192 end;
179193
180-(* What has been made, written to standard error *)
194+(* What has been made, written to standard error, or the rows to
195+ standard output *)
181196 proc flush;
182-var s: []const U8; n: INT;
197+var s: []const U8; n, fd: INT;
183198 begin
184199 s := Buf.bytes(out);
200+ if form = Form.rows then fd := Sys.stdout; else fd := Sys.stderr; end;
185201 while LEN(s) > 0 do
186- n := Sys.write(Sys.stderr, s);
202+ n := Sys.write(fd, s);
187203 if n <= 0 then break; end;
188204 s := s[n..LEN(s)];
189205 end;
@@ -231,12 +247,36 @@
231247 return n;
232248 end;
233249
250+(* A message as raz -q check gives it, a row for an editor: the file,
251+ the line and the byte in the line where p starts, the same where it
252+ ends, the kind and the message, split by tabs; all from 1. A message
253+ about no place in a file has no file, and zeros. *)
254+proc row(p: Pos; kind, msg: []const U8);
255+var line, start, endLine, endStart: INT; e: Pos;
256+begin
257+ if p.f >= numFiles then
258+ Fmt.write(out, "\t0\t0\t0\t0\t{}\t{}\n", [Fmt.str(kind), Fmt.str(msg)]);
259+ else
260+ line, start := locate(p);
261+ e := p;
262+ e.a := p.b;
263+ endLine, endStart := locate(e);
264+ Fmt.write(out, "{}\t{}\t{}\t{}\t{}\t{}\t{}\n", [Fmt.str(files[p.f].path), Fmt.int(line),
265+ Fmt.int(p.a - start + 1), Fmt.int(endLine), Fmt.int(p.b - endStart + 1), Fmt.str(kind), Fmt.str(msg)]);
266+ end;
267+ flush;
268+end;
269+
234270 (* "file:line:col: kind: msg", then the line with p underlined. A tab
235271 before p is copied into the underline, so that the two line up
236272 whatever the terminal makes of tabs. *)
237273 proc show(p: Pos; kind, kindColour, msg: []const U8);
238274 var line, start, stop, lo, hi, i, n: INT; buf: ^U8; f: ^File; digits: []const U8;
239275 begin
276+ if form # Form.pretty then
277+ if form = Form.rows then row(p, kind, msg); end;
278+ return;
279+ end;
240280 if p.f >= numFiles then
241281 (* about no place in a file, as for Rt, which the compiler
242282 imports before it reads one *)
@@ -348,11 +388,14 @@
348388 lastError := p;
349389 show(p, "error", Red, msg);
350390 INC(errors);
351- if errors >= MaxErrors then
352- put("raz: stopping after ");
353- putNum(MaxErrors);
354- put(" errors\n");
355- flush;
391+ (* raz -q words reads on to the cursor, past any number of errors *)
392+ if (errors >= MaxErrors) and (form # Form.silent) then
393+ if form = Form.pretty then
394+ put("raz: stopping after ");
395+ putNum(MaxErrors);
396+ put(" errors\n");
397+ flush;
398+ end;
356399 Rt.exit(1);
357400 end;
358401 end;
@@ -376,7 +419,7 @@
376419
377420 proc help*(msg: []const U8);
378421 begin
379- if shown then
422+ if shown and (form = Form.pretty) then
380423 paint(Green, "help:");
381424 put(" ");
382425 put(msg);
@@ -389,10 +432,14 @@
389432 read: it stops the compiler at once. *)
390433 proc fatal*(msg: []const U8);
391434 begin
392- put("raz: ");
393- put(msg);
394- putc('\n');
395- flush;
435+ if form = Form.pretty then
436+ put("raz: ");
437+ put(msg);
438+ putc('\n');
439+ flush;
440+ elsif form = Form.rows then
441+ row({f: MAX(INT), a: 0, b: 0}, "error", msg);
442+ end;
396443 Rt.exit(1);
397444 end;
398445
@@ -406,7 +453,9 @@
406453 if there were errors. *)
407454 proc finish*;
408455 begin
409- if (errors > 0) and (warnings > 0) then
456+ if form # Form.pretty then
457+ (* no count: each message was a row of its own, or none *)
458+ elsif (errors > 0) and (warnings > 0) then
410459 put("raz: "); put(count(errors, "error")); put(", "); put(count(warnings, "warning")); putc('\n');
411460 elsif errors > 0 then
412461 put("raz: "); put(count(errors, "error")); putc('\n');

src/Parse.raz (history) modified +16 -1

@@ -26,7 +26,7 @@
2626 Scan.Sym is a chain of tests, since it has more names than a set
2727 holds. *)
2828 module Parse;
29-import Fmt, Diag, Scan, Sym, Chunk, Gen, Item, Sys, Str, Buf, Heap;
29+import Fmt, Diag, Scan, Sym, Chunk, Gen, Item, Sys, Str, Buf, Heap, Out, Rt;
3030 import SYSTEM;
3131
3232 type
@@ -558,10 +558,24 @@
558558 [Fmt.str(a), Fmt.str(nameOf(o^.name)), Fmt.str(b), Fmt.str(nameOf(o^.name))]));
559559 end;
560560
561+(* raz -q words: the current symbol is the cursor, where a name of
562+ scope s can be typed, or of any scope open if s < 0. The names that
563+ start with what is typed are written, and the compile ends. *)
564+proc complete(s: INT);
565+var b: Buf.Buf;
566+begin
567+ Buf.init(b, Heap.heap);
568+ Sym.offer(s, Scan.prefix, b);
569+ Out.str(Buf.bytes(b));
570+ Out.flush();
571+ Rt.exit(0);
572+end;
573+
561574 proc qualIdent: (PObj, ERROR);
562575 var o: PObj; m: PModule; at: Diag.Pos;
563576 begin
564577 if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
578+ if Scan.id = Scan.atCursor then complete(-1); end;
565579 at := Scan.tokPos();
566580 o := Sym.lookup(Scan.id);
567581 if o = nil then
@@ -579,6 +593,7 @@
579593 try expect(Scan.sPeriod);
580594 if Scan.tok # Scan.sIdent then return nil, expected("a name"); end;
581595 m := o^.home;
596+ if Scan.id = Scan.atCursor then complete(m^.scope); end;
582597 o := Sym.find(m^.scope, Scan.id);
583598 if (o = nil) or not o^.exported then
584599 Diag.error(Scan.tokPos(), say2("{} isn't exported by {}", nameOf(Scan.id), nameOf(m^.name)));

src/Raz.raz (history) modified +52 -3

@@ -2,6 +2,7 @@
22
33 raz [-I dir]... [-o file] [-Werror] [-S] [-libc glibc|musl] [-base addr] [-bare] Main.raz
44 raz run [-I dir]... Main.raz [arg]...
5+ raz -q check|words [-I dir]... Main.raz[:LINE:COL]
56 raz --version
67
78 Compiles the main module and every module it imports, writes the
@@ -10,7 +11,10 @@
1011 the main module's code instead. raz run writes it to a memfd
1112 instead, a file that lives only in memory, and executes it in raz's
1213 place with the arguments after Main.raz, so its status is the
13- program's; its argv[0] is Main.raz.
14+ program's; its argv[0] is Main.raz. raz -q, for an editor, reads
15+ the main module's text from standard input and stops once it is
16+ checked: check writes its messages as rows, and words the names
17+ that can be typed at the cursor (forEditor).
1418
1519 The program starts by saving argc and argv, runs every module's body
1620 (those of the modules the program imports, imported modules first),
@@ -29,7 +33,7 @@
2933 Leaves out: the work itself; the other units compile, link and
3034 write, and this only reads the command line and runs them in order. *)
3135 module Raz;
32-import Sys, Out, Version, Files, Host, Fmt, Diag, Scan, Sym, Chunk, X64, Gen, Parse, Link, Elf;
36+import Sys, Out, Str, Version, Files, Host, Fmt, Diag, Scan, Sym, Chunk, X64, Gen, Parse, Link, Elf;
3337 import SYSTEM;
3438
3539 const
@@ -118,6 +122,41 @@
118122 return INT(v), true;
119123 end;
120124
125+(* The file, line and column of raz -q words' FILE:LINE:COL; false if
126+ it isn't one *)
127+proc cursorAt(s: []const U8): ([]const U8, INT, INT, BOOL);
128+var i, j: INT; line, col: I64; ok1, ok2: BOOL;
129+begin
130+ j := Str.findLast(s, ":");
131+ if j <= 0 then return s, 0, 0, false; end;
132+ i := Str.findLast(s[0..j], ":");
133+ if i <= 0 then return s, 0, 0, false; end;
134+ line, ok1 := Str.toInt(s[i + 1..j]);
135+ col, ok2 := Str.toInt(s[j + 1..LEN(s)]);
136+ return s[0..i], INT(line), INT(col), ok1 and ok2 and (line >= 1) and (col >= 1);
137+end;
138+
139+(* raz -q, for an editor: the main module's text is standard input,
140+ and messages are rows (check) or not given (words, whose path names
141+ the cursor). The result is the main module's path. *)
142+proc forEditor(query, path: []const U8): []const U8;
143+var line, col: INT; ok: BOOL;
144+begin
145+ line := 0;
146+ col := 0;
147+ if query = "check" then
148+ Diag.setForm(Diag.Form.rows);
149+ elsif query = "words" then
150+ path, line, col, ok := cursorAt(path);
151+ if not ok then Diag.fatal(say1("-q words {}: expected FILE:LINE:COL", path)); end;
152+ Diag.setForm(Diag.Form.silent);
153+ else
154+ Diag.fatal(say1("-q {}: expected check or words", query));
155+ end;
156+ Scan.setStdin(path, line, col);
157+ return path;
158+end;
159+
121160 (* What raz -h says *)
122161 proc usage;
123162 begin
@@ -139,6 +178,10 @@
139178 Out.str(" runs no body of Rt, which sets the signals' handlers\n");
140179 Out.str(" -libc name links a program that uses C against glibc or musl; by\n");
141180 Out.str(" default glibc, or musl where only its loader is there\n");
181+ Out.str(" -q check for an editor: checks Main.raz, its text read from standard\n");
182+ Out.str(" input, and writes each message as a row (see raz(1))\n");
183+ Out.str(" -q words with Main.raz:LINE:COL, writes the names that can be\n");
184+ Out.str(" typed at the cursor there, one row each\n");
142185 Out.str(" -h, --help says this\n");
143186 Out.str(" --version says the version, and the report it follows\n");
144187 Out.str("see raz(1), and the report, doc/raz.md\n");
@@ -272,11 +315,12 @@
272315 i, first, entry, last, base: INT;
273316 m, rt, thread: ^Sym.Module; mainObj: ^Sym.Obj;
274317 run, noProfile, listing, dynamic, libcSaid, ok, bare: BOOL; err: ERROR;
275- libDir: []const U8;
318+ libDir, query: []const U8;
276319 begin
277320 path := "";
278321 outPath := "";
279322 libDir := "";
323+ query := "";
280324 noProfile := false;
281325 bare := false;
282326 listing := false;
@@ -312,6 +356,9 @@
312356 if not ok or (base mod Link.Page # 0) then
313357 Diag.fatal(say1("-base {}: expected an address, a multiple of 4096 as raz writes it, as 0FFFFFFFF80000000H", Files.arg(i)));
314358 end;
359+ elsif s = "-q" then
360+ INC(i);
361+ query := Files.arg(i);
315362 elsif s = "-noprofile" then
316363 noProfile := true;
317364 elsif s = "-bare" then
@@ -342,6 +389,7 @@
342389 usage();
343390 return 1;
344391 end;
392+ if LEN(query) > 0 then path := forEditor(query, path); end;
345393 if run and (LEN(outPath) > 0) then Diag.fatal("raz run takes no -o"); end;
346394 if run then
347395 (* asked now, before any source is read: its error is the refusal *)
@@ -384,6 +432,7 @@
384432 if Diag.errors > 0 then Diag.finish(); end;
385433 end;
386434 Diag.finish();
435+ if LEN(query) > 0 then return 0; end; (* checked: an editor wants no program *)
387436
388437 if rt = nil then Diag.fatal("can't find module Rt"); end;
389438 (* what Rt is given: the places, which the linker makes, for Rt to say

src/Scan.raz (history) modified +107 -17

@@ -6,6 +6,12 @@
66 compares names as small integers. The scanner also says where the
77 current symbol is, for messages.
88
9+ For an editor (raz -q), one file's text may come from standard
10+ input instead (setStdin), and a place in it may be marked: the
11+ symbol there is a name, atCursor, standing for what is typed of the
12+ name at the cursor, prefix, so that the parser can say what names
13+ can be typed there.
14+
915 Depends on: Sys, to read files; Diag, to report errors.
1016 Leaves out: recovery from errors in the text itself, such as a string
1117 not closed: the first such error stops the compiler. The parser goes
@@ -44,6 +50,8 @@
4450 rval: F64;
4551 id: INT;
4652 f: INT; (* the file, as Diag knows it *)
53+ cursor: INT; (* raz -q words: the byte the cursor is at, until
54+ the symbol there is made; else MAX(INT) *)
4755 end;
4856
4957 const
@@ -80,6 +88,11 @@
8088 error, so slips in it aren't reported again. *)
8189 skipping*: BOOL;
8290
91+ atCursor*: INT; (* the name the symbol at the cursor has *)
92+ prefix*: []const U8; (* what is typed of the name at the cursor *)
93+ stdinPath: []const U8; (* the file whose text is standard input, or "" *)
94+ cursorLine, cursorCol: INT; (* the cursor in it, from 1, or 0 for none *)
95+
8396 (* Whether a byte may be in a name: a letter, a digit or _. A table,
8497 since the loop that reads a name asks it of every byte. *)
8598 nameChar: [256]BOOL;
@@ -487,28 +500,80 @@
487500 return n < NumWords;
488501 end;
489502
503+(* raz -q: the text of the file at path is standard input, and the
504+ cursor is at line and col there (bytes, from 1), or nowhere if 0 *)
505+proc setStdin*(path: []const U8; line, col: INT);
506+begin
507+ stdinPath := path;
508+ cursorLine := line;
509+ cursorCol := col;
510+end;
511+
512+(* Standard input, read whole; its length is the second result *)
513+proc readStdin: (^U8, INT);
514+var buf: ^U8; n, size, r: INT;
515+begin
516+ size := 65536;
517+ buf := grab(size);
518+ n := 0;
519+ r := 1;
520+ while r # 0 do
521+ if n + 1 = size then
522+ buf := regrab(buf, n, 2 * size);
523+ size := 2 * size;
524+ end;
525+ r := Sys.read(Sys.stdin, buf[n..size - 1]);
526+ if r > 0 then
527+ n := n + r;
528+ elsif (r < 0) and (r # Sys.errIntr) then
529+ Diag.fatal("can't read standard input");
530+ end;
531+ end;
532+ return buf, n;
533+end;
534+
535+(* The byte of buf, n long, at line and col, both from 1; n if past it *)
536+proc byteAt(buf: ^U8; n, line, col: INT): INT;
537+var i, l: INT;
538+begin
539+ i := 0;
540+ l := 1;
541+ while (i < n) and (l < line) do
542+ if buf[i] = '\n' then INC(l); end;
543+ INC(i);
544+ end;
545+ if i + col - 1 < n then return i + col - 1; end;
546+ return n;
547+end;
548+
490549 (* Reads the file at path to scan it; "" if it can, else why not *)
491550 proc open*(path: []const U8): []const U8;
492551 var fd, n, got, r, err: INT; info: Sys.Info;
493552 begin
494- info, err := Sys.info(path);
495- if err = Sys.errNoEntry then return "there is no such file"; end;
496- if err = Sys.errDenied then return "permission denied"; end;
497- if err < 0 then return "it can't be opened"; end;
498- if not info.file then return "it isn't a file"; end;
499- fd := Sys.openRead(path);
500- if fd = Sys.errNoEntry then return "there is no such file"; end;
501- if fd = Sys.errDenied then return "permission denied"; end;
502- if fd < 0 then return "it can't be opened"; end;
503- n := INT(info.size);
504- cur.buf := grab(n + 1);
505- got := 0;
506- while got < n do
507- r := Sys.read(fd, cur.buf[got..n]);
508- if r <= 0 then Diag.fatal(Diag.say("can't read {}", [Fmt.str(path)])); end;
509- got := got + r;
553+ cur.cursor := MAX(INT);
554+ if (LEN(stdinPath) > 0) and (path = stdinPath) then
555+ cur.buf, n := readStdin();
556+ if cursorLine > 0 then cur.cursor := byteAt(cur.buf, n, cursorLine, cursorCol); end;
557+ else
558+ info, err := Sys.info(path);
559+ if err = Sys.errNoEntry then return "there is no such file"; end;
560+ if err = Sys.errDenied then return "permission denied"; end;
561+ if err < 0 then return "it can't be opened"; end;
562+ if not info.file then return "it isn't a file"; end;
563+ fd := Sys.openRead(path);
564+ if fd = Sys.errNoEntry then return "there is no such file"; end;
565+ if fd = Sys.errDenied then return "permission denied"; end;
566+ if fd < 0 then return "it can't be opened"; end;
567+ n := INT(info.size);
568+ cur.buf := grab(n + 1);
569+ got := 0;
570+ while got < n do
571+ r := Sys.read(fd, cur.buf[got..n]);
572+ if r <= 0 then Diag.fatal(Diag.say("can't read {}", [Fmt.str(path)])); end;
573+ got := got + r;
574+ end;
575+ Sys.close(fd);
510576 end;
511- Sys.close(fd);
512577 cur.buf[n] := 0; (* the sentinel that ends every scan *)
513578 cur.len := n;
514579 cur.pos := 0;
@@ -713,6 +778,7 @@
713778 end;
714779 until depth = 0;
715780 cur.commentEnd := cur.pos;
781+ if (open < cur.cursor) and (cur.cursor < cur.pos) then cur.cursor := MAX(INT); end; (* no names in a comment *)
716782 end;
717783
718784 (* Reading a decimal real exactly: the F64 nearest to digits times 10 to
@@ -1014,6 +1080,16 @@
10141080 tok := sString;
10151081 end;
10161082
1083+(* Makes the current symbol the name at the cursor, typed from start up
1084+ to at; the cursor is passed then *)
1085+proc cursorName(start, at: INT);
1086+begin
1087+ prefix := cur.buf[start..at];
1088+ cur.cursor := MAX(INT);
1089+ tok := sIdent;
1090+ id := atCursor;
1091+end;
1092+
10171093 (* Reads the next symbol *)
10181094 proc next*;
10191095 var c: U8; start, h, v, i, p: INT; buf: ^U8;
@@ -1045,6 +1121,15 @@
10451121 cur.tokPos := p;
10461122 cur.tokLine := cur.line;
10471123 cur.tokLineStart := cur.lineStart;
1124+ if p >= cur.cursor then
1125+ (* the cursor is before this symbol: if it was between symbols, not
1126+ in a string or a comment, a name of nothing typed is made there *)
1127+ if cur.prevEnd <= cur.cursor then
1128+ cursorName(cur.cursor, cur.cursor);
1129+ return;
1130+ end;
1131+ cur.cursor := MAX(INT);
1132+ end;
10481133 if single[c] # sNull then
10491134 INC(cur.pos);
10501135 tok := single[c];
@@ -1055,6 +1140,10 @@
10551140 start := p;
10561141 repeat INC(p); until not nameChar[buf[p]];
10571142 cur.pos := p;
1143+ if p >= cur.cursor then (* the name the cursor is in or just after *)
1144+ cursorName(start, cur.cursor);
1145+ return;
1146+ end;
10581147 if p - start > MaxIdent then
10591148 lexError(Diag.say("a name has at most {} characters", [Fmt.int(MaxIdent)]));
10601149 end;
@@ -1167,4 +1256,5 @@
11671256 tableMask := 2 * nameCap - 1;
11681257 table := words64(tableMask + 1);
11691258 for i := 0 to NumWords - 1 do _ := intern(SYSTEM.PTR(words[i]), LEN(words[i])); end;
1259+ atCursor := intern(SYSTEM.PTR("(cursor)"), 8); (* no name can be written so *)
11701260 end Scan.

src/Sym.raz (history) modified +51 -10

@@ -388,32 +388,73 @@
388388 return d[LEN(a)][LEN(b)];
389389 end;
390390
391+(* Whether o is a name that can be reached from here: in scope s, if
392+ it is exported or of the module being compiled; or, if s < 0, in a
393+ scope open *)
394+proc reaches(o: ^Obj; s: INT): BOOL;
395+var j: INT;
396+begin
397+ if (o = nil) or (o^.name < 0) or (o^.typ = tPoison) then return false; end;
398+ if s >= 0 then return (o^.scope = s) and (o^.exported or (o^.home = curModule)); end;
399+ for j := 0 to depth - 1 do
400+ if o^.scope = scopes[j] then return true; end;
401+ end;
402+ return false;
403+end;
404+
391405 (* The name spelled most like name, for "did you mean": in scope s, if
392406 it can be reached from here, or in the scopes in reach if s < 0; nil
393407 if none is within an edit for every three characters. Only after an
394408 error, so it looks at every object. *)
395409 proc closest*(name, s: INT): ^Obj;
396-var i, j, d, best: INT; o, found: ^Obj; n: []const U8; reach: BOOL;
410+var i, d, best: INT; o, found: ^Obj; n: []const U8;
397411 begin
398412 n := Scan.nameOf(name);
399413 best := LEN(n) div 3 + 1;
400414 found := nil;
401415 for i := 0 to hashMask do
402416 o := hashTab[i];
403- if (o = nil) or (o^.name = name) or (o^.name < 0) or (o^.typ = tPoison) then
404- reach := false;
405- elsif s >= 0 then
406- reach := (o^.scope = s) and (o^.exported or (o^.home = curModule));
407- else
408- reach := false;
409- for j := 0 to depth - 1 do reach := reach or (o^.scope = scopes[j]); end;
410- end;
411- if reach then
417+ if reaches(o, s) and (o^.name # name) then
412418 d := distance(n, Scan.nameOf(o^.name));
413419 if d < best then best := d; found := o; end;
414420 end;
415421 end;
416422 return found;
423+end;
424+
425+proc typeName*(t: ^Type): []const U8; forward;
426+
427+(* What kind of declaration o is, as raz -q words says it *)
428+proc kindOf(o: ^Obj): []const U8;
429+begin
430+ match o^.cls of
431+ | oConst, oCase: return "const";
432+ | oType: return "type";
433+ | oVar: return "var";
434+ | oProc: return "proc";
435+ | oModule: return "module";
436+ | oField: return "field";
437+ | oBuiltin: return "builtin";
438+ end;
439+end;
440+
441+(* raz -q words: a row in out for each name in reach that starts with
442+ prefix, in scope s as closest has it: its kind, the name and its
443+ type, split by tabs. A name another declaration hides is left out. *)
444+proc offer*(s: INT; prefix: []const U8; var out: Buf.Buf);
445+var i: INT; o: ^Obj; n, t: []const U8;
446+begin
447+ for i := 0 to hashMask do
448+ o := hashTab[i];
449+ if reaches(o, s) and ((s >= 0) or (lookup(o^.name) = o)) then
450+ n := Scan.nameOf(o^.name);
451+ t := "";
452+ if (o^.typ # nil) and (o^.cls # oModule) and (o^.cls # oBuiltin) then t := typeName(o^.typ); end;
453+ if (LEN(n) >= LEN(prefix)) and (n[0..LEN(prefix)] = prefix) then
454+ Fmt.write(out, "{}\t{}\t{}\n", [Fmt.str(kindOf(o)), Fmt.str(n), Fmt.str(t)]);
455+ end;
456+ end;
457+ end;
417458 end;
418459
419460 (* Types *)

test/check.sh (history) modified +17 -0

@@ -168,6 +168,23 @@
168168 && readelf -s $out/own/Own | grep -q ' Own.main$' && readelf --debug-dump=decodedline $out/own/Own | grep -q 'Own.raz'; then pass=$((pass + 1))
169169 else echo "FAIL own Rt: status $status, $statusFail"; cat $out/own/Own.out $out/own/OwnFail.out; fail=$((fail + 1)); fi
170170
171+# raz -q, for an editor: check's rows, and the names words offers at a
172+# cursor after a part of a name, after a module's dot, and none in a
173+# comment or a string. The text is standard input: checking an empty
174+# one shows that the file on disk isn't read.
175+for t in "check Check.raz check" "words Words.raz:9:16 prefix" "words Words.raz:10:11 export" \
176+ "words Words.raz:11:10 none" "words Words.raz:12:15 none"; do
177+ set -- $t
178+ f=test/query/${2%%:*}
179+ $raz -q $1 test/query/$2 < $f > $out/query.out
180+ if [ "$3" = none ]; then : > $out/query.expect; else cp test/query/$3.expect $out/query.expect; fi
181+ if cmp -s $out/query.out $out/query.expect; then pass=$((pass + 1))
182+ else echo "FAIL raz -q $1 $2"; diff $out/query.expect $out/query.out | head -5; fail=$((fail + 1)); fi
183+done
184+if [ -z "$($raz -q check test/query/Words.raz < /dev/null | grep 'expected "module"')" ]; then
185+ echo "FAIL raz -q check: read the file, not standard input"; fail=$((fail + 1))
186+else pass=$((pass + 1)); fi
187+
171188 # what src/ asks of lib/ is what doc/compiler.md lists (test/asks.sh)
172189 if sh test/asks.sh > $out/asks.out 2>&1; then pass=$((pass + 1))
173190 else echo "FAIL test/asks.sh:"; cat $out/asks.out; fail=$((fail + 1)); fi

test/query/Check.raz (history) added +13 -0

@@ -0,0 +1,13 @@
1+module Check;
2+import Out;
3+
4+var count: INT;
5+
6+proc main*;
7+var total: INT;
8+begin
9+ total := cout + 1;
10+ Out.str(1);
11+end;
12+
13+end Check.

test/query/Words.raz (history) added +15 -0

@@ -0,0 +1,15 @@
1+module Words;
2+import Out;
3+
4+var count: INT;
5+
6+proc main*;
7+var total: INT;
8+begin
9+ total := co;
10+ Out.st;
11+ (* co *)
12+ Out.str("co");
13+end;
14+
15+end Words.

test/query/check.expect (history) added +3 -0

@@ -0,0 +1,3 @@
1+test/query/Check.raz 9 14 9 18 error cout isn't declared
2+test/query/Check.raz 10 13 10 14 error can't use an integer constant as []const U8
3+lib/Out.raz 53 11 53 12 note it goes to s, declared here

test/query/export.expect (history) added +1 -0

@@ -0,0 +1 @@
1+proc str proc([]const U8)

test/query/prefix.expect (history) added +1 -0

@@ -0,0 +1 @@
1+var count INT