rules

package
v0.10.1 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: Apache-2.0 Imports: 6 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 rules defines the checker contract and the registry mapping YAML `type:` strings to implementations (spec §4).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecodeParams

func DecodeParams(n *yaml.Node, out any) error

DecodeParams strictly decodes a params node into out; unknown fields are errors. A nil or zero node leaves out at its zero value.

func IsWholeTreeInvariant

func IsWholeTreeInvariant(c Checker) bool

IsWholeTreeInvariant reports whether c's verdict is a whole-repo invariant that must be evaluated over the whole tree even under a changeset scan. Defaults to false (range-scopeable) for checkers that do not declare it.

func PrefilterImpliedBy

func PrefilterImpliedBy(c Checker) (implied, decidable bool, counterexample string)

PrefilterImpliedBy reports whether c proves its own prefilter redundant. Mirrors PrefilterOf: the single place that knows how to ask. decidable is false for any checker not implementing PrefilterImplication, so a new Prefiltered checker that never opts in degrades to "no static evidence" rather than to a silent pass.

func PrefilterOf

func PrefilterOf(c Checker) (literal string, ok bool)

PrefilterOf reports c's prefilter literal if it carries one. Mirrors CostOf / IsWholeTreeInvariant: the single place that knows a checker gates and on what literal. ok is false (literal "") when c is not Prefiltered or its prefilter is empty.

func ProcessBoundOf

func ProcessBoundOf(c Checker) bool

ProcessBoundOf reports whether c belongs in the width-capped analyzer pool. CostFast is never bound. CostHeavy without the interface is bound.

func Rank added in v0.6.3

func Rank(c Cost) int

Rank orders the cost classes: fast < range < tree < heavy (#22). fast is a per-file scan; range reads only a commit range (seconds; a pre-push hook can afford it); tree reads the working tree once; heavy resolves an AST, replays fixtures or proves mutations. An unknown class ranks as heavy — the fail-closed answer, since a class the engine cannot place must never be run somewhere cheaper than it belongs.

func Register

func Register(name string, f Factory)

Register adds a rule type. Duplicate registration is a programming error.

func SkipReasonOf

func SkipReasonOf(c Checker) (reason string, skipped bool)

SkipReasonOf reports whether c declined to run itself, and why. Mirrors CostOf / PrefilterOf: the single place that knows how to ask. A Checker that does not implement SkipReporter never skips itself as far as callers are concerned, which is the only sound default — nothing else in the package can tell.

Unlike PrefilterOf, an empty reason does NOT downgrade skipped to false: that would turn a checker's under-documented skip into no skip at all, and this interface exists precisely because an unreported skip reads as a pass. Rendering an empty reason is the caller's problem to make loud.

func TypeNames

func TypeNames() []string

TypeNames lists registered types, sorted, for error messages.

func ValidCost

func ValidCost(s string) bool

ValidCost reports whether s names a cost class.

Types

type AnchorProbe

type AnchorProbe struct {
	// contains filtered or unexported fields
}

AnchorProbe is the fail-closed half of a NAME-anchored rule type.

A rule that selects its subject by name — `funcs:` on the Go analyzers, `method:` on dart/method-delegates, a `sequence:` stage — skips whatever the anchor does not match and then reports nothing. That makes an empty anchor set indistinguishable from full compliance: the rule passes its fixture, somebody renames the subject for an unrelated reason, and the invariant is retired with no signal at all. A gate that is green because it can no longer see its own subject is worse than a missing gate, because the dashboard says the invariant is held.

The verdict is deliberately SCOPE-WIDE rather than per-file: a rule scoped to a package where only one file declares the anchored func is compliant, and only a scope in which NO file declares it is a finding. It therefore lands in Finalize, and the owning rule must report itself a WholeTreeInvariant — under --staged the file bearing the anchor may sit outside the changeset, and a per-changeset verdict would read that absence as a rename.

Observe/Hit are called from the engine's per-file worker pool, so both are atomic. Safe for concurrent use; the zero value is ready.

func (*AnchorProbe) Dead

func (a *AnchorProbe) Dead() bool

Dead reports whether the scope was non-empty and the anchor matched nothing.

func (*AnchorProbe) Hit

func (a *AnchorProbe) Hit()

Hit records that the anchor matched.

func (*AnchorProbe) Observe

func (a *AnchorProbe) Observe()

Observe records that a file the anchor could have matched was scanned. A scope that matched zero files leaves the probe unarmed, and that stays correct: an unarmed probe means "nothing to anchor against", which is a fact about the SCOPE rather than about this anchor, and every rule type would have to re-derive it. It is reported once, by identity, one level up — `check`'s scan summary discloses such rules on a whole-tree run (naming the first ten and counting the rest in its line formats, all of them under -format json), and `formwork lint`'s empty-scope fails them (spec §11).

func (*AnchorProbe) Verdict

func (a *AnchorProbe) Verdict(what, pattern string) []Match

Verdict returns the missing-anchor finding, or nil when the anchor is live. what names the param the anchor came from (e.g. "funcs anchor") so the cure points at the field to update.

type Checker

type Checker interface {
	CheckFile(f *scan.File) ([]Match, error)
}

Checker evaluates one rule. CheckFile must be safe for concurrent use: the engine calls it from a worker pool.

type Cost

type Cost string

Cost classifies a rule type's evaluation cost (spec §8). Fast rules are cheap per-file scans safe to run on every commit; heavy rules shell out to external tools or git and belong to heavier lanes. A Checker that does not implement Coster is CostFast.

const (
	CostFast  Cost = "fast"
	CostRange Cost = "range"
	CostTree  Cost = "tree"
	CostHeavy Cost = "heavy"
)

func CostOf

func CostOf(c Checker) Cost

CostOf returns c's declared cost, defaulting to CostFast.

type Coster

type Coster interface {
	Cost() Cost
}

Coster is optionally implemented by a Checker to declare its cost class.

type ErrFinalizer

type ErrFinalizer interface {
	FinalizeErr(FinalizeContext) ([]Match, error)
}

ErrFinalizer is a Finalizer that may fail and needs run context. Rule types that execute external tools (`command`, `git-diff`) report an execution failure — a missing binary, a git error — as an engine error (exit 2), never as a silent pass (spec §11). The engine prefers ErrFinalizer over Finalizer when a checker implements both.

type Factory

type Factory func(params *yaml.Node) (Checker, error)

Factory builds a Checker from a rule's params node (may be nil).

func Lookup

func Lookup(name string) (Factory, bool)

Lookup resolves a rule type name.

type FinalizeContext

type FinalizeContext struct {
	// Root is the tree UNDER EVALUATION: the repository under `check`, a
	// fixture tree under `test`, a scratch under a downstream mutation run.
	// It is what {{root}} resolves to.
	Root string
	// Repo is the corpus's own tree — where .formwork lives. Under `check`
	// the two are the same directory; under `test` Root is the fixture and
	// Repo is the repository, which is how a detector that lives in the
	// repository stays reachable while judging a fixture (#28). Empty means
	// "same as Root", so a caller that predates the field is unchanged.
	Repo string
	// Fixture is true when the tree under evaluation is a FIXTURE rather than
	// the live repository. Some planes exist only in the live tree and a
	// fixture cannot fake them. A commit-range scan is the case: an isolated
	// fixture IS a real repository, so "is this a git checkout" answers yes,
	// but it has no upstream branch for a default range to resolve against —
	// and a detector that cannot tell the planes apart either dies on the
	// missing ref or skips its range in CI as well, which is a gate that
	// fails open. It reaches the tool as FORMWORK_FIXTURE=1 (#28).
	Fixture bool
}

FinalizeContext carries run-scoped facts a whole-run rule needs but the per-file Checker path does not — chiefly the repository root external-tool rules (`command`, `git-diff`) must run in.

type Finalizer

type Finalizer interface {
	Finalize() []Match
}

Finalizer is implemented by checkers that need a pass after every in-scope file has been seen (e.g. required-pattern in exists mode).

type Match

type Match struct {
	Path    string
	Line    int
	Message string
}

Match is one raw hit from a checker. Path is optional: when empty, the engine substitutes the path of the file being checked; finalizers may set it (or leave it empty for scope-level findings).

type PrefilterImplication

type PrefilterImplication interface {
	PrefilterImplied() (implied, decidable bool, counterexample string)
}

PrefilterImplication is optionally implemented by a Prefiltered checker that can decide, from its own compiled pattern alone, whether a match is possible without the prefilter literal. A prefilter is a pure optimization exactly when it is implied — no data required to know it.

This is what lets lint judge a prefilter on a rule with zero findings and no fixtures, where both differentials are silent (#133).

The contract is deliberately three-valued, not two. decidable=false means "this checker cannot tell" — a regexp2 pattern it does not parse, a case-folded literal, a branch with no guaranteed literal — and is NEVER on its own a finding. Only implied=false with decidable=true is a defect, and it must come with a counterexample naming the branch that can match without the literal. A purely lexical version of this test was considered and rejected in the 2026-07-27 design as noisy and wrong on escaping; an implementation earns the right to report by parsing, and by staying silent whenever it is unsure.

type Prefiltered

type Prefiltered interface {
	Prefilter() string
	WithoutPrefilter() Checker
}

Prefiltered is optionally implemented by a checker carrying a literal prefilter gate (spec §5): a cheap substring test that skips a file before the real matcher runs. WithoutPrefilter returns an equivalent checker with the gate removed, for lint's load-bearing-prefilter differential (spec §9). It is for STATELESS per-file checkers only — WithoutPrefilter may share state via a shallow copy, so a stateful checker must instead rebuild via its factory.

type ProcessBound

type ProcessBound interface {
	ProcessBound() bool
}

ProcessBound is optionally implemented by a CostHeavy checker whose subprocess footprint is per-process RAM (Dart/Flutter analyzers). The engine caps those at heavyFinalizerWorkers. A CostHeavy checker that does not implement ProcessBound defaults to bound — the conservative #67 default so an unknown heavy type cannot fork unbounded analyzers.

command implements it, and OPTS OUT of the conservative default above for the one rule type that can spawn an arbitrary program: it binds only what it can recognise as an analyzer (#81). A wrapper naming no analyzer is still unbound — see ProcessBound's comment and #236.

git-diff implements it as not bound (git is not multi-GB).

type SkipReporter

type SkipReporter interface {
	SkipReason() (reason string, skipped bool)
}

SkipReporter is optionally implemented by a Checker that can DECLINE TO RUN ITSELF — a gate of its own, expressed in its params rather than in the rule's scope, that the engine and the scope predicate know nothing about. `command`'s `when.paths_changed` is the gate it was written for.

The contract is "did you skip, and why": reason must be a complete, operator- readable sentence naming the gate and the fact that the work did not happen, because it is rendered verbatim beside the rule id and is the entire cure surface of the disclosure. skipped must be reported only after the checker has actually declined — a checker that has not reached its decision must answer false, so the disclosure describes the run rather than predicting it.

It exists because such a skip is indistinguishable, in every renderer, from a rule that ran and passed: `[id] OK`, exit 0, tool never executed (#159). The skip stays correct; only its silence is the defect.

ORDERING IS A CALLER OBLIGATION, and this is where it differs from Coster and Prefiltered: those answer from static config and are pure, so the moment you ask is irrelevant. SkipReasonOf reads MUTABLE RUN STATE. Asked before the engine has run the checker, it answers "no skip" — indistinguishable from a rule that ran — so a caller must ask after the run whose skips it is reporting, and the requirement that a checker answer false until it has declined is what makes the early answer merely empty rather than wrong.

type WholeTreeInvariant

type WholeTreeInvariant interface {
	WholeTreeInvariant() bool
}

WholeTreeInvariant is optionally implemented by a Checker whose verdict is a whole-repo invariant: it depends on the ABSENCE of a pattern anywhere in scope (required-pattern in exists mode), a cross-file join (set-relation), a scope-wide count (pattern-count), or a tracked-set comparison (baseline). Such a rule is NON-MONOTONIC under file removal — restricting the input to a changeset can flip a true pass into a false "not found" / "subset violated" / "count off" finding merely because the file bearing the token is not in the change range. The CLI therefore evaluates these rules over the WHOLE tree even under --staged/--range, while range-scoping the per-file (monotonic) rules for speed. A Checker that does not implement this — forbidden-pattern, required-pattern in every-file mode, and every per-file scanner — is range-scopeable: removing files can only remove its findings, never add one.

Directories

Path Synopsis
Package baseline implements the `baseline` rule type (spec §5): it extracts a set of values from the in-scope files and compares that set to a tracked baseline file.
Package baseline implements the `baseline` rule type (spec §5): it extracts a set of values from the in-scope files and compares that set to a tracked baseline file.
Package binarycontent implements the `binary-content` rule type (spec §5): a per-file guard against oversized or binary blobs in tracked files.
Package binarycontent implements the `binary-content` rule type (spec §5): a per-file guard against oversized or binary blobs in tracked files.
Package command implements the `command` rule type (spec §5): the interim escape hatch for toolchain gates that cannot be expressed declaratively.
Package command implements the `command` rule type (spec §5): the interim escape hatch for toolchain gates that cannot be expressed declaratively.
Package dartscan implements heuristic analyzers for Dart source.
Package dartscan implements heuristic analyzers for Dart source.
Package docpathexists implements the `doc-path-exists` rule type (spec §5): repo-relative paths cited in docs and comments must exist on disk.
Package docpathexists implements the `doc-path-exists` rule type (spec §5): repo-relative paths cited in docs and comments must exist on disk.
Package filenaming implements the `file-naming` rule type (spec §5): naming constraints over in-scope file paths (never their content).
Package filenaming implements the `file-naming` rule type (spec §5): naming constraints over in-scope file paths (never their content).
Package filesize implements the `file-size` rule type: per-file line-count caps.
Package filesize implements the `file-size` rule type: per-file line-count caps.
Package gitdiff implements the `git-diff` rule type (spec §5): assertions over the added/removed lines of a git range — "no new X", "don't delete Y".
Package gitdiff implements the `git-diff` rule type (spec §5): assertions over the added/removed lines of a git range — "no new X", "don't delete Y".
Package goast implements the built-in Go-AST analyzer rule types (spec §4, phase 4).
Package goast implements the built-in Go-AST analyzer rule types (spec §4, phase 4).
Package ordering implements the `ordering` rule type (spec §5): within each file, a `before` pattern must precede an `after` pattern.
Package ordering implements the `ordering` rule type (spec §5): within each file, a `before` pattern must precede an `after` pattern.
Package pairconsistency implements the `pair-consistency` rule type (spec §5): a `trigger` match obliges a `requires` match within the same UNIT.
Package pairconsistency implements the `pair-consistency` rule type (spec §5): a `trigger` match obliges a `requires` match within the same UNIT.
Package pattern implements the line-oriented pattern rule types (spec §5: forbidden-pattern, required-pattern).
Package pattern implements the line-oriented pattern rule types (spec §5: forbidden-pattern, required-pattern).
Package patterncount implements the `pattern-count` rule type (spec §5): a whole-scope assertion on how many lines match a regex across the in-scope file set.
Package patterncount implements the `pattern-count` rule type (spec §5): a whole-scope assertion on how many lines match a regex across the in-scope file set.
Package setrelation implements the `set-relation` rule type (spec §5): a cross-file join that extracts a string set from each of two file groups and asserts a relation (subset, equal, disjoint) between them.
Package setrelation implements the `set-relation` rule type (spec §5): a cross-file join that extracts a string set from each of two file groups and asserts a relation (subset, equal, disjoint) between them.
Package sqlparse implements the parse-tree-backed SQL rule types (sql/parses, sql/locking-select-order).
Package sqlparse implements the parse-tree-backed SQL rule types (sql/parses, sql/locking-select-order).
Package sqltext implements the `sql/statement-predicate` rule type: a predicate over individual SQL statements, sourced both from `.sql` files (used verbatim) and from SQL embedded in Go string literals (`.go` files, reassembled heuristically — see sqlextract).
Package sqltext implements the `sql/statement-predicate` rule type: a predicate over individual SQL statements, sourced both from `.sql` files (used verbatim) and from SQL embedded in Go string literals (`.go` files, reassembled heuristically — see sqlextract).

Jump to

Keyboard shortcuts

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