Whitespace Rules
Rules governing spaces, line breaks, and blank lines work fundamentally differently from all other rules: they never modify source code directly. Instead, they declare what should exist in the space between two adjacent tokens, leaving conflict resolution and formatting to the engine.
What a Gap Is
In DressCode, a gap refers to everything in source code that sits between two adjacent tokens: whether that space is
completely empty, contains one or more spaces, or spans line breaks, blank lines, and comments. In the API, this space is
represented by the Gap class.
$sum = $a + $b;
This short line contains exactly five gaps: between $sum and =, between = and
$a, between $a and +, between + and $b, and finally between
$b and ;. That final gap is just as real as the others, even though it currently holds nothing, and a
rule can say something about it just the same: that it must remain empty.
A whitespace rule (derived from DressCode\GapRule) states what such a gap should look like. It never writes into
the gap, deletes anything from it, or searches it.
Why Rules Don't Rewrite Whitespace
If a rule enforcing spaces after commas inserted spaces directly into the syntax tree, and a rule wrapping long lists inserted newlines, both rules would collide at the exact same location. Whichever ran last would win, and a subsequent pass might flip the result back.
That is why whitespace rules never touch the code directly. Each rule merely submits a declarative claim (the
Claim class in the API) describing how a specific gap should appear. The engine evaluates all submitted claims
simultaneously, settles conflicts centrally, formats the whitespace, and attributes any reported violation to the decision whose
claim won.
For the author of a rule, this means it never has to fight other rules over a gap: claims from both sides of a gap are combined by a fixed precedence, and two claims contradicting each other on the same side of the same slot are an error the tool catches right away (see Who Wins).
What a GapRule cannot do by design is mutate tokens: it consists entirely of claims and does nothing else. When a
construct requires both whitespace claims and token transformations, implement them as two collaborating rules (each with its own
decision): one GapRule and one NodeRule. Attributes
are a prime example: spacing.attribute claims whitespace inside #[...], while
classes.emptyParentheses.attribute adds or removes empty parentheses following attribute names. This separation
ensures projects can disable one behavior via keep while leaving the other fully active.
Where a Claim Applies
A whitespace rule extends GapRule, carries the #[RuleInfo] attribute like any other rule, and in
getClaims() declares which slots (named places of a node, such as condition of an if, see
the glossary) across which nodes it claims,
specifying claims independently for the gap before and after the slot value:
#[RuleInfo(Stage::Formatting)]
final class ReturnBlankLinesRule extends GapRule
{
private Claim $claim;
public static function getDecisions(): array
{
return [
new Decision('acme.blankLinesBeforeReturn', Domain::blankLines(), 'Blank lines before a `return` that is not the first statement of its block'),
];
}
public function configure(Values $values): void
{
$this->claim = Claim::blankLines($values->get('acme.blankLinesBeforeReturn')->getCountRange());
}
public function getClaims(): array
{
return [
'*' => [
'statements:item' => [
fn(Gap $gap) => $gap->value instanceof ReturnNode && $gap->index > 0 ? $this->claim : null,
null,
],
],
];
}
}
The example above states: before every return statement in a statements list that is not the first statement in
its block, there must be as many blank lines as specified by acme.blankLinesBeforeReturn. The rule builds its claim
instance once in configure() from the configured value and returns it from the closure (an anonymous function)
without reallocating it per gap.
The rule never visits nodes directly because GapRule has no traversal methods; the engine handles all whitespace
formatting from claims during the Formatting stage. This is why the RuleInfo attribute for a whitespace
rule must specify Stage::Formatting exclusively (any other stage is rejected as an error).
Rule authors never write messages. Given the value 1, the generated report reads
Expected 1 blank line before the return, 0 found. The engine composes this sentence from the context and appends the
path acme.blankLinesBeforeReturn in the output. Messages like
Expected a single space before the `=` operator. or Expected a line break before the opening brace. are
assembled the same way.
The array that getClaims() returns reads as follows:
- the first-level key is a node class, or the wildcard
*to match any node containing that slot; - the second-level key is the slot name (
'body'), orslot:itemfor every element of a list ('statements:item','items:item'), orslot:separatorfor list delimiters ('items:separator'); under*,'*:item'matches elements and'*:separator'matches delimiters across every list in the code, which is howspacing.commaclaims whitespace around all commas; - the value is a two-element array
[before, after], where each element is a staticClaim,null(if unconstrained), or a closure accepting aGapand returning a claim ornull. A claim on a slot containing a node applies to the gap before its first token (before) or after its final token (after).
Slot names are strings, meaning an IDE refactoring won't automatically rename them if an internal property
changes. However, typos are caught immediately: a claim referencing an invalid slot (like 'statemnts:item') triggers
a ConfigurationException when rules are assembled
(Rule `Acme\CodeStyle\ReturnBlankLinesRule` claims the whitespace of `*.statemnts:item`, but no node has a slot `statemnts`.).
See the node reference for all slot names.
The closure receives a Gap object providing the boundary token, the slot value or list item, its index in the
list, and the file's style configuration (including line length limits). Closures can evaluate conditions dynamically, for
example, treating concatenation dots differently from other binary operators:
public function getClaims(): array
{
$operator = fn(Gap $gap): ?Claim => $gap->token->text === '.' ? null : $this->claim;
return [
BinaryOpNode::class => ['operator' => [$operator, $operator]],
AssignmentNode::class => ['equals' => [$this->claim, $this->claim]],
];
}
Closures can also query file analyses via findAnalysis(), just like RuleContext::findAnalysis().
Rules with a single requirement report under it automatically. Rules governing multiple requirements associate each claim with
its decision: new Claim(Space::Single, decision: 'acme.operatorSpacing'), or for an existing instance via
$claim->withDecision('acme.operatorSpacing'). Blank lines below comments can belong to a distinct decision passed
via decisionBelowComment.
What a Claim Says
A Claim consists of four independent components, and a rule specifies only those it cares about in a given
context:
| part | what it says | values |
|---|---|---|
space |
Horizontal spacing when both tokens share the same line | Space::None, Single, AtLeastOne, and variants SingleOrTabs and
AtLeastOneOrTabs that tolerate column-aligning tabs |
line |
Whether the second token sits on the same line as the first, or breaks to the next line | Line::Same, Line::Next |
blankLines |
The number of blank lines when a line break is present | An integer, or a range [min, max] (null indicates an open-ended range) |
blankLinesBelowComment |
Blank lines between a comment in the gap and the subsequent token | An integer or range matching blankLines |
The most common claims have dedicated factory methods: Claim::noSpace(), singleSpace(),
singleSpaceOrTabs(), atLeastOneSpace(), atLeastOneSpaceOrTabs(), sameLine(),
nextLine(), and blankLines(), which accepts both fixed integers (blankLines(1)) and ranges
(blankLines([1, 2])). Compound claims spanning multiple properties or claims with textual reasons are created via the
constructor: new Claim(Space::None, line: Line::Same) or
new Claim(line: Line::Next, because: 'the line is 135 characters long'). The engine automatically appends the reason
to the report message after a comma.
Blank lines are measured above comments that occupy their own lines preceding a token, because comments logically belong
to the code that follows them. The sole exception is a comment immediately preceding a closing brace or EOF: such comments bind to
the code above. Blank lines between the final comment and the token are governed by blankLinesBelowComment, which is
used, for example, by rules enforcing spacing between docblocks and declarations.
A Decision That Must Be the Same Every Time
Claims that depend on the overall layout of code (such as whether an argument list is multiline, or whether a line exceeds length limits) must return the identical answer for every gap across that construct, regardless of how the engine modified earlier gaps in the meantime. Otherwise, the first comma might wrap the list and the second comma would immediately collapse it back onto one line. Such evaluations are therefore computed once per construct:
public function getClaims(): array
{
return [
ArgumentListNode::class => [
'items:item' => [
function (Gap $gap): ?Claim {
$list = $gap->value->parent->parent; // the ArgumentListNode
return $gap->once($list, fn() => $this->isBroken($list)) ? Claim::nextLine() : null;
},
null,
],
],
];
}
The once() method evaluates the supplied closure at the first gap of the specified node and caches the answer,
returning that identical value for all other gaps in that node until the pass concludes. You write the helper
isBroken() yourself: treat a list as multiline as soon as any element or the closing parenthesis begins on a new
line, ensuring the decision to wrap applies consistently across the rest of the list. Given foo($a, $b, with
$c) on the next line, the rule breaks every argument onto its own line and reports a single combined violation:
Expected a line break before the argument., while leaving single-line calls like bar($a, $b)
untouched.
A decision recorded via once() that returns an active result (not null, false, or an
empty array) is reported as a single violation for the entire construct, rather than generating separate findings for every gap:
the defect is the shape of the construct, not each individual break. A multiline condition spanning five lines produces one
finding positioned at the first problem, meaning a single inline dresscode:ignore comment can suppress it and the
baseline records it under a single fingerprint. The fixes are the same as if every gap were reported separately.
Who Wins
The engine merges claims from both sides of a gap component by component, using strict precedence rules rather than configuration file ordering:
- a claim targeting a specific node class takes precedence over a wildcard
*claim, - a claim on an inner child slot takes precedence over an ancestor slot claim,
- for horizontal spacing, the stricter requirement wins over the looser one: for
return;,Expected no whitespacewins overExpected at least one space, - for line breaks,
Line::Nextalways takes precedence overLine::Same, - for blank line counts, the intersection of both allowed ranges applies; if the ranges are mutually exclusive, the narrower range wins.
Two static claims on the same component of the same side of a slot trigger a ConfigurationException at startup.
Two closures may share a slot because each can return null where the other decides. If both closures return claims
for the same component at a specific gap, the engine throws a ConfigurationException at runtime at that exact gap
(Rules `Acme\CodeStyle\ARule` and `Acme\CodeStyle\BRule` both govern the whitespace before `PhpSyntax\Nodes\Expression\BinaryOpNode.operator`.).
Built-in rules are designed never to conflict; if a plugin rule needs to handle a gap differently from the engine, the project
must set the engine decision for that gap to keep.
Required line breaks are inserted immediately, with exact blank line counts adjusted in the subsequent pass. Forbidden line breaks, by contrast, are removed only when the gap contains pure whitespace and no comments. The indentation of newly wrapped lines is not governed by claims: the engine assigns them default indentation, and the indentation rule places them at their exact level during final cleanup.
Testing a Whitespace Rule
Whitespace rules are tested like any other rule using RuleTester against fixtures; verified reports in .violations are those composed
automatically by the engine.