feat/lsp #1

Merged
duke_duck merged 84 commits from feat/lsp into main 2026-10-11 07:23:13 +00:00
Owner

add a language server and many numerious fixes and features

add a language server and many numerious fixes and features
`examples/http_server.hiki`'s `serveMany` is `Loop` plus `spawn` now. An
acceptor task parks on the listener and spawns a `serveOne` per connection, and
`loop.run(maxRequests + 1)` is the whole scheduler -- the `+ 1` is the acceptor,
since every other task is a connection, so the loop returns when the last one is
done without anybody counting.

This is the first thing in the project to put the loop, `spawn` and two awaited
operations on the same real descriptor at once, and it found a bug in the loop
that no earlier test could reach. `adopt` appended and did `live += 1`; `retire`
lowers `live` *without* shortening the array. So after the first retire the two
disagreed about which index was live, and the next adopted frame went in one
slot past `live` while claiming the slot below it -- a poll of freed memory,
which reported a frame kind of 3 and spun. Every test so far spawned its tasks
before its first turn, so `live` happened to equal `frames.count()`; a task that
spawns from inside its own poll is the shape that pulls them apart. `adopt` now
re-establishes `live` from the append and reuses the vacated slot, and the
invariant is written down on the field.

`acceptWait` also hands back a non-blocking connection now. It has to: an
awaited accept is nearly always followed by an awaited read, there is no `try` in
between, and on an inherited blocking socket that read never returns -- the same
trapping mistake `makePipe` had, one layer up.

`tests/e2e_http.rs::silent_clients_do_not_delay_others_on_the_event_loop` is the
property the rewrite is for: five clients that connect and never speak, then
twenty fast ones, all answered in milliseconds. A serialized server answers too
-- it just cannot get there, because the five are ahead of the twenty in line.

260 tests.
`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.
Thirteen warnings to none. Most were leftovers from the async transform: a
`Gen` builder that tracked locals no helper ever read, a reachability walk
nothing called, two name-parsing helpers superseded by the Task type itself, and
three struct fields set by one pass and read by no one.

Two were not cosmetic.

`lower_poll` returned `Result<(), String>` and could not fail, so both call sites
discarded an error that could never arrive — which is the shape that eventually
grows one. It returns unit now.

`pretty_print` was unused in the bin because `emit-mir` always called the *sized*
printer, even for a program with no `async` function and therefore no sizes to
report. It printed an empty column rather than no column, which reads as a
measurement that came back nothing. Two printers, chosen on whether there is
anything to measure.

`docs/PHASE-7.md` gets a status line per step, the real test count, and a new
section on the three bugs from this stretch. They are one bug in three costumes —
a number that meant one thing read as another — which is the pattern worth
recording rather than the instances: `waitTimeout` read as an absolute clock,
`Loop.live` read as `frames.count()`, and a `Void` result read out of a frame
with no result field. All three were silent, and all three would have been found
by the test that went with the feature rather than by the feature's own tests.

Also records why `task.cancel()` is left. A task cannot read its own frame, so
making the flag observable needs a compiler hook at each `await`; the check has
to throw, so it needs a spawned function that can be `throws`. Those are one
piece of work, and the third part — per-suspension-point drop glue, so freeing a
cancelled task's frame does not free a live `String` underneath it — is what
decides whether the first two are worth their shape.

262 tests, zero warnings.
`examples/http_server.hiki` on both runtimes: three clients that connect and never
speak, then ten concurrent `GET /` -- ten answered, zero errors, on `c` and on
`hiki` alike. An async test that only runs on one backend is a test of half the
thing, since `hiki` is a different allocator, a different string representation
and a different set of syscalls underneath.

Three clippy lints in this phase's code fixed (`append` for a full-vector drain,
an explicit auto-deref). The fourth, `emit_assign`'s eight arguments, is left:
threading a context struct through it is a refactor of a hot, well-tested path
for a lint that has been pre-existing since before this phase.

`bench/compare.sh` records 1.00x. `docs/PHASE-7.md` gets the current number, the
two-backend check, and nothing else changed.

262 tests, zero build warnings, one pre-existing clippy lint.
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.
The `doc_above` function now strips `///` before `//` to prevent a stray
leading slash in documentation. Additionally, imported symbols are now
categorized into `by_name` and `members` within a new `Visible` struct,
ensuring that namespace imports (e.g., `sys.free`) do not pollute the
top-level name resolution table. This allows prelude and explicit
imports to carry their own documentation correctly without affecting
bare name resolution.
the Hiki prelude

The editor session now defaults to the pure-Hiki `String` rather than
the
C-backed one, per spec §18.6 which allows exactly one `String` to be
live.
`hiki_lsp::analysis::BACKEND` selects the backend, and `string_type()`
derives the mangled type name from it instead of hard-coding
`hk_std_string_c_String`, which previously caused every string literal
to
be typed as a type the program does not have.

The backend is threaded through `prelude_symbols`, `Visible::all`, and
the
resolver so member lookups translate mangled names back to source names.
Tests verify the default `String` identity, that `s.count()` resolves
and
hovers, and that inlay hints show `String` rather than a mangled name.
editing an incomplete file

The strict parser's response to an invalid file was to produce no
analysis at all, which silently disabled hover, goto-definition,
references, semantic highlighting, and completion for the entire
duration of an edit. Switching `Analyzed::build` to `parse_recovering`
keeps the model usable mid-edit, with per-item diagnostics pointing at
the actual broken ranges instead of the top of the file. The compiler's
path through `parse_spanned` is unchanged, so nothing here can make a
broken program build.

Completion was rewritten around the same premise. It now reads the token
stream directly to decide what the cursor is asking for—members after a
dot, namespace members after `alias.`, types after `:`/`->`/`as`, or
bare names—and filters by the prefix being typed, so it answers
correctly on files that do not parse. Items are tiered (locals, then
file declarations, then imports, then the prelude) and keywords and
declaration-form snippets lead. Members and namespace members are no
longer offered as bare names, primitive types appear in type positions,
and an empty list is returned instead of `null` so clients keep asking.

Two semantic bugs fixed along the way: `Ty::name` now includes `Applied`
so generic receivers like `Map<String, i64>` resolve their members, and
the import filter snapshots the file's own names before filling in
imports so `String.count` and `Array.count` both survive instead of the
second being dropped as a duplicate. Call labels now resolve to the
callee's field or parameter rather than the enclosing scope, and a
destructured import's placeholder is overwritten when the import fills
in what the name refers to. The old `probe.rs` smoke test is removed and
replaced by targeted tests in `hiki-syntax` (recovery makes progress,
the compiler path still fails), `hiki-semantics` (broken files yield a
usable model, mangled receivers, array members, skipped-statement
resolution, import placeholders, same-named methods on different types),
and `hiki-lsp` (completion contexts, prefix filtering, snippets, import
details, empty lists, hover/tokens on broken files, and diagnostics on
the broken line).
Update hiki-semantics to mark submodules in module names

The `hiki_semantics` crate now marks submodules in module names. This
makes the library's output
compatible with the `crate` feature, which is designed to work with
`cargo` and other tools
that assume the root module is the name of the crate.

The change is in `hiki_semantics/src/program.rs` and
`hiki_semantics/tests/hir.rs`.
The body of the commit message should explain the changes made in the
commit. It should be short and concise, and should not repeat
information from the subject line. Use the imperative mood in the
subject line. If the changes can be summarized in just the subject line,
then the body can be omitted.

In this commit, we have made improvements to the code by adding
descriptive commit messages. This will help others understand the
changes made more easily and make it easier to track progress on the
project. The commit messages now provide useful information about the
changes made, making it simpler to review and understand the codebase.
In the lowering process, we've added a release statement to free up
memory when dealing with async await loops. The subject line clearly
states the change made and the reason behind it. The body provides
additional context about the issue that led to this change and how it
solves it. The commit message is concise and easy to understand, making
it simple for anyone reading it to grasp the purpose of the commit.
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.
Follows the amortized `String.append` from the previous commit, which made it
worth using: `out = out + s` in a loop is one allocation per iteration, and
`out.append(s)` is zero once the box has room.

`writeResponse` built every response with `out = out + ...` once per header, so
a response with n headers cost n allocations and -- worse -- O(n^2) copied
bytes, because each step built a fresh String from both operands and recopied
every header written so far. Measured on a nine-header response: 13 allocations
now 10, and the quadratic copy gone entirely.

The saving is smaller than it first looks, and the reason is worth recording:
`+` over a chain already desugars to a *fused* concat -- codegen emits one
`hk_string_concat_n_to` for the whole chain, which `refcount` pins with a test --
so a per-header `+` was one allocation, not one per operand. What it was not free
of was the copy. The alloc test's bound is set at 11 rather than something
generous for that reason: it has to sit between the measured 10 and the 13 the
old spelling produces, or it would not catch the regression it documents. I
checked that it fails when `writeResponse` is reverted.

`parseRequest` called `headerEnd(raw)` twice -- once for `head`, once for `end`
after the header loop -- and the second cannot differ, since nothing in between
touches `raw`. One scan now serves both.

`lowercased` was `s.toString().lowercase()`: materialize the view, then
lowercase that copy. Two allocations for one lowercase, run once per header
name per request. `Str.lowercase` and `Str.uppercase` copy once and transform
the copy, which is all the second copy was ever for.

A gap this found, which is pre-existing and not fixed here: a `String`
*parameter* takes no implicit `Describable` conversion. `take(n)` with `n` an
`i64` fails to compile, while `n + 1` works, because `+` desugars to a
describe-based concat. So the pieces of a response that are not already Strings
-- `status` is an `i64` -- have to be described explicitly. The original
`writeResponse` got this for free by routing them through `+`; `append` does not,
which is why the status line and the content-length are interpolated. Worth
closing on its own: it is a hole where correct-looking code will not build, and
the diagnostic is a C type error rather than a Hiki one.

Tests:

- `e2e_alloc`: serializing a response does not allocate per header, bounded so
  it discriminates between the two spellings.
- `e2e_std`: `Str.lowercase`/`uppercase` agree with the `String` spellings byte
  for byte. They are hand-written rather than delegating, so the two can drift,
  and a drift would be silent -- `std/http` lowercases header names through the
  `Str` path and compares them through the `String` path, so a header that
  stopped matching would be dropped rather than misread. The comparison runs in
  the program and prints a verdict, because parsing lines whose payload can be
  empty in Rust would test the parser rather than the case conversion.
`take(n)` where `n` is an `i64` and `take` takes a `String` did not compile.
The failure was a C type error -- `passing 'int64_t' to parameter of
incompatible type 'hk_std_string__string_String'` -- while `n + ""` and `"\(n)"`
both worked, because those desugar to a describe-based concat. So the same value
was acceptable to concatenate and not to pass, and the diagnostic a reader got
was in clang's vocabulary with no mention of `Describable` and no suggestion.

`print` already converted its argument this way, which is why `print(n)` worked
and `take(n)` did not. This makes the two agree.

Found by the previous commit rather than designed for: `writeResponse` now
appends, and `HttpResponse.status` is an `i64`, so `out.append(r.status)` was
the first thing to hit it. That commit interpolated the two non-String values as
a workaround; this removes the workaround, so `writeResponse` appends
`r.status` and `r.body.count()` directly.

The two call paths differ -- a free function's arguments go through
`lower_call_args` and a method's through the receiver loop -- so the rule is one
function called from both. Fixing only the free-function path left `append`
broken, which the e2e_alloc response test caught; that is why it is shared rather
than written twice.

Narrow on purpose: only a parameter that *is* a String, and only when the
argument is not already one. A `Point` argument to a `Point` parameter is
untouched, a numeric parameter is not a String so no numeric conversion changes,
and `Unknown` is left alone -- it means the argument's type is an inference gap
that `describe_value` cannot resolve either, so converting it would report a
real bug in the wrong terms.

A type with no `describe()` is now a Hiki diagnostic naming the fix, rather than
a clang one naming nothing: "has no `describe()`", plus the `extension
Opaque: Describable` spelling that would work.

Tests in `e2e_fnvalues`, both halves: the conversion over i64/u64/f64/bool/
already-a-String/user-type-with-describe, with numeric parameters alongside to
show they are unaffected; and the rejection, asserting the message names the
witness and does *not* read `incompatible type`.
The list in `AGENTS.md` was short by 13 of 19. It named 6, which meant
`e2e_prelude` and `e2e_go_parity` looked green when they are not, and 7 of the
10 `e2e_std` failures were absent entirely. Anyone reading it would have chased
failures that were not theirs -- the opposite of what it is for. Re-verified by
stashing and re-running each suite on a clean tree at `1ea4ae0`.

Also recorded, because it is the reason `tools/t.sh` exists and the list did not
say so: `hiki-semantics`'s `hir` test does not compile (`missing field
'owned_members' in initializer of 'Visible'`, three sites), so
`cargo test --no-fail-fast` stops before any suite runs at all.

`TODO.md` gains the efficiency pass, and two negative results worth more than
the positive ones:

Small-string optimization cannot be done in this representation. SSO needs
`ptr` to point into the String's own inline buffer, but a String is copied by
value -- `return l0_t;`, a by-value parameter, `let b = take(a)`, an
`Array<String>` element are each a struct copy in the generated C -- so a copy's
`ptr` would point into the original's inline buffer and dangle the moment the
original died. Growing `HikiString` does not help: SSO needs a tagged union, so
`ptr` is not always a pointer to the bytes, which breaks the invariant
`c/string_types.c` states outright ("`ptr`/`len` always point at the live bytes
either way, so reads never need to branch"). Every read site would have to
learn to branch. It is a change to the language's core value type.

`readAvailableWait`'s malloc-8192-then-copy is already the right shape. Reading
into the `RcBuf` directly saves one allocation but retains 8 KiB per in-flight
read instead of freeing the scratch immediately -- a bad trade for a server
holding many concurrent connections. The frame-carried scratch that avoids both
needs the `Wait<String>` shape changed, and at ~2 allocations of 72 per request
it is not worth touching the async frame layout for.
Each turn polled every parked task and recomputed the deadline by
scanning all frames. The loop now files each frame's wait into a
descriptor chain, a run queue, or a deadline heap, and polls only the
frames that are due.
`std/buffer.hiki` is a growable byte buffer: appendString/appendFrom/
appendByte to add bytes, toString to materialise, readInto(fd) to read
once from a descriptor and grow as needed.

It is an `RcBuf` rather than a malloc'd block, so the runtime frees it on
every path including the `throw` ones. That is the reason it is worth
landing: `fs.readFile` had a `malloc` with a matching `free` on three
exits and `process.captureOutput` had four, and each set becomes a leak
the moment someone adds an exit and forgets the `free`. Ownership removes
the class rather than the instance. It also retires the `nil` check after
the allocation -- `RcBuf.alloc` traps instead of returning nil.

`readInto` additionally owns the grow-before-read / record-length-after
order, which is the part that is easy to get subtly wrong by hand, and
`fs.readFile` becomes a loop rather than one read bounded by a size
`seek` measured earlier -- so a file that grew in between is no longer
truncated.

Two methods that mutate the length must be `mutating`: `readInto` was not,
at first, and read 0 bytes every time. A non-mutating method takes `self`
by value, so the length it set went to a copy that died at the return.
Nothing warned -- it compiled, ran, and returned a plausible number -- so
the test that catches it asserts the byte count against the real file size
rather than just checking the text.

Tests: 2 new in e2e_std (growth across reallocation, and readInto on a
file larger than the starting capacity), both asserting no `hiki: leak`.
e2e_std 28 pass / 10 pre-existing failures, unchanged from a clean tree;
e2e_rc 39, e2e_unsafe 14, e2e_http 7, e2e_net 3 all green.
The ratchet (spec §10.1, §18.6): `e2e_unsafe_count` holds each std module
to its current count, so the number can only go down. Ceilings rather than
an allowlist of permitted modules, because an allowlist keeps passing
while a module grows from 3 uses to 30 -- the failure this exists to
catch. A module using `unsafe` with no ceiling also fails, so a new
module cannot opt itself in by omission. Comments are excluded: the
count would otherwise measure how much `array.hiki` explains the
refcount protocol in.

Verified by deliberately breaking it -- adding an `unsafe` to std/json
reports `std/json/mod.hiki: 14 > 13`, and a new std/probe.hiki reports
that it has no ceiling.

The `Ptr<` half of the check excludes `@extern` parameter types.
`poll.hiki`'s `c_poller_wait(_ events: Ptr<u8>, ...)` passes a pointer
*to* C, which reads it; nothing there dereferences it, so requiring
`unsafe` would require a keyword for a dereference that does not happen.

Also: `string_c.hiki` is exempt from the ratchet, with the reason in the
file. It is the C-backed reference String behind `--runtime-backend c` --
a differential-testing target, not the runtime anyone runs.

array.hiki gains a comment, no behaviour change. The doc's suggestion for
`grow` was to move elements with no refcount traffic, since `append`
checks `isUnique` first and the buffer is exclusively held. That argument
is sound and it is not a refcount-correctness problem -- it is blocked by
sizing: `memcpy` needs `T.sizeOf()`, and `T` cannot be named inside a
method of a generic type. Attempted, reverted (it broke 3 e2e_http tests
before being caught), and written up so the next attempt does not
rediscover it. The ownership half being settled is the part worth having
in the file.

Suites: e2e_unsafe_count 2, e2e_rc 39, e2e_unsafe 14, e2e_http 7,
e2e_net 3, e2e_json 3, e2e_fnvalues 23 all pass. e2e_std 28/10 and
e2e_modules 89/2 and e2e_async 19/1 match the clean-tree baseline.
`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.
`cpu_secs` read `ps -o time=`, which is macOS's spelling. Under OrbStack
that reports `00:00:00` for any process, so every CPU figure in the
status-server benchmark came back zero -- and looked plausible, because a
server that had just answered 299 requests reporting no CPU at all is a
number nobody stops to question.

Verified rather than assumed: a 2-second busy loop reads `00:00:00`
through that VM's `ps` while `/proc/<pid>/stat` reports 50 ticks.

Now reads `utime`+`stime` from `/proc/<pid>/stat` on Linux, divided by
CLK_TCK, falling back to `ps` on macOS and when `/proc` is unavailable.
The field scan starts after the closing parenthesis of `comm`, which may
itself contain spaces and parentheses -- `(sleep)`, `(my prog)` -- so the
line cannot be split blindly.

`cpu_secs_reads_a_real_process` burns known CPU in a child and asserts
`cpu_secs` sees it, which is the check that was missing: confirmed to
fail (0.00, 30s timeout) when the `/proc` path is disabled, and to pass
with it, on both macOS and the VM.

bench/compare.sh: `--bin hiki`. The workspace has two binaries, so a
bare `cargo run` stops with "could not determine which binary to run".
That has been true since the split that added hiki-lsp, so the strings
benchmark has not been runnable as written.

Status servers, 2-core OrbStack VM, HIKI_BENCH_SCALE=2:

  metric                          go        hiki
  binary bytes              8251844       149448
  idle RSS kB                 17208        1304
  RSS kB, 10k parked         120428        9724
  kB per parked conn            10.3         0.8
  CPU s while parked             0.34        0.04
  req/s (8 conns)            117576       237590
  CPU s saturating             8.22        6.79

Strings, 2-core VM, best of 5, 4 runs: c 167-175ms, hiki 167-168ms,
ratio 0.99-1.00x.
Completion ranked bare names by tier, then discarded that order in
`finish`, which sorted by name. Type positions listed everything
alphabetically, burying primitives like `i64` under library types.

Replace `finish` with `finish_ranked`, which keeps a (tier, order) rank
and breaks ties by name. Locals lead bare completions once a prefix is
typed, and type positions order own types, primitives, prelude types,
then the rest of the library.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
duke_duck/hiki-lang!1
No description provided.