preprocess

package
v0.17.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 5 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package preprocess provides line-preserving content transforms that rules select via the envelope's preprocess: param (spec §5, §6; phase-3a design §1). Transforms know nothing about rules; scan caches their output per file. Every Transform MUST be pure and line-preserving: same line count as the input, removed text replaced by spaces.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CodeOnlyDart

func CodeOnlyDart(src []byte) []byte

CodeOnlyDart keeps only the CODE of a Dart source file: comment bytes (`//`, `///`, and the nesting `/* … */` form) and the CONTENTS of every string literal become spaces. The quote delimiters themselves survive, so the projection still reads as Dart — an empty string where a literal was — and a rule can tell "a string was here" from "nothing was here".

It is the complement of CommentsOnlyDart and shares that function's lexer shape, including its two bounding decisions: block comments NEST, and a single-/double-quoted string is closed at a newline as well as at its quote so an unbalanced quote costs one line of projection rather than the rest of the file (#9272).

Blanking string contents is what makes DELIMITER COUNTING sound. Dart string interpolation puts arbitrary code — including parentheses and braces — inside a literal (`'${label(x)}'`), and a rule that walks an argument list by bracket depth over raw source would take those as real brackets and lose the end of the invocation. Under this projection an interpolation contributes no delimiters at all.

func CommentsOnlyAwk

func CommentsOnlyAwk(src []byte) []byte

CommentsOnlyAwk keeps only the CONTENTS of awk '#' comments: the text after each '#' survives verbatim; code, "…" string contents, /…/ regex-literal contents, and every delimiter (the '#' included) become spaces. Same contract and same purpose as CommentsOnlyGo; see that doc comment for why a comment-opener regex cannot substitute.

awk is NOT a scope widening of the shell lexer, and the difference is not cosmetic:

  • awk has /regex/ literals. A '#' inside one is regex content. Whether a '/' opens a regex or is the division operator cannot be decided from the byte alone — it depends on what came before, because a regex literal is only valid where an OPERAND is expected. prevValue below carries exactly that one bit.
  • awk has no heredocs and no single-quoted strings. The shell lexer treats an apostrophe as opening a literal that spans lines, so it desyncs on the first apostrophe in awk code or in a comment ("don't") and blanks every comment after it — a silent pass, not a visible error.

Both failure directions are real, but they are not equally bad. Reading a regex as division makes a '#' inside the regex look like a comment opener, which reports a violation that is not there — loud, and corrected by the next reader. Reading division as a regex swallows the rest of the line hunting a closing '/', which blanks a real comment and makes any marker in it unmatchable — silent, and it passes a file that should fail. Where the grammar is genuinely ambiguous this lexer therefore prefers division.

func CommentsOnlyDart

func CommentsOnlyDart(src []byte) []byte

CommentsOnlyDart keeps only the CONTENTS of Dart comments: the text of `//`/`///` line comments and `/* … */` block comments — which NEST in Dart — survives verbatim; code, string contents (single `'`, double `"`, the two triple-quoted forms, and the raw `r'…'`/`r"…"` forms), and every delimiter become spaces. Same contract and same purpose as CommentsOnlyGo; see that doc comment for why a comment-opener regex cannot substitute.

Contributed from the validating port, where it replaced a hand-maintained awk lexer that was deleted once this became the only implementation. This is the sole definition of the contract; tested at comments_only_test.go in this package.

One deliberate difference from the awk it replaced: a single-quote/double-quote string is closed at a newline as well as at its quote. Dart's non-triple string forms cannot span lines, and bounding them means an unbalanced quote costs one line of projection rather than blanking the rest of the file — the unbounded blast radius #9272 was filed about.

func CommentsOnlyGo

func CommentsOnlyGo(src []byte) []byte

CommentsOnlyGo keeps only the CONTENTS of Go comments: the text of `//` line comments and `/* … */` block comments survives verbatim; code, string/rune/raw literal contents, and every delimiter (including the `//`, `/*` and `*/` themselves) become spaces. It is the third projection of the shared Go lexer family — DecommentGo keeps code, StringsOnlyGo keeps string contents, this keeps comment contents.

It answers the question an annotation-marker rule needs: "is this token inside a COMMENT — regardless of where in the comment it sits?" A comment-opener regex cannot answer that. It (a) misses a marker on a bare continuation line of a multi-line block comment, because that line carries no comment token at all, and (b) accuses comment-shaped bytes INSIDE a string literal, where an annotation spelled inside a `"// … "` prefix is data — which is exactly the shape of the marker rules' own pattern tables. Because the delimiters are blanked, a consuming rule needs no comment-opener anchor in its pattern at all — being present in this projection IS being in a comment.

Contributed from the validating port, where it replaced a hand-maintained awk lexer of the same contract. That awk remains live there on a separate path, so downstream holds the two to one shared case table; upstream's copy of that table is comments_only_test.go in this package.

func CommentsOnlySQL

func CommentsOnlySQL(src []byte) []byte

CommentsOnlySQL keeps only the CONTENTS of SQL comments: the text of `--` line comments and `/* … */` block comments — which NEST in PostgreSQL — survives verbatim; code, string contents (`'…'` with doubled-quote and E-string `\` escapes, `"…"` quoted identifiers with `""` escapes, and `$tag$…$tag$` dollar-quoted bodies), and every delimiter become spaces. Same contract and same purpose as CommentsOnlyGo; see that doc comment for why a comment-opener regex cannot substitute — a dollar-quoted function body is a string literal, so a `--` inside one is row data, not a comment.

The lexical rules live in sqlScanComments (sql_lex.go), shared with DecommentSQL, which is this function's complement. This is the sole definition of the keep-comments contract; tested at comments_only_test.go in this package.

Contributed from the validating port, where it replaced a hand-maintained awk lexer that was deleted once this became the only implementation.

func DecommentDart added in v0.6.1

func DecommentDart(src []byte) []byte

DecommentDart blanks Dart comments, retaining every other byte, including literal text and executable interpolation. Nested comments, raw/triple strings and nested interpolation are lexical contexts, not regex boundaries. Output owns its storage and preserves byte offsets and CR/LF positions. Unterminated block comments run to EOF; a non-triple string ends at a bare CR or LF, bounding malformed source without truncating subsequent code.

func DecommentDestringGo

func DecommentDestringGo(src []byte) []byte

DecommentDestringGo blanks Go comments AND the interiors of string and rune literals, preserving line structure. Only real code survives.

decomment-go alone is not enough for a required-pattern that must prove a call is still made: the symbol surviving in a string literal satisfies the matcher just as a comment used to. For the entitlements lockdowns that is the natural shape of a refactor rather than a contrivance — the package already carries several fmt.Errorf("entitlements.ConsumeTakeoff: %w", err) strings, so the call can be deleted while the error-wrap string keeps the gate green.

The quotes themselves are kept so the result stays recognisably Go and a pattern anchored on a delimiter still behaves; only the contents go.

func DecommentGo

func DecommentGo(src []byte) []byte

DecommentGo blanks // and /* */ comments in Go source, preserving line structure. Comment markers inside string and rune literals are untouched.

func DecommentSQL

func DecommentSQL(src []byte) []byte

DecommentSQL blanks SQL comments and keeps everything else — the complement of CommentsOnlySQL. `--` line comments and `/* … */` block comments (which NEST in PostgreSQL) become spaces, delimiters included; every other byte survives verbatim. Newlines are preserved, so the result has the same length and the same line structure as the input: byte offset N in is byte offset N out, and a consumer that counts newlines to report a line number reads the same number before and after.

It shares CommentsOnlySQL's lexer (sqlScanComments), so the rules for what is NOT a comment are stated once rather than twice: `'…'` with doubled-quote and E-string `\` escapes, `"…"` quoted identifiers with `""` escapes, and `$tag$…$tag$` dollar-quoted bodies are string data, and a `--` inside one is row content rather than a comment. `$1` does not open a dollar-quote. An unterminated comment runs to end of input; an unterminated string swallows the rest, so no comment is found inside it. Those are the existing lexer's semantics — this function inherits them, it does not restate them.

DELIBERATELY NOT REGISTERED as a `preprocess:` vocabulary word. A registered transform is applied to whole source files as the engine scans them, and the caller that needs this one — the sql/statement-predicate rule type — works on SQL that sqlextract has already lifted OUT of Go string literals. Running SQL lexing over raw Go source fails in the silent direction: the SQL sits inside `"…"`, which this lexer reads as a quoted identifier, so a comment inside it is never seen and the transform would report success having done nothing. Registering it is a separate decision with its own vocabulary cost (Names(), the AGENTS.md map, `formwork list preprocessors`); it is not owed by #137.

func DecommentSh

func DecommentSh(src []byte) []byte

DecommentSh is the fourth projection of the one shell lexer (scanSh): it blanks ONLY the blankable-comment spans and leaves everything else — string interiors, heredoc bodies, code — matchable. It exists for gates ported from bash pipelines whose comment handling was `grep -v '^[[:space:]]*#'` (strip comment lines, keep string contents): the bash buf-breaking baseline gate is the case in point, where the forbidden shape `branch=staging` lives INSIDE a quoted --against ref, so DestringSh's string blanking would silence the gate and DestringDecommentSh's pair of blankings doubly so.

The blanked-comment boundary is the same narrow one DestringDecommentSh documents (isCommentBlankBoundary): a '#' blanks to end-of-line only at start-of-line or after a space/tab, matching the reference stripper `sed -E 's/(^|[[:space:]])#.*$//'`. A `cmd;# ...` comment is skipped by the lexer but NOT blanked; ${x#foo}, $#, and url#fragment are never comment starts. Because string interiors survive, an apostrophe inside a blanked comment can never open a phantom string either — the lexer still skips the comment before quote state is considered.

func DestringDecommentSh

func DestringDecommentSh(src []byte) []byte

DestringDecommentSh is DestringSh plus comment-body blanking: string interiors, heredoc bodies, AND the body of a '#' comment (the '#' included) are replaced by spaces. Quotes, heredoc delimiter lines, and line structure survive, as with every transform here. It is the third projection of the one shell lexer (scanSh), which is why it cannot drift from DestringSh about where a string ends: it blanks exactly DestringSh's spans, plus the lexer's blankable-comment spans.

The two differ only in what a comment gets. DestringSh skips over a comment without touching it — enough to stop an apostrophe inside one from opening a phantom string, but the comment text remains matchable. That is wrong for any rule whose pattern is a shape the scanned files are expected to DESCRIBE as well as avoid: the validating port's shell-meta gates (check-no-sigpipe-producer-grep, check-no-negated-searcher-quiet) ban a code shape that every gate header comment quotes verbatim, so matching against destring-sh output alone reports the documentation as a violation. Those gates pipe destring-sh.awk through a sed comment-stripper for exactly this reason; this transform is that pair in one pass, and inherits the correct heredoc-in-comment handling (issue #6) that the awk version lacks.

The blanked-comment boundary is NARROWER than the boundary DestringSh uses to merely SKIP a comment, and the two must not be conflated. A '#' is only blanked when it begins a line or follows whitespace — the reference stripper's `sed -E 's/(^|[[:space:]])#.*$//'` rule. It is *recognized* as a comment (and skipped) after the wider word-breaking set ';', '|', '&', '(', ')', '<', '>' too, but blanking there would destroy live code — `x=$(ls)#tag` is a single shell word — so a comment introduced by one of those characters is left intact, exactly as the sed leaves it. That distinction is enforced inside the lexer, which reports the wide set as skipped and only the narrow set as blankable (isCommentBlankBoundary). A rule reading this transform therefore must NOT assume every comment is blanked: a `cmd;# ...` comment survives into the scanned view. In both cases ${x#foo}, $#, and url#fragment are ordinary text, never comment starts.

func DestringSh

func DestringSh(src []byte) []byte

DestringSh blanks the contents of single- and double-quoted strings and heredoc bodies in shell text; quotes and heredoc delimiter lines survive. It is one of the two projections of the shared shell lexer scanSh — this one DROPS the data regions, StringsOnlySh keeps only them — so the two can never disagree about where a string ends.

It stands in for the validating port's scripts/lib/destring-sh.awk, but is NOT a byte-for-byte reimplementation of it — deliberately, because the awk has known defects the port exists to remove (issue #6 and its §7.1b): the awk reads a heredoc token inside a comment as a real opener and blanks to EOF, and its strictly line-based quote matching mis-lexes multi-line constructs. This lexer is a proper cross-line lexer: a string, heredoc, or the state between them is tracked across newlines. That is what lets it correctly close a multi-line single-quoted awk program and see the real `| grep -q` on its closing line — a live violation (check-go-golangci-pinned.sh:97) the line-based awk blanks and misses. Cross-line tracking is the feature, not an accident.

The cost of cross-line tracking is a bounded-blast-radius hazard in ONE direction: an unbalanced quote (a lone `"` or `'` with no partner) opens a string that runs to the next matching quote or to EOF, blanking real code in between. That is the BLIND direction, and it is worth being explicit about which way blindness runs here: this projection keeps code and blanks data, and a forbidden-pattern rule fires on what SURVIVES, so an over-blank makes the blanked text unmatchable and the rule reports a false PASS. An over-blank is silence, never a loud false positive. The limitation is shared with the awk's own failure modes and is not "fixed" by resetting quote state per line, because that reintroduces the awk's multi-line defect and loses the :97 find above — the two cannot both be had without a real shell grammar. Everywhere the boundary IS decidable, it is decided in favour of keeping code: an unquoted backslash escape, an arithmetic `<<`, and a heredoc token inside a comment all exist to stop the lexer claiming code as data.

A '#' starts a comment (left untouched to end of line) only at the start of input, at the start of a line, or when the previous byte is a space, tab, newline, or one of the word-breaking shell metacharacters ';', '|', '&', '(', ')', '<', '>' — so ${#var}, $#, and url#fragment are ordinary text, while `cmd;#comment` is recognized. Without the comment rule at all, an apostrophe in a real comment would open a phantom string and swallow the rest of the file. Here-strings (<<<) are not heredocs.

A backslash escapes the next byte both inside double quotes and in UNQUOTED text, which is what shell itself does. The unquoted arm is load-bearing, not symmetry for its own sake: a bash `[[ =~ ]]` character class routinely carries `\"` and `\'` in unquoted text (e.g. `[[ "$1" =~ \.go([[:space:]\"\'\/]|$) ]]`), and honoring the escape only inside quotes let that `\"` open a phantom string that ran to the next quote or to EOF and blanked every comment after it — silent blindness for any rule reading this projection, since a blanked comment produces no finding at all. An escaped NEWLINE is line joining, so a queued heredoc body begins at the next UNESCAPED newline. That is bash: for

cat <<EOF \
body
EOF

bash joins the first two lines into `cat <<EOF body`, hands `body` to cat as a filename argument (`cat: body: No such file or directory`), and takes the `EOF` line as the delimiter of an EMPTY body. So `body` is code and blanking it would hide anything written there.

ANSI-C quoting ($'...') is lexed as its own string form because it does not share plain single-quote semantics: inside $'...' a backslash IS an escape, so $'don\'t' is ONE string. Scanning it with the plain-single-quote arm closed on the escaped quote and left the trailing ' to open a phantom string that ran to EOF — the same blank-to-EOF blindness the unquoted-backslash fix above closed, through a different door.

Heredoc openers (<<WORD, <<-WORD, <<'WORD', <<"WORD", <<\WORD) are recognized; the delimiter word must start with a letter or underscore, and a << in an ARITHMETIC context is a left shift, never an opener. Both conditions are needed: the word-start rule alone covers 1<<20 but not 1<<w, where 'w' is a perfectly good delimiter word. Arithmetic context is tracked for all three of bash's forms — the $(( … )) expansion, the (( … )) COMMAND, and the rest of a `let` simple command — because they evaluate the same grammar and each one on its own is a door: `(( mask = 1 << n ))` and `let mask=1<<n` were both parsed as heredoc openers. Spans are tracked from the opener to their matching )), counting inner parens, so $(( (a+b)<<s )) closes in the right place; an arithmetic span is LEXED, not skipped, and an unbalanced ')' closes it rather than carrying it to EOF. That distinction is what commit 93983d9 ("revert the arithmetic skip; it broke more than it fixed") was about: a skip loses `((echo "a(b") || true)`, where a quoted paren unbalances the count inside nested subshells.

Only a <<- opener strips leading tabs when matching the terminator line; a plain << heredoc's terminator must match the body line exactly. The remainder of an opener line is lexed normally (its quotes are blanked like any other shell text), and multiple openers on one line (the legal `cmd <<A <<B` shape) queue their bodies to be blanked in order at the next newline.

func Names

func Names() []string

Names lists the accepted preprocess values, sorted, for error messages.

func QualifyProtoGoAlias

func QualifyProtoGoAlias(src []byte) []byte

QualifyProtoGoAlias prefixes each top-level `message Name {` with the file's go_package alias (`message domainv1.Name {`). It is line-preserving: same newline count as the input, CRLF kept as CRLF. Files with no `;alias` in go_package are returned unchanged so a missing alias is fail-closed at the rule (A emits a bare name that B will not contain) rather than invented.

Both scans read the same comment mask and every emitted byte comes from the original. Only a message the file actually declares is qualified, and the one it declares is reproduced exactly — its own inline and trailing comments included, which a rewrite that emitted the masked bytes would blank out.

func Register

func Register(name string, t Transform)

Register adds a named transform. Duplicate registration is a programming error.

func StringsOnlyGo

func StringsOnlyGo(src []byte) []byte

StringsOnlyGo keeps only the interiors of Go string literals (interpreted and raw); everything else — code, comments, rune literals, and the quotes themselves — is blanked. Used by rules that match content carried in strings (e.g. SQL).

func StringsOnlySh

func StringsOnlySh(src []byte) []byte

StringsOnlySh keeps ONLY the interiors of shell quoted strings and heredoc bodies; shell text — code, comments, and the quotes and delimiter lines themselves — is blanked. It is the exact complement of DestringSh over the same lexer (scanShData), so what one drops the other keeps, byte for byte. That is the reason the span extractor exists: the pair cannot be written as two independent scanners without eventually disagreeing about where a string ends, and a disagreement is a byte no rule reads at all.

It exists to read EMBEDDED PROGRAM TEXT: the awk programs shell scripts carry as single-quoted arguments or heredoc bodies, and the `bash -c '…'` worker bodies. That text is a program with its own '#' comments, but to the shell lexer it is opaque data, so DestringSh blanks it and every rule reading that projection is blind to it. Without this projection a ban on a token stops at the quote — the same token moved inside an awk program is unreachable by the rule that forbids it.

The two projections are deliberately separate rather than one union: a consumer must not confuse a '#' that opens a SHELL comment with a '#' that opens a comment in some other language that happens to be stored in a shell string. Rules that read this one are stating that they mean the latter.

Types

type Transform

type Transform func([]byte) []byte

Transform rewrites content without changing its line structure (enforced by scan.File.Variant, which errors if the newline count changes).

A Transform MUST NOT WRITE TO ITS ARGUMENT. Copy first — every implementation here opens with `out := append([]byte(nil), src...)` — and return the copy. The input is scan's cached content for that file, shared by every rule in the run, so an in-place edit would corrupt what every other rule sees. It would also silently change strings already returned by scan.File.Lines, which alias that same memory rather than copying it (#66). "Pure" in the package doc means this; it is stated separately because it is the one part a new transform can violate while still passing the line-count check.

func Lookup

func Lookup(name string) (Transform, bool)

Lookup resolves a transform name. The names "raw" and "" mean no transform: callers get (nil, true) and use the original content.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL