se — Part 2 (It Got Bigger!)
Contents
Disclaimer & Intro
This post has been made as my notes, even though I attempt to explain what I have built and how, I do not owe anyone any explanation. Do NOT expect anything.
My blog is my garden.
WARNING: Still no AI. Not one token.
What Happened Since Part 1
Part 1 covered the original se: the structural pipeline model, the ByteView abstraction, NEON literal scanning, out-of-band mutations, and the honest benchmark numbers. Go read that first.
This post covers what happened after. The short version: se is significantly larger and faster, it now beats grep at line-filtering instead of losing by 3×, and it ships a self-contained awk interpreter, fuzzy matching, semantic concept search, and structural tree navigation. Some of this was planned. Free time happened.
Still no AI. No LLM. No Copilot autocomplete. The awk interpreter is ~1,500 lines I wrote by hand with a recursive descent parser and a tree-walking evaluator.
The Benchmark Changed
In Part 1 I reported an honest loss: x/.*\n/ g/ERROR/ p (the grep idiom) was about 2.7× slower than grep. That bothered me. I knew why — splitting the file into one ByteView per line and filtering each through a boxed-iterator chain is a lot of virtual dispatch overhead for what is fundamentally just a scan.
That case is now fixed. The updated table:
| Workload | se | POSIX tool | Outcome |
|---|---|---|---|
Global substitute s/foo/bar/g | 1.40 s | sed 14.7 s | ~10.5× faster |
Locate literal ERROR (offsets) | 0.38 s | grep -bo 4.3 s | ~11× faster |
Filter lines containing ERROR | 0.40 s | grep 3.3 s | ~8.3× faster |
Filter lines containing ERROR | 0.40 s | awk 61 s | ~152× faster |
Exclude lines containing ERROR | 0.87 s | grep -v 5.6 s | ~6.4× faster |
The line-filter result used to be a loss. It is now ~8× faster than grep. All numbers are on an MX Chip, 1.47 GiB synthetic log, F_NOCACHE re-reading from disk on every run.
Why It Changed
A peephole optimizer (parser::optimize) now recognizes the grep idiom and rewrites it before execution. When it sees x/.*\n/ followed by g/lit/ or v/lit/ — where lit is a newline-free literal — it replaces both commands with a single LineFilterCommand.
LineFilterCommand works the way grep does: search, then extend. Instead of creating one ByteView per line and filtering it, it scans the buffer for the literal with NEON, then extends each hit to its enclosing line with memchr forward and memrchr backward. Work is proportional to the number of matches, not the number of lines. With ~5% of lines matching, se touches a small fraction of what grep must read normally.
The invert case (v/lit/ — grep -v) is different. You have to look at every line to know which ones don't match, so the invert path walks lines with NEON newline scan and keeps those with no literal hit. Still faster than grep -v, but the mechanism is different.
The optimizer fires for both the explicit form (x/.*\n/ g/ERROR/ p) and the bare awk form (se '/ERROR/' file), which desugars to the same shape. Both are byte-identical to the unfused pipeline. If the filter is a regex instead of a literal — g/[0-9]+ERR/ — the optimizer does nothing and the general per-line path runs. Fusing that safely requires proving the regex can't match a newline, which is future work.
pub fn optimize(pipeline: Pipeline) -> Pipeline {
// …
if let FusionInfo::LineSplit { require_newline } = &infos[i] {
match infos.get(i + 1) {
Some(FusionInfo::LineFilter { re, invert }) if line_safe_literal(re) => {
out.push(Box::new(LineFilterCommand {
matcher: re.as_literal().unwrap(),
invert: *invert,
require_newline: *require_newline,
}));
i += 2;
continue;
}
// …
}
}
}
Each Command now returns a FusionInfo enum from a fusion_info() method. The optimizer reads those tags and decides whether to fuse. It runs on the top-level pipeline only; nested blocks are left as written, which keeps the semantics predictable.
Capture Groups in s///
s/// now supports capture group references in the replacement. The full set:
$1…$9— numbered groups (Perl style)${12}— multi-digit numbered groups${name}/$name— named groups ((?P<name>…)or(?<name>…))$0— the whole match\1…\9— sed-style numbered groups$$— literal$
# Swap two words
se 's/(\w+) (\w+)/$2 $1/' names.txt
# Named groups
se 's/year=(?P<y>[0-9]+)/[${y}]/' log.txt
# sed-style backrefs work too
se 's/(\w+) (\w+)/\2 \1/' names.txt
# Whole match reference
se 's/hi/<$0>/' input.txt
The implementation lives in commands/replacement.rs as a ReplacementTemplate that compiles the replacement string into a sequence of literal runs and group references. A MatchCaps struct carries the group spans out of the regex engine per match.
The fast path is unchanged. When there are no group references — s/foo/bar/g — the replacement stays a shared Arc<[u8]> and recording each of 50 million substitutions is still a refcount bump. Capture references only allocate when you actually ask for them.
pub enum Segment {
Literal(Vec<u8>),
Group(usize), // 0 = whole match, usize::MAX = absent group (renders empty)
}
An absent group — referencing $7 when the pattern has no group 7 — renders as empty. No error. Same as Perl and every other tool that handles captures.
The Awk Interpreter
Pike's 1987 paper ends with a section called "The awk of the future?" He imagines a version of awk where the patterns define the input structure rather than merely selecting lines, and the actions have access to everything the patterns matched. The idea is that structural expressions and awk actions should be the same language, not two separate tools stapled together.
se now has @{ … } — an awk action that runs with each incoming view as its record:
# Sum column 1, print average
se 'x/.*\n/ @{ s += $1 END { printf "avg=%.2f\n", s/NR } }' nums.txt
# Count occurrences of each value in column 3
se 'x/.*\n/ @{ c[$3]++ END { for (k in c) print k, c[k] } }' access.log
# Per-function analysis: extract C functions, then awk over each one
se 'x/^[a-zA-Z].*\{(.|\n)*\}/ p' source.c
The last example is the point. Classic awk can't do that. x/pattern/ extracts whatever structure you need, then @{ … } does arithmetic over it. The views don't have to be lines. They can be functions, records, paragraphs, anything.
What the interpreter supports
| Feature | Status |
|---|---|
$0..$NF, NR, NF | Done |
FS, OFS, ORS, SUBSEP | Done |
Arithmetic, comparison, &&/||/!, ternary | Done |
Assignment operators (+= -= *= /= %= ^=), ++/-- | Done |
| String concatenation | Done |
Associative arrays, for (k in arr), delete | Done |
if/else, while, for(;;), break, continue, next | Done |
print, printf | Done |
BEGIN { … } / END { … } | Done |
Math builtins: sin cos atan2 exp log sqrt int rand srand | Done |
String builtins: length substr index split sprintf tolower toupper | Done |
In-awk regex literals (~, !~) | Not done — use g///x// instead |
getline, output redirection, pipes | Not done |
| User-defined functions | Not done |
In-awk regex is intentionally omitted. The whole point is that se's structural selectors (g//, x//, v//) handle filtering, and awk handles arithmetic and output. Mixing both in one language just recreates the original problem. Filter with se, compute with @{}.
The field splitter uses the NEON first_of set scan — the same one that handles bracket scanning in tree navigation. When FS is a single whitespace character, split_whitespace() runs. When it is a single other character, the scalar split path runs. Longer FS values split on the literal string.
printf is a full implementation of the awk printf subset: d i o u x X e E f g G c s %, all five flags (- + space 0 #), numeric width, .precision. No * width.
Fuzzy Matching: ~k/pattern/
~k/pattern/ keeps views that contain a substring within Levenshtein distance k of the literal. This is agrep's notion of fuzzy search, expressed structurally.
# Keep lines within edit distance 1 of "error" (catches typos)
se 'x/.*\n/ ~1/error/ p' system.log
# Fuzzy search over multi-line records — no grep-build can do this easily
se 'x/(.+\n)+/ ~2/kitten/ p' wordlist.txt
The implementation has two stages:
Stage 1: NEON pigeonhole prefilter. Split the pattern into k+1 disjoint pieces. Any alignment with ≤ k edits can damage at most k pieces, so at least one piece must occur exactly. Each piece is a SimdLiteralMatcher. If none of them find a match, the view is rejected without touching the DP — at memory bandwidth.
Stage 2: Banded DP verification. Only views that survive the prefilter get the O(n·m) approximate-substring DP. D[i][j] is the minimum edits to align pattern[..i] against a substring of text ending at j. Row 0 is all zeros (the match can start anywhere); column 0 is i (deletions to reduce the pattern to nothing). A match exists iff D[m][j] <= k for any j.
The prefilter is sound — it never drops a real match. For long patterns with small k, the pieces are large enough that the NEON scanner rejects almost everything before the DP runs. For very short patterns or large k, the DP runs more often, which is expected.
pub fn is_match(&self, text: &[u8]) -> bool {
let m = self.pattern.len();
if m == 0 || self.k >= m { return true; }
// Prefilter: at least one disjoint piece must occur exactly
if !self.pieces.iter().any(|p| p.find(text).is_some()) {
return false;
}
// DP confirmation
within_k(&self.pattern, text, self.k)
}
Semantic Matching: :sem:/concept/
:sem:/concept/ keeps views that mention any expansion of concept from a built-in lexicon. :sem:/error/ matches lines containing error, fail, failure, exception, panic, crash, abort, fault, bug — case-insensitive, as a substring.
# Lines about the *idea* of failure, not just the word "error"
se 'x/.*\n/ :sem:/error/ p' system.log
# Concept-driven search over multi-line records
se 'x/(.+\n)+/ :sem:/security/ p' audit.log
I want to be clear about what this is. This is lexicon-based concept expansion. It is not embedding-based semantic search. There is no quantised model, no inference runtime, no vectors. A concept key is looked up in a hardcoded thesaurus; the matching terms are compiled into a case-insensitive alternation and matched with the normal regex-automata meta engine. The meta engine's Teddy/NEON prefilters still apply.
A concept that isn't in the lexicon falls back to matching the word itself, so the operator is always well-defined.
The lexicon is small. It covers error, warning, success, time, money, person, location, network, delete, create, speed, and security. That's it.
I'm not going to ship a quantised model in a text editor to fake neural semantic search.
Tree Navigation: + and -
+ widens each view to the smallest bracketed block that encloses it. - descends into the first balanced bracket pair inside a view.
# Select the {…} block containing "timeout"
se 'x/timeout/ + p' config.json
# The full block containing a specific function call
se 'x/malloc/ + p' source.c
# Select the content inside the first bracket pair on each line
se 'x/.*\n/ - p' code.go
# Expand and then descend: select the body of the block containing "b"
se 'x/b/ + - p' "f({a, b}, c)"
# → a, b
+ (expand) walks backward from the view start to find the unmatched opener, then forward from the view end to find its matching closer. memrchr for the backward scan, NEON first_of bracket scan for the forward one. When a view is already at the top level with no enclosing brackets, it passes through unchanged.
- (collapse) finds the first opener inside the view with NEON first_of, then matches it forward. It returns the content between the brackets, not including the brackets themselves. A view with no brackets is dropped.
Bracket kinds ((), [], {}) are matched by nesting depth across all three, which is the standard "folding" model. This is not a language-aware parser — it works on bytes and balanced delimiters, so it will misbehave on bracket characters inside string literals. That's a reasonable trade-off for a structural text tool. I may look for a solution to this later someday.
Programs that begin with - need -- to keep clap from reading it as an option flag:
se -- '- p' file.txt
The simd.rs Additions
Two new functions joined the SIMD module that other parts of the codebase needed.
memrchr — reverse single-byte search. Used by LineFilterCommand to walk backward from a match to the start of its line. The reverse scans are over the gap since the previous line boundary, so they are disjoint and cost O(n) total across the whole input. Currently scalar; good enough for the workload.
first_of(set, haystack) — find the first byte equal to any member of a small set. NEON implementation: broadcast each set member into a uint8x16_t, compare against the current 16-byte chunk with vceqq_u8, OR the comparison masks together, then vmaxvq_u8 to check if any lane fired. Used by the awk field splitter (whitespace set) and the tree navigator (bracket set).
unsafe fn first_of_neon(set: &[u8], haystack: &[u8]) -> Option<usize> {
let n = set.len();
let mut targets = [vdupq_n_u8(0); 8];
for (i, &b) in set.iter().enumerate() {
targets[i] = vdupq_n_u8(b);
}
while ptr.add(16) <= end {
let chunk = vld1q_u8(ptr);
let mut acc = vceqq_u8(chunk, targets[0]);
for t in &targets[1..n] {
acc = vorrq_u8(acc, vceqq_u8(chunk, *t));
}
if vmaxvq_u8(acc) != 0 { /* scalar confirmation */ }
ptr = ptr.add(16);
}
// …
}
Set size is capped at 8 by the function signature; anything larger falls back to scalar. The bracket set is 6 bytes, the whitespace set is typically 2, so this limit is never hit in practice for me.
What the Tests Cover for Now
tests/cli.rs drives the compiled binary end-to-end. The test suite now covers:
- Extract, yank, global filter, reject filter
- Fused grep idiom — multiple matches per line emitted once, blank line handling, newlineless tail behaviour under
.*\nvs.*\n?, invert - Bare awk form (
/lit/) and explicit (x/.*\n/ g/lit/ p) both fusing - Multi-binder passthrough not broken by fusion (regression test)
- Capture group substitutions —
$1,\1,${name},$name,$0,$$, absent group, global with captures - Substitute flags (
g,i, combined) - Replacement escape sequences
- Change, byte offsets, next-join, reduce, awk binder, map block, nested block
- Some Edge cases: empty input, no-match substitute passthrough, invalid regex, unbalanced brace, unknown command
- In-place edit, in-place with backup
- Tree expand and collapse, roundtrip, top-level passthrough
- Fuzzy matching at distance 1 and 2
- Semantic matching — known concept, unknown concept fallback
- Awk fields, NR, NF, sum with BEGIN/END, associative arrays, for-in, math builtins, printf
Current Status
| Feature | Status |
|---|---|
Core commands (x y z g v c s p = N r t m) | Done |
| Fused NEON line-filter | Done — beats grep ~8× on literal |
Capture group references in s/// | Done |
Awk interpreter (@{ … }) | Done |
Fuzzy matching (~k/pat/) | Done |
Semantic matching (:sem:/concept/) | Done |
Tree navigation (+ / -) | Done |
Named capture references in s/// | Done |
argv[0] dispatch to emulate sed/awk/grep | Not done |
miette source-span diagnostics | Not done |
| Non-literal regex line-filter fusion | Not done |
The Full Command Set (Current)
# SELECTORS
se 'x/re/' # extract: replace views with matches of re
se 'y/re/' # yank: replace views with gaps between matches
se 'g/re/' # keep only views containing a match
se 'v/re/' # drop views containing a match
se '~2/pat/' # fuzzy: keep views within edit distance 2 of pat
se ':sem:/concept/' # semantic: keep views mentioning concept
# ACTIONS
se 'c/text/' # change: overwrite each view with text
se 's/re/repl/gi' # substitute with capture refs, global, case-insensitive
se 'p' # print
se '=' # print byte offsets (start,end,length)
# OPERATORS
se '{ ... }' # group: run sub-pipeline on each view
se '/re/ { ... }' # awk binder: run block on matching views
se 'm/re/ { ... }' # map: extract matches and run block on each
se '@{ awk }' # awk action: each view is a record
se 'N' # next: merge adjacent view pairs
se 'r/sep/' # reduce: fold all views into one joined by sep
se 't { ... }' # test: run block if substitution was made
se '+' # expand: widen to enclosing bracket block
se '-' # collapse: descend into first bracket pair
One More Benchmark Number
The line-filter fix turned the worst case into the best case. The ~152× awk number is worth sitting with. awk at 61 seconds on a 1.47 GiB file for something as simple as pattern-matching every line. That is not a awk problem, it is a model problem. When the tool's model is wrong for the job, performance degrades accordingly.
se at 0.40 seconds on the same file, re-reading from cold disk every run. That is the difference between treating files as arrays of characters and treating them as arrays of lines.
Pike was right in 1987. I just built the tool he was describing.
Engineering is measurable. Measure it.
Jai Hind.
Wake up. Dig deeper.
#rust #development #research #systems #linux #macos
🔑 Verify authenticity
PGP key xer0x-public.asc · id e8270d03
sha256(post) fd04b070c8fbb51931b9bd24c729006878407e38a25a20fecdc37d8ea347f6fd
Confirm this post is byte-for-byte authentic — paste into any macOS or Linux terminal:
curl -fsSL https://xer0x.in/blog/se-02/content.txt | openssl dgst -sha256 | grep -qi fd04b070c8fbb51931b9bd24c729006878407e38a25a20fecdc37d8ea347f6fd && echo "signature ok" || echo "TAMPERED"