feat/lsp #1
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/lsp"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
add a language server and many numerious fixes and features
`await sleepUntil(due)`, from two functions in `std/poll.hiki`. No compiler change was needed, which is the interesting part. An `await` re-evaluates its operand on every poll, so the deadline has to be computed once and *captured*: `let due = deadlineAfter(200); let _ = await sleepUntil(due)`. A `sleep(200)` that computed its own deadline would compute a fresh 200ms on each poll and never come due -- wake, re-evaluate, park for another 200ms, forever. Given the capture, the readiness check is an ordinary expression whose truth depends on the clock, re-evaluated on each poll, which is exactly the shape the await machinery already had. The alternative -- a frame field recording *why* it was woken, with a generated check treating "the wait you published has been satisfied" as ready -- would make the compiler responsible for the meaning of a user's readiness type, and structural recognition is the whole reason a readiness type can be a user's own. A timer also parks on no descriptor. Waking is a descriptor's job; a deadline only decides how long the loop may sleep. Giving a timer an fd would make every timer spin, which is why `Loop.survey` counts a deadline-only frame as parked rather than runnable. Two units bugs, both found by the new test: The frame's wait field was read as an *absolute* clock reading by both `Loop` and `hiki_async_wait_step`, while `Wait.wait(fd, timeoutMs)` carries a *duration*. A 150ms wait was compared against a monotonic clock that had been running for hours, expired immediately, and left the loop reporting a zero block timeout -- so a timer was a spin. The field is now `waitTimeout`, documented as a duration, and both readers convert exactly once. `survey` samples the clock once for the whole pass: a minimum across frames read at slightly different instants is not the minimum of any one turn. `hk_async_join_*` moved the result out of the frame unconditionally, so a `Void`-returning `async` function emitted `void l = {0}` and a read of a field the struct does not have. Two functions in the example server return nothing, which is why nothing had ever compiled one. 262 tests.spec §19.10 asks for `crates/hikic` (the compiler) and a separate CLI, and spec §22 puts the LSP in v1. Neither is possible from a single crate, so the compiler becomes a four-crate workspace with the cut where the compiler's own module graph already had one. hiki-syntax span, diag, ast, lexer, parser deps: logos hiki-semantics program, stdlib, conform, synth, consteval, infer deps: hiki-syntax hikic mir, monomorph, codegen, driver deps: hiki-semantics hiki-lsp the server deps: hiki-syntax `hiki-lsp` deliberately does not depend on `hikic`, so nothing in the editor can reach monomorphization, MIR lowering, or C emission -- and none of those is slow to link. `mir::infer` moves to `hiki-semantics` because it is local inference over the AST with no dependency on MIR; it was sitting in `mir/` for no structural reason, and the editor needs it. `front_end` moves out of `main.rs` into `hikic::driver`, which `mir/resolve_arrays.rs`'s test was already reaching into `main` to call. Spans, because nothing in an editor works without them and the compiler had none. `Span` is a byte range; `LineIndex` converts to and from the UTF-16 code units the protocol speaks, which is not the same thing and is off by a column in any file containing a non-ASCII character. `lex_spanned` keeps what `lex` threw away. Two lexer bugs surfaced while wiring that up, both worth the test: - A string literal's token span was one byte -- logos derives a token's span from `Lexer::span()`, which after a morph reports the closing quote. So a URL in a string was read as a `//` comment in the gap after it, and only the opening quote was coloured. - The block-comment scanner that fixes this walks the gaps between tokens rather than the raw text, because a byte scan cannot tell a comment from a `//` inside a string and the lexer already knows. Interpolation spans needed real work: `\(...)` bodies were kept as text and re-lexed, so they had no position anywhere. They now carry the file offset their source began at, and the closing `)` as well -- the first cut got the start right and stopped one byte early. `StrPart::Expr` and `InterpPart::Expr` become struct variants for this, which is the only change to the AST shape. The server itself: stdio, full-document sync, a versioned document store that refuses a stale request rather than answering about text the user has already changed, and semantic tokens in LSP's delta encoding. The syntax layer works on a file that does not lex, which is most of the time. Twelve protocol tests drive the handlers in process, and one runs the whole stack over a real duplex stream -- `Service::call` skips `Content-Length` framing, so a server whose framing is broken passes every other test and is still unusable. Pre-existing and untouched: `e2e_async::emit_mir_prints_measured_frame_sizes` fails on main as well, so the frame-size probe is not producing its table.Nothing in an editor can point at anything without this, so it is the second half of the split's real work. `Expr`, `Stmt`, `Lvalue` and `Pattern` become `{ span, kind }` pairs over an un-spanned `*Kind` enum, and the declarations (`Func`, `StructDecl`, `Param`, `Arg`, `SwitchCase`, ...) gain a `span` and, where they have a name, a `name_span`. The wrapper shape rather than a spanned variant per case (`Expr::IntLit(i64, Span)`) because there are a dozen variants and ~300 construction sites, and a variant's arity change is a hand edit at every one. One wrapper is one edit. `Ty` deliberately does *not* gain a span: it derives Hash + Eq and is a key in four maps, including the monomorphizer's instance set. A span would break it, so type annotations stay position-free and only the nodes around them move. Three places where the right span is not the obvious one, each caught by a test rather than by reading: - A parenthesised expression is the expression *inside* it. `(a + b)` keeps the extent `a + b`, so `a + (b + c) * d` still has a node for `b + c`. This is why `parse_unary` and `parse_postfix` only rebuild a node when they actually appended something -- rebuilding unconditionally grew the node back over the brackets, and both had to be fixed separately. - An interpolated `\(...)` is parsed from an extracted copy of the source, so its tokens are relative to that copy. `StrPart::Expr` now carries the file offset that copy began at, and the parser rebases. Without it every expression inside a string literal was unlocatable. - A `pub` declaration spans from `pub`, so the parser entry points take the declaration's start index from their caller rather than capturing it after the keyword is consumed. Synthesized nodes -- conformance witnesses, `synth`'s `==` and `hash` bodies, a monomorphized instance -- get `Span::NONE`, which is the documented "no known position" and makes an editor decline to underline rather than guess. `parse(tokens)` is kept for callers that only want a tree; it gives every node `Span::NONE` rather than inventing offsets. Nothing on the compiler's own path uses it -- `program::load_into` goes through `parse_spanned`. Twenty-six tests assert the spans are *right* rather than merely present, by slicing the source each node claims. A span that is off by one is worse than none, because an editor draws it. Also tags two doc-comment code blocks as `text`. They are Hiki programs, and untagged rustdoc hands them to the Rust compiler, so they were failing as doctests on main as well.This is the thing the editor actually queries. The compiler answers questions about a program by transforming it -- rename, monomorphize, lower, emit -- and every one of those is destructive and none keeps a map from a place in the source to what it means. Fine for a compiler, useless for an editor, which has to answer "what is this identifier" one cursor at a time on a file that may not compile. `hir::Analysis::build` is a second reading of the same AST, built on the program as *written* -- before spec §19.6 mangling and before monomorphization, because that is the only stage where a source name still looks like what the user typed. Three tables come out: the declarations, an occurrence-to-symbol map keyed by exact span, and an inferred type per expression. It lives in `hiki-semantics` rather than `hiki-lsp` because the type inference it needs already exists. `infer::Decls` and `infer::Env` type every expression shape in the language against a declaration table, written against the AST rather than MIR. Writing a second inference for the editor and then keeping the two honest about each other forever is the alternative, and it is worse. Infallible by construction: a file that does not parse never gets here, and a name that does not resolve is *recorded as unresolved* rather than treated as an error, because a file with one unknown name is still worth analysing. That also gives completion and a future "unknown name" warning somewhere to point. Four bugs the integration tests caught, each invisible in a unit test: - `run` never pushed a scope, so every parameter and `self` was declared into nothing and no parameter reference resolved. Now each body gets one scope holding its type parameters, parameters and receiver, popped afterwards -- which is also what keeps one function's locals out of the next one's. - A scope popping removed every local with that *name*, so an inner scope that shadowed an outer one deleted the outer binding on the way out. Each scope now remembers what the environment had and restores it. - The parser recorded a binding's name span off by one -- `self.pos + 1` after the keyword had already been consumed, so `let n = 3` reported `=`. Caught by counting the `n`s in `"\(n + 1)"` and finding two instead of three. - A field access recorded the span of `a.b`, not of `b`. That means a cursor anywhere in `a.b` resolves to the field, and a rename would rewrite the receiver. Recovered from the text now, bounded by the node's own span so a name in a later sibling cannot be found by mistake. `Stmt::Binding`, `Param`, `ConstDecl`, `StructField`, `StaticField` and `EnumCase` gain a `name_span`. Every one of them is a case where the declaration's span is the whole line and the interesting range is three characters. Fifty-four tests: unit tests for the pieces, and integration tests over real programs in `examples/`, because the only way to find out whether the resolver survives the language as written is to run it over a program that uses generics, protocols, `async throws`, enums, switches, extensions and string interpolation at once.`Analysis` existed but nothing asked it anything. Now the features read it: hover a signature, the inferred type, the doc comment, whether it is `pub` -- and for a keyword, from the token stream alone, so it answers on a file that does not parse goto definition the declaration's name range, not its whole extent find references every use, with the declaration excluded on request rename the declaration and every use; refuses a local, whose references this cannot be sure are all in one file document symbols from the model, not a token scan -- a scan cannot tell a top-level `func` from one inside `unsafe`, and reports every field as a declaration completion what is in scope at the cursor, plus what the file declares inlay hints inferred types where none is written, and argument labels where the call was positional semantic tokens parameter versus local, function versus call site, and `async`/`throws`/`mutating`/`static`/`readonly` modifiers diagnostics pull (`textDocument/diagnostic`), with the version as the result id so a re-ask is `Unchanged` rather than a repeat Inlay hints are worth a note, because Hiki is an unusually good language for them. It is statically typed with no implicit conversions, so an inferred type is not a guess about what the user meant -- it is the type the compiler inferred, from the code that will reject the program if it is wrong. And every parameter has a label (spec §4.2), so `send("a")` for `send(to recipient:)` is genuinely ambiguous without the hint and unambiguous with it. The syntax layer still answers semantic tokens for a file the parser cannot read, falling back rather than returning nothing. That is the state a file is in most of the time someone is typing in it, and it is the case where an editor is most useful. Three things the end-to-end tests caught that unit tests did not: - A declaration's own name was not an occurrence of itself, so hover, rename and prepare-rename worked on every *use* of a name and not on the declaration -- the one place a reader is most likely to ask. - `occurrence_at` needed the same "the caret just finished this identifier" rule the token layer had. Without it a caret at the end of a declaration's name resolved to nothing. - Completion tested `decl_span.contains(offset)`, which is the binding's own three characters. A symbol now records the extent it is *visible* over -- the enclosing function -- because a cursor after `var x = 1` is inside `x`'s scope and a span comparison on the binding cannot tell that. Twenty-nine protocol tests drive the whole stack end to end, because the interesting failures are the ones where each layer is individually correct and the join is not.Idle CPU was already 0 -- `blockTimeout` returns -1 and the loop blocks in the kernel -- but the cost of *waking* was O(live frames) rather than O(ready). `Loop.turn` carried a comment saying it polled only what the wait reported, and then polled every frame; `Poller.isReady` existed, documented as the design, and had no callers anywhere in the tree. Ten thousand parked connections therefore cost ten thousand dispatches per wakeup, each re-evaluating an `await` operand -- for `readAvailableWait` that is a malloc(8192), a read, a String.fromBytes copy and a free per frame per wakeup, to learn nothing had arrived. A frame now qualifies three ways: its descriptor was named by the wait, or it published no descriptor (a payload-less `pending` asks to be re-evaluated now), or its own timeout expired. That third clause is load-bearing. `Wait.wait(fd, 1000)` parks on a descriptor *and* a deadline, and when the deadline is what the block returned for, the descriptor is by definition not ready -- so a readiness-only gate skips exactly the frame the timeout was for and re-arms forever. A task that can never time out is worse than the CPU it saved. `watched` records what each slot has registered, so a re-park on an unchanged descriptor skips the syscall. On Linux `EPOLL_CTL_ADD` on a registered descriptor fails and retries as `MOD`; on macOS `EV_ADD` returns `EEXIST` and recovery means delete-then-re-add. Both already "worked" -- at the price of one wasted syscall per frame per turn. It moves with frames across `retire`'s swap, and `retire` now unwatches the descriptor the slot *registered* rather than the one the frame is parked on, so a task that moved sockets still gives back its first registration. Measured on spec Appendix B, 10k parked connections: 124.80 CPU-seconds while parked, down to 28.80 (Go: 29.40). Throughput 4679 -> 5411 req/s. Idle RSS 1824 kB -> 880 kB. String: - `describeI64/U64/F64` formatted into a malloc'd scratch, then allocated a second buffer and copied the digits across -- two allocations to render one integer, on every log line, every content-length, every interpolation of a number. `RcBuf.alloc` hands back a pointer to its own bytes and nothing constrains them to the box's `len`, so the formatter now writes straight into the box the String will own. One allocation, no copy. The price is at most 23 unused bytes on a 24-byte allocation. - `append` was `self = String.concat(self, other)`: a fresh box per call and a copy of the whole prefix, so n appends cost O(n^2) bytes and n allocations. `std/http`'s response writer appends once per header and `std/json`'s escaper once per escape, so both of a server's hot loops were quadratic. Now amortized, using the RcBuf box's spare `len` as capacity -- a field that was already present and unread for Strings. 2000 appends: 2000 allocations -> 10. - `toCString` copies with the `memcpy` this file already imports. - `split` reads the needle's first byte once and only enters the full compare where it matches, so a separator not present at a position costs one comparison rather than `needle_len`. A compiler bug, found by the corpus rather than by reasoning. Rewriting `append` to publish ptr/len/body field by field was *required* for the in-place path: a wholesale `self = ...` makes `lower::assigned_param_names` mark the receiver as replaced, the refcount pass then has the caller snapshot the old value, and that snapshot is a live reference -- so `isUnique` is false on entry and every append takes the slow path. But the snapshot was also the signal `refcount::literal_backed_locals` used to decide a local was safe to skip releasing. Field writes emit no snapshot, so `var s = "a"; s.append("-tail")` left a heap String in a slot the pass still believed immortal, and the concatenation leaked. The corpus fixture `string/append.replace_self.hiki` caught it as one allocation not freed. Fixed in `literal_backed_locals`: a local passed to a call as a `&` argument has its literal-backing revoked, because a callee can write through it and this pass cannot see the callee's body. Conservative -- it costs a release for a literal that was never replaced -- but it errs toward a release rather than a leak. Tests: - `tests/e2e_alloc.rs`, 8 tests, asserting allocations per operation through a debug-only `hiki_alloc_count` accessor. A count is a property of the program rather than of the machine, which is why it can gate where the throughput benchmark reports: the same source allocates the same number of times on a laptop and on CI, on macOS and on Linux. Each test was checked to fail when its fix is reverted. - `split` semantics in `e2e_std`, over the cases a first-byte fast path can get wrong -- shared first byte with a different tail, overlapping needles, a needle at the very end, one longer than its input -- with expectations checked against Python's `str.split`. - `toCString` copies `self.len` bytes and writes the NUL separately: the buffer is `malloc`'d at `len + 1`, so a copy of `len + 1` writes one past the end. Not done, and deliberately: - Small-string optimization. The largest remaining win, and the only genuinely risky one: `HikiString`'s `{ptr, len, body}` layout is load-bearing for the bridge type check and for every `RcBuf.ptr()` consumer. It wants its own change and full e2e_rc/e2e_std/e2e_http runs, not a batch. - `Map.rehash`. `Map` has no callers in `std` or the tests; `std/json` deliberately uses a struct because `Map<String, Json>` does not compile. - Array growth via `memcpy`. `array.hiki`'s own header records that a manual copy loop already measured at parity with memcpy, and a memcpy path would have to be gated on the element type owning nothing -- the `Arr_str` bug class.unsafein std, and record why grow() stays a loop 4729467a69`String` and `Str` gain the operations that `http`, `net` and `json` each open-coded with an `unsafe` pointer read per byte: `byteAt`, `indexOf(byte)`, `indexOfString(needle)`, `hasPrefix`, `hasSuffix`, `trim`, `lines`, `parseInt`, `parseIntOpt`, and `toOwnedCString`. `indexOfString` rather than an `indexOf` overload because a type has one method per name and the byte form is the commoner call. `parseIntOpt` because `parseInt` cannot tell "not a number" from zero, and for a `Content-Length` those are different things: treating `banana` as 0 reads a request with a body as one without. `indexOfString` is `memmem`, which is a GNU extension -- glibc and macOS both hide it behind `_GNU_SOURCE` -- so `c/string.c` carries a portable `hiki_memmem` rather than changing every translation unit's feature macros to reach one function. `http/internal`'s local `trim` is deleted in favour of `Str.trim`, the same OWS rule: spaces and tabs only, deliberately not CR/LF, because a newline in a header value is a request-splitting attempt. `net`'s `digitsFrom` is left alone -- it scans a *range* of a shared buffer with its own cursor and lenient whitespace, which `parseInt`'s whole-string contract does not match. `CString` and `Argv` replace `toCString`/`freeCString` and `buildArgv`/`freeArgv`. `Argv` deletes seven `freeArgv` calls across `run` and `captureOutput`, three of them on throwing exits -- the class of leak where a new exit is added later and its free is forgotten. The `close`/`free` pairs for `pipe(2)`'s descriptor block stay: raw syscall returns have no `Deinit` to hang ownership on. **Found while doing this, and worked around rather than fixed:** `func mk() -> Rc<Hold>? { return Rc<Hold>.alloc(...) }` *hangs* when `Hold` has an owning field. Verified on an unmodified tree. `Rc<T>` without the optional is fine, and so is `Rc<T>?` when `T` holds nothing owning -- the release is only wrong when there is something for the freed box to take with it. A fix in `refcount.rs` turned the hang into a leak rather than into correct code, and a second attempt leaked an unrelated local, so it was reverted instead of left half-applied. `Argv.build` returns a plain `Rc<Argv>` and traps on allocation failure, which costs the ability to turn "out of memory" into a `ProcessError`; TODO.md has both the bug and the workaround. Tests: 2 new in e2e_std (helper edge cases, and `run` on the error path so an `Argv` released twice or not at all fails the leak/double-free checker). e2e_std 30 pass / 10 pre-existing failures, e2e_unsafe_count 2, e2e_rc 39, e2e_unsafe 14, e2e_http 7, e2e_net 3, e2e_json 3, e2e_fnvalues 23, e2e_errors 5. e2e_modules 89/2 and e2e_async 19/1 byte-identical to a stashed clean tree. unsafe: http/internal 14->12, process 14->13, net 21, json 13. Ceilings in e2e_unsafe_count updated to the current counts.