On this page

0235. Compact C for large integer matches

Context

lower::integer_match turns each arm into a private done/matched flag plus >=/<= predicates, and the C backend printed that as a nested if chain with a #line per statement. plugins/tui/unicode.hn has matches of several hundred range arms (gcb, wide); they were 61% of the TUI dashboard's generated C. A 588-arm microbenchmark took gcc -O2 about 100 s (207 s under load) to compile and 470 ms to run.

Patterns are half-open (lo..hi), literals are n..n+1, alternatives use |, and the checker allows overlapping arms: first match wins.

Decision

Only C emission changes; Core IR and harness interp keep the if chain as the independent reference. cgen_match recognizes exactly the predicate shape integer_match emits, for 8 or more consecutive integer-pattern arms on one scrutinee (_ and later arms are emitted as before). It resolves overlaps at compile time with an endpoint sweep that keeps the lowest arm index, producing disjoint inclusive ranges, then:

Byte (u8) decision trees keep the existing 256-entry table (cgen_byte), which is tried first. Matches with fewer than 8 arms emit unchanged C.

Alternatives considered

Consequences

The 588-arm microbenchmark compiles in 0.23 s and runs in about 45 ms with identical output; the TUI dashboard's emitted C halves (2.69 MB to 1.43 MB). Emitted C changes only for programs with such matches (TUI plugins, the http reason table and generated codec field dispatch). Runtime traps, results and evaluation order are unchanged; tests/programs/integer-match-table checks boundaries, overlaps, widths and loop control against the interpreter.