From 5afc418b2ce7d02bbf448ac9db1b9d8dbe3456f3 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:43:06 +0000 Subject: [PATCH] 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. --- diff --git a/README.md b/README.md index 18482f4..51c9f58 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,8 @@ raz [-I dir]... [-o file] [-Werror] [-S] [-s] [-noprofile] [-libc glibc|musl] [-base addr] [-bare] Main.raz raz run [option]... Main.raz [arg]... + raz -q check [option]... Main.raz + raz -q words [option]... Main.raz:LINE:COL raz -h raz --version diff --git a/doc/compiler.md b/doc/compiler.md index ecdfa4d..8d9fc35 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -1,6 +1,6 @@ # Reading the raz compiler -The compiler is twelve files of raz, about 12,900 lines of code (the +The compiler is twelve files of raz, about 13,100 lines of code (the budget is 14,000). It is its own compiler: a release of it, the one `BOOT` names, builds `src/`, and `make fixpoint` checks that what it makes makes itself again, byte for byte. Each release was built by the @@ -16,18 +16,18 @@ | File | Lines | Code | What | |---|---|---|---| -| `src/Diag.raz` | 423 | 325 | Messages: positions, source excerpts, colour, counts | -| `src/Scan.raz` | 1,170 | 966 | Symbols, literals, comments, positions | -| `src/Sym.raz` | 815 | 652 | Types, objects, scopes, layout | +| `src/Diag.raz` | 472 | 358 | Messages: positions, source excerpts, colour, counts | +| `src/Scan.raz` | 1,260 | 1,036 | Symbols, literals, comments, positions | +| `src/Sym.raz` | 856 | 682 | Types, objects, scopes, layout | | `src/Chunk.raz` | 364 | 280 | The compiled program: chunks, fixups, line notes | | `src/X64.raz` | 1,777 | 1,450 | The instruction encoder, jumps within a procedure, the assembler | | `src/Gen.raz` | 2,846 | 1,989 | The stack machine, for x86-64: values, operations, checks, calls, frames | | `src/Item.raz` | 2,553 | 2,051 | Items: types, constants, variables, operators, conversions, calls | -| `src/Parse.raz` | 4,877 | 4,143 | Declarations, statements, expressions, built-ins, recovery, warnings | +| `src/Parse.raz` | 4,892 | 4,154 | Declarations, statements, expressions, built-ins, recovery, warnings | | `src/Link.raz` | 411 | 317 | Tree shaking, layout, patching, the places | | `src/Elf.raz` | 450 | 356 | Static and dynamic ELF, symbol table, line numbers | | `src/Host.raz` | 103 | 52 | The system running the compiler | -| `src/Raz.raz` | 439 | 343 | The command line | +| `src/Raz.raz` | 488 | 381 | The command line, and `-q` for an editor | 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. @@ -2338,6 +2338,47 @@ the library last, after `-I` and `RAZ_PATH`, and the duplicate check (a symbolic link to one of the two files chooses it) is as before. +## raz -q: for an editor + +`raz -q` answers an editor's language server about the text it holds, +saved or not, with the compiler itself, so that there is one grammar +and one set of rules. It is a compile that writes no program, with +three changes, each in the unit it concerns. + +- **The text from standard input.** `Raz.forEditor` gives `Scan` the + main module's path (`Scan.setStdin`); `Scan.open`, asked for that + path, reads standard input instead of the file. Imports are found + and read as ever. +- **Messages as rows.** `Diag.form` is `pretty`, the messages a + person reads; `rows`, for `-q check`, where `show` writes each + error, warning and note as a line of tab-split fields on standard + output (`Diag.row`), and help, counts and the stop after + `MaxErrors` say nothing; or `silent`, for `-q words`, which says no + message at all and reads on past any number of errors, to reach the + cursor. After the main module is checked, `Raz.main` returns before + linking. +- **The cursor is a symbol.** For `-q words`, `Scan` knows the byte + the cursor is at (`State.cursor`, `MAX(INT)` when there is none, + so that `next` pays one compare for it). When `next` comes to the + cursor, it makes the symbol there a name, `Scan.atCursor`, which no + source can spell (`(cursor)`), and keeps what is typed of the name + in `Scan.prefix`: the bytes from the start of the name the cursor is + in or just after, or none if it is between symbols. The parser reads + on as for any name; where `qualIdent` would look a name up, it + meets `atCursor` and calls `complete` instead, which writes the + names that reach there (`Sym.offer`, over the same test as + `closest`'s, `Sym.reaches`) and ends the compile. After `M.`, the + names are what `M` exports. A cursor inside a comment or a string + is dropped, so that it gives no names. Since `cursor` is part of the + scanner's state, a recovery or a read ahead that puts the state back + puts the cursor back too, and it is met again. + +What it leaves out: a record's fields after `r.`, which would need the +type of an expression cut short; names declared further down, which a +one-pass compiler hasn't met yet; and a +main module that `Rt` imports already, as a module of `lib/` being +edited, whose text is then the file's. + ## A program with its own Rt A hosted program uses `lib/Rt.raz`. A freestanding one, a kernel's @@ -2668,19 +2709,20 @@ | `Sys.close` | `Scan` and `Parse`: closes a source or `RAZ-VERSION` file after reading | | `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 | | `Sys.env`, `Sys.envAt` | `Diag` (`NO_COLOR`) and `Raz.userLibraries` (`RAZ_PATH`, `HOME`; `envAt` tells unset from empty) | -| `Sys.errDenied`, `Sys.errNoEntry` | `Scan`: "permission denied" and "there is no such file" in a message | +| `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 | | `Sys.info`, `Sys.Info` | `Scan` and `Parse`: whether a path is a file (`file`) and its length (`size`) | | `Sys.isTerminal` | `Diag`: colour only when standard error is a terminal | | `Sys.openRead`, `Sys.read` | `Scan`: reads a source file whole; `Parse`: the library's `RAZ-VERSION` | +| `Sys.stdin` | `Scan`: `raz -q`'s source, read from standard input | | `Sys.readLink` | `Host.libraryDir`: `/proc/self/exe`, to find the library beside the compiler | -| `Sys.stderr`, `Sys.write` | `Diag`: its messages | +| `Sys.stderr`, `Sys.stdout`, `Sys.write` | `Diag`: its messages, or `raz -q check`'s rows on standard output | | `Sys.workDir` | `Diag`: shows a path relative to the working directory; `Elf`: the compilation directory of the line table | `Rt`, the run time, besides `fail`, `exit` and the places (above): | Name | What for | |---|---| -| `Rt.exit` | `Diag`: ends the compiler, with status 1, after an error that stops it | +| `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 | `Files`, whole files and the command line: @@ -2697,8 +2739,8 @@ |---|---| | `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` | | `Fmt.write`, `Fmt.Arg`, `Fmt.str`, `Fmt.int`, `Fmt.char`, `Fmt.hex` | Formatting: `Diag.say`'s `{}` messages and a type's name | -| `Out.str`, `Out.ln`, `Out.flush` | Standard output: the `-S` listing, `-h` and `--version` | -| `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`) | +| `Out.str`, `Out.ln`, `Out.flush` | Standard output: the `-S` listing, `-h`, `--version` and `raz -q words`' names | +| `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`) | | `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 | ## This compiler's choices diff --git a/doc/raz.1 b/doc/raz.1 index 0781b29..0540f8c 100644 --- a/doc/raz.1 +++ b/doc/raz.1 @@ -14,6 +14,14 @@ .Op Ar option ... .Ar Main.raz .Op Ar arg ... +.Nm +.Fl q Cm check +.Op Ar option ... +.Ar Main.raz +.Nm +.Fl q Cm words +.Op Ar option ... +.Ar Main.raz : Ns Ar LINE : Ns Ar COL .Sh DESCRIPTION .Nm compiles the module in @@ -167,6 +175,20 @@ .Pa /lib/ld-musl-x86_64.so.1 , and not glibc's, as Alpine has. A program without C needs no C library, and runs on either. +.It Fl q Cm check +For an editor: check +.Ar Main.raz , +reading its text from standard input, as the editor holds it, and +write no program. +Each message is a row on standard output; see +.Sx FOR AN EDITOR . +.It Fl q Cm words +For an editor: with +.Ar Main.raz : Ns Ar LINE : Ns Ar COL +in place of +.Ar Main.raz , +write the names that can be typed at that cursor, a row each, and +nothing else. .It Fl h , Fl \-help Say the options. .It Fl \-version @@ -223,6 +245,68 @@ .Nm .Cm run exits as the program does. +.Sh FOR AN EDITOR +.Fl q +is for an editor's language server, which asks of the text it holds, +saved or not. +The text of the main module comes from standard input; the modules it +imports are read from their files, found as for a compile. +Every row is fields split by tabs. +.Pp +.Fl q Cm check +gives a row for each error, warning and note: +.Bd -literal -offset indent +FILE LINE COL ENDLINE ENDCOL KIND MESSAGE +.Ed +.Pp +where the place runs from +.Ar LINE +and +.Ar COL +up to, not including, +.Ar ENDLINE +and +.Ar ENDCOL , +lines and bytes in a line counted from 1, and +.Ar KIND +is +.Cm error , +.Cm warning +or +.Cm note . +.Ar FILE +may be another module's, as for a note. +An error about no place in a file, as a module not found, has an empty +.Ar FILE +and zeros. +It exits 1 if there was an error, else 0. +.Pp +.Fl q Cm words +reads the module up to the cursor, past any errors, and gives a row for +each name that can be typed there and starts with what is typed of the +name the cursor is in or just after: +.Bd -literal -offset indent +KIND NAME TYPE +.Ed +.Pp +where +.Ar KIND +is +.Cm const , +.Cm type , +.Cm var , +.Cm proc , +.Cm module , +.Cm field +or +.Cm builtin . +After a module's name and a dot, the names are those the module +exports; elsewhere, every name in scope there, a local hiding a global +of its name. +The rows come in no order. +Inside a comment or a string, after a record's dot, or where a name is +declared, there are none. +It exits 0. .Sh LISTING The listing of .Fl S diff --git a/src/Diag.raz b/src/Diag.raz index 8d8bca3..de22f72 100644 --- a/src/Diag.raz +++ b/src/Diag.raz @@ -8,6 +8,9 @@ NO_COLOR isn't set. Diag keeps every source file it is given, so that a note can show a line of a module compiled earlier. + For an editor (raz -q), messages are rows on standard output + instead, or not given at all (form). + Depends on: Sys, to write and to ask about the terminal; Buf and Fmt, to build what it writes. Leaves out: wording. The callers say what is wrong, with say; a @@ -23,6 +26,11 @@ a = b marks the place between two characters. *) Pos* = record f*, a*, b*: INT; end; + (* How messages are given: shown to a person on standard error; as + rows on standard output, for an editor (raz -q check); or not at + all (raz -q words, which says only names) *) + Form* = (pretty, rows, silent); + File = record path: []const U8; buf: ^U8; @@ -45,6 +53,7 @@ (* The construct being read uses a name already reported as not declared: its errors follow from that one, and aren't shown. *) quiet*: BOOL; + form*: Form; files: ^File; (* numFiles of them, in room for cap *) numFiles, cap: INT; @@ -65,6 +74,11 @@ quiet := yes; end; +proc setForm*(f: Form); +begin + form := f; +end; + (* Paths are shown from the working directory where they are under it, so messages read the same wherever the compiler or its library is. *) proc shownPath*(path: []const U8): []const U8; @@ -177,13 +191,15 @@ paintOn(Plain); end; -(* What has been made, written to standard error *) +(* What has been made, written to standard error, or the rows to + standard output *) proc flush; -var s: []const U8; n: INT; +var s: []const U8; n, fd: INT; begin s := Buf.bytes(out); + if form = Form.rows then fd := Sys.stdout; else fd := Sys.stderr; end; while LEN(s) > 0 do - n := Sys.write(Sys.stderr, s); + n := Sys.write(fd, s); if n <= 0 then break; end; s := s[n..LEN(s)]; end; @@ -231,12 +247,36 @@ return n; end; +(* A message as raz -q check gives it, a row for an editor: the file, + the line and the byte in the line where p starts, the same where it + ends, the kind and the message, split by tabs; all from 1. A message + about no place in a file has no file, and zeros. *) +proc row(p: Pos; kind, msg: []const U8); +var line, start, endLine, endStart: INT; e: Pos; +begin + if p.f >= numFiles then + Fmt.write(out, "\t0\t0\t0\t0\t{}\t{}\n", [Fmt.str(kind), Fmt.str(msg)]); + else + line, start := locate(p); + e := p; + e.a := p.b; + endLine, endStart := locate(e); + Fmt.write(out, "{}\t{}\t{}\t{}\t{}\t{}\t{}\n", [Fmt.str(files[p.f].path), Fmt.int(line), + Fmt.int(p.a - start + 1), Fmt.int(endLine), Fmt.int(p.b - endStart + 1), Fmt.str(kind), Fmt.str(msg)]); + end; + flush; +end; + (* "file:line:col: kind: msg", then the line with p underlined. A tab before p is copied into the underline, so that the two line up whatever the terminal makes of tabs. *) proc show(p: Pos; kind, kindColour, msg: []const U8); var line, start, stop, lo, hi, i, n: INT; buf: ^U8; f: ^File; digits: []const U8; begin + if form # Form.pretty then + if form = Form.rows then row(p, kind, msg); end; + return; + end; if p.f >= numFiles then (* about no place in a file, as for Rt, which the compiler imports before it reads one *) @@ -348,11 +388,14 @@ lastError := p; show(p, "error", Red, msg); INC(errors); - if errors >= MaxErrors then - put("raz: stopping after "); - putNum(MaxErrors); - put(" errors\n"); - flush; + (* raz -q words reads on to the cursor, past any number of errors *) + if (errors >= MaxErrors) and (form # Form.silent) then + if form = Form.pretty then + put("raz: stopping after "); + putNum(MaxErrors); + put(" errors\n"); + flush; + end; Rt.exit(1); end; end; @@ -376,7 +419,7 @@ proc help*(msg: []const U8); begin - if shown then + if shown and (form = Form.pretty) then paint(Green, "help:"); put(" "); put(msg); @@ -389,10 +432,14 @@ read: it stops the compiler at once. *) proc fatal*(msg: []const U8); begin - put("raz: "); - put(msg); - putc('\n'); - flush; + if form = Form.pretty then + put("raz: "); + put(msg); + putc('\n'); + flush; + elsif form = Form.rows then + row({f: MAX(INT), a: 0, b: 0}, "error", msg); + end; Rt.exit(1); end; @@ -406,7 +453,9 @@ if there were errors. *) proc finish*; begin - if (errors > 0) and (warnings > 0) then + if form # Form.pretty then + (* no count: each message was a row of its own, or none *) + elsif (errors > 0) and (warnings > 0) then put("raz: "); put(count(errors, "error")); put(", "); put(count(warnings, "warning")); putc('\n'); elsif errors > 0 then put("raz: "); put(count(errors, "error")); putc('\n'); diff --git a/src/Parse.raz b/src/Parse.raz index 2d1a719..6bdde4c 100644 --- a/src/Parse.raz +++ b/src/Parse.raz @@ -26,7 +26,7 @@ Scan.Sym is a chain of tests, since it has more names than a set holds. *) module Parse; -import Fmt, Diag, Scan, Sym, Chunk, Gen, Item, Sys, Str, Buf, Heap; +import Fmt, Diag, Scan, Sym, Chunk, Gen, Item, Sys, Str, Buf, Heap, Out, Rt; import SYSTEM; type @@ -558,10 +558,24 @@ [Fmt.str(a), Fmt.str(nameOf(o^.name)), Fmt.str(b), Fmt.str(nameOf(o^.name))])); end; +(* raz -q words: the current symbol is the cursor, where a name of + scope s can be typed, or of any scope open if s < 0. The names that + start with what is typed are written, and the compile ends. *) +proc complete(s: INT); +var b: Buf.Buf; +begin + Buf.init(b, Heap.heap); + Sym.offer(s, Scan.prefix, b); + Out.str(Buf.bytes(b)); + Out.flush(); + Rt.exit(0); +end; + proc qualIdent: (PObj, ERROR); var o: PObj; m: PModule; at: Diag.Pos; begin if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; + if Scan.id = Scan.atCursor then complete(-1); end; at := Scan.tokPos(); o := Sym.lookup(Scan.id); if o = nil then @@ -579,6 +593,7 @@ try expect(Scan.sPeriod); if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; m := o^.home; + if Scan.id = Scan.atCursor then complete(m^.scope); end; o := Sym.find(m^.scope, Scan.id); if (o = nil) or not o^.exported then Diag.error(Scan.tokPos(), say2("{} isn't exported by {}", nameOf(Scan.id), nameOf(m^.name))); diff --git a/src/Raz.raz b/src/Raz.raz index 258aaa6..50137b1 100644 --- a/src/Raz.raz +++ b/src/Raz.raz @@ -2,6 +2,7 @@ raz [-I dir]... [-o file] [-Werror] [-S] [-libc glibc|musl] [-base addr] [-bare] Main.raz raz run [-I dir]... Main.raz [arg]... + raz -q check|words [-I dir]... Main.raz[:LINE:COL] raz --version Compiles the main module and every module it imports, writes the @@ -10,7 +11,10 @@ the main module's code instead. 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. + program's; its argv[0] is Main.raz. raz -q, for an editor, reads + the main module's text from standard input and stops once it is + checked: check writes its messages as rows, and words the names + that can be typed at the cursor (forEditor). The program starts by saving argc and argv, runs every module's body (those of the modules the program imports, imported modules first), @@ -29,7 +33,7 @@ Leaves out: the work itself; the other units compile, link and write, and this only reads the command line and runs them in order. *) module Raz; -import Sys, Out, Version, Files, Host, Fmt, Diag, Scan, Sym, Chunk, X64, Gen, Parse, Link, Elf; +import Sys, Out, Str, Version, Files, Host, Fmt, Diag, Scan, Sym, Chunk, X64, Gen, Parse, Link, Elf; import SYSTEM; const @@ -118,6 +122,41 @@ return INT(v), true; end; +(* The file, line and column of raz -q words' FILE:LINE:COL; false if + it isn't one *) +proc cursorAt(s: []const U8): ([]const U8, INT, INT, BOOL); +var i, j: INT; line, col: I64; ok1, ok2: BOOL; +begin + j := Str.findLast(s, ":"); + if j <= 0 then return s, 0, 0, false; end; + i := Str.findLast(s[0..j], ":"); + if i <= 0 then return s, 0, 0, false; end; + line, ok1 := Str.toInt(s[i + 1..j]); + col, ok2 := Str.toInt(s[j + 1..LEN(s)]); + return s[0..i], INT(line), INT(col), ok1 and ok2 and (line >= 1) and (col >= 1); +end; + +(* raz -q, for an editor: the main module's text is standard input, + and messages are rows (check) or not given (words, whose path names + the cursor). The result is the main module's path. *) +proc forEditor(query, path: []const U8): []const U8; +var line, col: INT; ok: BOOL; +begin + line := 0; + col := 0; + if query = "check" then + Diag.setForm(Diag.Form.rows); + elsif query = "words" then + path, line, col, ok := cursorAt(path); + if not ok then Diag.fatal(say1("-q words {}: expected FILE:LINE:COL", path)); end; + Diag.setForm(Diag.Form.silent); + else + Diag.fatal(say1("-q {}: expected check or words", query)); + end; + Scan.setStdin(path, line, col); + return path; +end; + (* What raz -h says *) proc usage; begin @@ -139,6 +178,10 @@ Out.str(" runs no body of Rt, which sets the signals' handlers\n"); Out.str(" -libc name links a program that uses C against glibc or musl; by\n"); Out.str(" default glibc, or musl where only its loader is there\n"); + Out.str(" -q check for an editor: checks Main.raz, its text read from standard\n"); + Out.str(" input, and writes each message as a row (see raz(1))\n"); + Out.str(" -q words with Main.raz:LINE:COL, writes the names that can be\n"); + Out.str(" typed at the cursor there, one row each\n"); Out.str(" -h, --help says this\n"); Out.str(" --version says the version, and the report it follows\n"); Out.str("see raz(1), and the report, doc/raz.md\n"); @@ -272,11 +315,12 @@ i, first, entry, last, base: INT; m, rt, thread: ^Sym.Module; mainObj: ^Sym.Obj; run, noProfile, listing, dynamic, libcSaid, ok, bare: BOOL; err: ERROR; - libDir: []const U8; + libDir, query: []const U8; begin path := ""; outPath := ""; libDir := ""; + query := ""; noProfile := false; bare := false; listing := false; @@ -312,6 +356,9 @@ if not ok or (base mod Link.Page # 0) then Diag.fatal(say1("-base {}: expected an address, a multiple of 4096 as raz writes it, as 0FFFFFFFF80000000H", Files.arg(i))); end; + elsif s = "-q" then + INC(i); + query := Files.arg(i); elsif s = "-noprofile" then noProfile := true; elsif s = "-bare" then @@ -342,6 +389,7 @@ usage(); return 1; end; + if LEN(query) > 0 then path := forEditor(query, path); end; if run and (LEN(outPath) > 0) then Diag.fatal("raz run takes no -o"); end; if run then (* asked now, before any source is read: its error is the refusal *) @@ -384,6 +432,7 @@ if Diag.errors > 0 then Diag.finish(); end; end; Diag.finish(); + if LEN(query) > 0 then return 0; end; (* checked: an editor wants no program *) if rt = nil then Diag.fatal("can't find module Rt"); end; (* what Rt is given: the places, which the linker makes, for Rt to say diff --git a/src/Scan.raz b/src/Scan.raz index 3e63fe0..7e49e0f 100644 --- a/src/Scan.raz +++ b/src/Scan.raz @@ -6,6 +6,12 @@ compares names as small integers. The scanner also says where the current symbol is, for messages. + For an editor (raz -q), one file's text may come from standard + input instead (setStdin), and a place in it may be marked: the + symbol there is a name, atCursor, standing for what is typed of the + name at the cursor, prefix, so that the parser can say what names + can be typed there. + Depends on: Sys, to read files; Diag, to report errors. Leaves out: recovery from errors in the text itself, such as a string not closed: the first such error stops the compiler. The parser goes @@ -44,6 +50,8 @@ rval: F64; id: INT; f: INT; (* the file, as Diag knows it *) + cursor: INT; (* raz -q words: the byte the cursor is at, until + the symbol there is made; else MAX(INT) *) end; const @@ -80,6 +88,11 @@ error, so slips in it aren't reported again. *) skipping*: BOOL; + atCursor*: INT; (* the name the symbol at the cursor has *) + prefix*: []const U8; (* what is typed of the name at the cursor *) + stdinPath: []const U8; (* the file whose text is standard input, or "" *) + cursorLine, cursorCol: INT; (* the cursor in it, from 1, or 0 for none *) + (* Whether a byte may be in a name: a letter, a digit or _. A table, since the loop that reads a name asks it of every byte. *) nameChar: [256]BOOL; @@ -487,28 +500,80 @@ return n < NumWords; end; +(* raz -q: the text of the file at path is standard input, and the + cursor is at line and col there (bytes, from 1), or nowhere if 0 *) +proc setStdin*(path: []const U8; line, col: INT); +begin + stdinPath := path; + cursorLine := line; + cursorCol := col; +end; + +(* Standard input, read whole; its length is the second result *) +proc readStdin: (^U8, INT); +var buf: ^U8; n, size, r: INT; +begin + size := 65536; + buf := grab(size); + n := 0; + r := 1; + while r # 0 do + if n + 1 = size then + buf := regrab(buf, n, 2 * size); + size := 2 * size; + end; + r := Sys.read(Sys.stdin, buf[n..size - 1]); + if r > 0 then + n := n + r; + elsif (r < 0) and (r # Sys.errIntr) then + Diag.fatal("can't read standard input"); + end; + end; + return buf, n; +end; + +(* The byte of buf, n long, at line and col, both from 1; n if past it *) +proc byteAt(buf: ^U8; n, line, col: INT): INT; +var i, l: INT; +begin + i := 0; + l := 1; + while (i < n) and (l < line) do + if buf[i] = '\n' then INC(l); end; + INC(i); + end; + if i + col - 1 < n then return i + col - 1; end; + return n; +end; + (* Reads the file at path to scan it; "" if it can, else why not *) proc open*(path: []const U8): []const U8; var fd, n, got, r, err: INT; info: Sys.Info; begin - info, err := Sys.info(path); - if err = Sys.errNoEntry then return "there is no such file"; end; - if err = Sys.errDenied then return "permission denied"; end; - if err < 0 then return "it can't be opened"; end; - if not info.file then return "it isn't a file"; end; - fd := Sys.openRead(path); - if fd = Sys.errNoEntry then return "there is no such file"; end; - if fd = Sys.errDenied then return "permission denied"; end; - if fd < 0 then return "it can't be opened"; end; - n := INT(info.size); - cur.buf := grab(n + 1); - got := 0; - while got < n do - r := Sys.read(fd, cur.buf[got..n]); - if r <= 0 then Diag.fatal(Diag.say("can't read {}", [Fmt.str(path)])); end; - got := got + r; + cur.cursor := MAX(INT); + if (LEN(stdinPath) > 0) and (path = stdinPath) then + cur.buf, n := readStdin(); + if cursorLine > 0 then cur.cursor := byteAt(cur.buf, n, cursorLine, cursorCol); end; + else + info, err := Sys.info(path); + if err = Sys.errNoEntry then return "there is no such file"; end; + if err = Sys.errDenied then return "permission denied"; end; + if err < 0 then return "it can't be opened"; end; + if not info.file then return "it isn't a file"; end; + fd := Sys.openRead(path); + if fd = Sys.errNoEntry then return "there is no such file"; end; + if fd = Sys.errDenied then return "permission denied"; end; + if fd < 0 then return "it can't be opened"; end; + n := INT(info.size); + cur.buf := grab(n + 1); + got := 0; + while got < n do + r := Sys.read(fd, cur.buf[got..n]); + if r <= 0 then Diag.fatal(Diag.say("can't read {}", [Fmt.str(path)])); end; + got := got + r; + end; + Sys.close(fd); end; - Sys.close(fd); cur.buf[n] := 0; (* the sentinel that ends every scan *) cur.len := n; cur.pos := 0; @@ -713,6 +778,7 @@ end; until depth = 0; cur.commentEnd := cur.pos; + if (open < cur.cursor) and (cur.cursor < cur.pos) then cur.cursor := MAX(INT); end; (* no names in a comment *) end; (* Reading a decimal real exactly: the F64 nearest to digits times 10 to @@ -1014,6 +1080,16 @@ tok := sString; end; +(* Makes the current symbol the name at the cursor, typed from start up + to at; the cursor is passed then *) +proc cursorName(start, at: INT); +begin + prefix := cur.buf[start..at]; + cur.cursor := MAX(INT); + tok := sIdent; + id := atCursor; +end; + (* Reads the next symbol *) proc next*; var c: U8; start, h, v, i, p: INT; buf: ^U8; @@ -1045,6 +1121,15 @@ cur.tokPos := p; cur.tokLine := cur.line; cur.tokLineStart := cur.lineStart; + if p >= cur.cursor then + (* the cursor is before this symbol: if it was between symbols, not + in a string or a comment, a name of nothing typed is made there *) + if cur.prevEnd <= cur.cursor then + cursorName(cur.cursor, cur.cursor); + return; + end; + cur.cursor := MAX(INT); + end; if single[c] # sNull then INC(cur.pos); tok := single[c]; @@ -1055,6 +1140,10 @@ start := p; repeat INC(p); until not nameChar[buf[p]]; cur.pos := p; + if p >= cur.cursor then (* the name the cursor is in or just after *) + cursorName(start, cur.cursor); + return; + end; if p - start > MaxIdent then lexError(Diag.say("a name has at most {} characters", [Fmt.int(MaxIdent)])); end; @@ -1167,4 +1256,5 @@ tableMask := 2 * nameCap - 1; table := words64(tableMask + 1); for i := 0 to NumWords - 1 do _ := intern(SYSTEM.PTR(words[i]), LEN(words[i])); end; + atCursor := intern(SYSTEM.PTR("(cursor)"), 8); (* no name can be written so *) end Scan. diff --git a/src/Sym.raz b/src/Sym.raz index c3a1524..83656ed 100644 --- a/src/Sym.raz +++ b/src/Sym.raz @@ -388,32 +388,73 @@ return d[LEN(a)][LEN(b)]; end; +(* Whether o is a name that can be reached from here: in scope s, if + it is exported or of the module being compiled; or, if s < 0, in a + scope open *) +proc reaches(o: ^Obj; s: INT): BOOL; +var j: INT; +begin + if (o = nil) or (o^.name < 0) or (o^.typ = tPoison) then return false; end; + if s >= 0 then return (o^.scope = s) and (o^.exported or (o^.home = curModule)); end; + for j := 0 to depth - 1 do + if o^.scope = scopes[j] then return true; end; + end; + return false; +end; + (* The name spelled most like name, for "did you mean": in scope s, if it can be reached from here, or in the scopes in reach if s < 0; nil if none is within an edit for every three characters. Only after an error, so it looks at every object. *) proc closest*(name, s: INT): ^Obj; -var i, j, d, best: INT; o, found: ^Obj; n: []const U8; reach: BOOL; +var i, d, best: INT; o, found: ^Obj; n: []const U8; begin n := Scan.nameOf(name); best := LEN(n) div 3 + 1; found := nil; for i := 0 to hashMask do o := hashTab[i]; - if (o = nil) or (o^.name = name) or (o^.name < 0) or (o^.typ = tPoison) then - reach := false; - elsif s >= 0 then - reach := (o^.scope = s) and (o^.exported or (o^.home = curModule)); - else - reach := false; - for j := 0 to depth - 1 do reach := reach or (o^.scope = scopes[j]); end; - end; - if reach then + if reaches(o, s) and (o^.name # name) then d := distance(n, Scan.nameOf(o^.name)); if d < best then best := d; found := o; end; end; end; return found; +end; + +proc typeName*(t: ^Type): []const U8; forward; + +(* What kind of declaration o is, as raz -q words says it *) +proc kindOf(o: ^Obj): []const U8; +begin + match o^.cls of + | oConst, oCase: return "const"; + | oType: return "type"; + | oVar: return "var"; + | oProc: return "proc"; + | oModule: return "module"; + | oField: return "field"; + | oBuiltin: return "builtin"; + end; +end; + +(* raz -q words: a row in out for each name in reach that starts with + prefix, in scope s as closest has it: its kind, the name and its + type, split by tabs. A name another declaration hides is left out. *) +proc offer*(s: INT; prefix: []const U8; var out: Buf.Buf); +var i: INT; o: ^Obj; n, t: []const U8; +begin + for i := 0 to hashMask do + o := hashTab[i]; + if reaches(o, s) and ((s >= 0) or (lookup(o^.name) = o)) then + n := Scan.nameOf(o^.name); + t := ""; + if (o^.typ # nil) and (o^.cls # oModule) and (o^.cls # oBuiltin) then t := typeName(o^.typ); end; + if (LEN(n) >= LEN(prefix)) and (n[0..LEN(prefix)] = prefix) then + Fmt.write(out, "{}\t{}\t{}\n", [Fmt.str(kindOf(o)), Fmt.str(n), Fmt.str(t)]); + end; + end; + end; end; (* Types *) diff --git a/test/check.sh b/test/check.sh index 26ca377..8b062a2 100755 --- a/test/check.sh +++ b/test/check.sh @@ -168,6 +168,23 @@ && readelf -s $out/own/Own | grep -q ' Own.main$' && readelf --debug-dump=decodedline $out/own/Own | grep -q 'Own.raz'; then pass=$((pass + 1)) else echo "FAIL own Rt: status $status, $statusFail"; cat $out/own/Own.out $out/own/OwnFail.out; fail=$((fail + 1)); fi +# raz -q, for an editor: check's rows, and the names words offers at a +# cursor after a part of a name, after a module's dot, and none in a +# comment or a string. The text is standard input: checking an empty +# one shows that the file on disk isn't read. +for t in "check Check.raz check" "words Words.raz:9:16 prefix" "words Words.raz:10:11 export" \ + "words Words.raz:11:10 none" "words Words.raz:12:15 none"; do + set -- $t + f=test/query/${2%%:*} + $raz -q $1 test/query/$2 < $f > $out/query.out + if [ "$3" = none ]; then : > $out/query.expect; else cp test/query/$3.expect $out/query.expect; fi + if cmp -s $out/query.out $out/query.expect; then pass=$((pass + 1)) + else echo "FAIL raz -q $1 $2"; diff $out/query.expect $out/query.out | head -5; fail=$((fail + 1)); fi +done +if [ -z "$($raz -q check test/query/Words.raz < /dev/null | grep 'expected "module"')" ]; then + echo "FAIL raz -q check: read the file, not standard input"; fail=$((fail + 1)) +else pass=$((pass + 1)); fi + # what src/ asks of lib/ is what doc/compiler.md lists (test/asks.sh) if sh test/asks.sh > $out/asks.out 2>&1; then pass=$((pass + 1)) else echo "FAIL test/asks.sh:"; cat $out/asks.out; fail=$((fail + 1)); fi diff --git a/test/query/Check.raz b/test/query/Check.raz new file mode 100644 index 0000000..fa90768 --- /dev/null +++ b/test/query/Check.raz @@ -0,0 +1,13 @@ +module Check; +import Out; + +var count: INT; + +proc main*; +var total: INT; +begin + total := cout + 1; + Out.str(1); +end; + +end Check. diff --git a/test/query/Words.raz b/test/query/Words.raz new file mode 100644 index 0000000..5772525 --- /dev/null +++ b/test/query/Words.raz @@ -0,0 +1,15 @@ +module Words; +import Out; + +var count: INT; + +proc main*; +var total: INT; +begin + total := co; + Out.st; + (* co *) + Out.str("co"); +end; + +end Words. diff --git a/test/query/check.expect b/test/query/check.expect new file mode 100644 index 0000000..2ac036d --- /dev/null +++ b/test/query/check.expect @@ -0,0 +1,3 @@ +test/query/Check.raz 9 14 9 18 error cout isn't declared +test/query/Check.raz 10 13 10 14 error can't use an integer constant as []const U8 +lib/Out.raz 53 11 53 12 note it goes to s, declared here diff --git a/test/query/export.expect b/test/query/export.expect new file mode 100644 index 0000000..ae444fc --- /dev/null +++ b/test/query/export.expect @@ -0,0 +1 @@ +proc str proc([]const U8) diff --git a/test/query/prefix.expect b/test/query/prefix.expect new file mode 100644 index 0000000..f6100dd --- /dev/null +++ b/test/query/prefix.expect @@ -0,0 +1 @@ +var count INT