Compilation orchestration
Compilation orchestration turns parsed CSS selector alternatives into one executable predicate. It orders checks for useful short-circuiting, adds the right scope for relative and nested selectors, and joins all matching alternatives into the result used by the query APIs. See Selector compilation pipeline for the wider compilation flow and Predicate composition helpers for the related predicate-building rules.
Token processing
The compiler receives a selector as alternatives made of ordered token groups. An alternative describes one possible match path. A token group describes the checks and traversals that must hold together. The compiler processes each alternative and preserves the distinction between “all rules in this alternative” and “any alternative in the selector.” src/types.ts• L3-11 and src/types.ts• L185-205 define these internal and executable shapes.
Selector alternatives
Each alternative becomes a predicate chain. The chain starts with the terminal condition supplied by the compilation options. Each new rule adds one more condition around that chain. This lets a selector express a path from the candidate element through its attributes, pseudos, and related nodes without turning each alternative into a separate query.
The compiler combines alternative chains with OR behavior. A candidate therefore matches when at least one parsed alternative succeeds. An alternative that can never match is discarded. An alternative that is always true can end compilation early because it already accepts every candidate allowed by the terminal condition.
References: src/compile.ts• L69-81 src/compile.ts• L119-150 src/types.ts• L185-205
Rule ordering
Rules inside one token group are reordered before compilation. The order favors checks that are cheap or selective before checks that can inspect large subtrees or nested selectors. This changes evaluation order for speed but does not change the selector’s meaning because all rules in the group must still pass.
Traversal tokens keep their role as links between related elements. Expensive checks such as content and nested-subselector tests are delayed when possible. The resulting predicate can reject a candidate before it performs the more costly work. src/…/selectors.ts• L20-45 and src/…/selectors.ts• L78-123 define this ordering model.
References: src/compile.ts• L73-76 src/compile.ts• L119-140 src/…/selectors.ts• L20-45 src/…/selectors.ts• L78-123
Traversal ordering
Compilation builds predicates around a candidate in token order so that the final candidate is checked first and related elements are reached through the surrounding traversal rules. A descendant, parent, child, sibling, or adjacent relationship then determines which other elements must satisfy the rest of the chain. The general selector layer supplies these traversal meanings while orchestration decides when each rule enters the chain.
Traversal direction
The compiler applies each rule to the predicate already built for the remaining path. At evaluation time, this makes a compound selector check the candidate’s direct properties before it follows the required relationship. For example, a child relationship moves from the candidate to its parent, while a sibling relationship inspects the earlier element siblings.
This direction matters for nested selectors and for short-circuiting. A traversal only continues when the predicate on the related element succeeds. The compiled query can also record that later siblings must be included in the search context when an alternative depends on adjacent or general sibling matching.
References: src/compile.ts• L97-117 src/compile.ts• L122-152 src/general.ts• L84-203 src/types.ts• L185-190
Sibling search scope
Sibling-dependent selectors affect both compilation and candidate preparation. During compilation, the predicate records whether the query needs following siblings. The query boundary uses that signal to add those siblings before traversal begins, while preserving the expected order of the original candidates and their siblings.
This is a contract between the compiled predicate and query execution. If the signal is lost, a valid sibling selector can compile correctly but never see all of its possible candidates. src/index.ts• L82-149 connects the signal to context preparation.
References: src/compile.ts• L97-117 src/compile.ts• L152-154 src/index.ts• L104-109 src/index.ts• L119-149
Context-sensitive compilation
Context-sensitive compilation gives a selector a defined boundary for :scope and relative selectors. The compiler normalizes a relative path with a scope anchor when needed. Nested selectors receive a separate option view so that a child selector does not inherit the parent’s context or terminal predicate by accident.
Relative selector scope
When relative selectors are enabled, a selector that starts with a traversal is made absolute against the supplied context. A relative selector without an explicit scope acts as a scoped descendant query. The compiler uses a special flexible descendant step for array contexts so that the scope can match the queried candidates and their relevant descendants.
When relative selectors are disabled, a selector that starts with a traversal is rejected instead of being silently reinterpreted. A missing context gives :scope root-like behavior. These rules keep the same compiled predicate contract for direct queries and nested relative queries.
References: src/compile.ts• L19-61 src/compile.ts• L83-95 src/…/filters.ts• L144-163 src/types.ts• L147-164
Nested selector context
Nested selector pseudos compile their own token groups through the same orchestration path. The nested compilation receives copied options with the parent context and terminal function removed. This isolates the nested selector’s matching boundary while still allowing the parent predicate to require or reject its result.
:has adds a special case for relative paths. It compiles the nested path with a placeholder scope and replaces that placeholder with the candidate element during evaluation. Context-dependent nested paths avoid result reuse when their answer can change with the current candidate.
References: src/…/options.ts• L3-15 src/…/subselects.ts• L36-70 src/…/subselects.ts• L72-139 src/compile.ts• L69-73
Compiled predicate output
The compilation result is a callable predicate that reports whether one element satisfies the complete selector. The public safe entry point adds an element check before this predicate runs. The query operations then use the same result for all-candidate selection, first-match selection, and direct matching.
Terminal predicate
The terminal predicate is the final condition in each chain. It normally accepts the element, but callers can provide a root function to add an outer condition. Every compiled selector rule must preserve that condition when it wraps the chain. This allows orchestration to add selector semantics without losing caller-defined filtering.
The compiler uses shared always-true and always-false predicates for early results. These values let compilation stop or discard work without creating another wrapper. They also give the public boundary a stable result for selectors that cannot match.
References: src/compile.ts• L78-81 src/compile.ts• L119-150 src/index.ts• L42-79 src/types.ts• L137-142
Final query contract
The final predicate represents all selector alternatives and carries one piece of traversal metadata: whether the query must test following siblings. Query execution reads that metadata before it enumerates candidates. It then evaluates the predicate through depth-first traversal for all-match queries or stops at the first success for first-match queries.
This output is the handoff from compilation to execution. The compiler decides what a candidate means. The query layer decides which candidates to present to it and how to return the matches.
References: src/compile.ts• L149-154 src/types.ts• L185-190 src/index.ts• L82-109 src/…/querying.ts• L11-59 src/…/querying.ts• L70-118
Change checklist
When these files or sections are changed, remember to consider these:
- Keep
shouldTestNextSiblingsaligned with candidate preparation inprepareContext; a change in either side can hide valid sibling matches. - Preserve the
:scopeand relative-selector rules shared byabsolutize, the scope filter, and nested:hascompilation. - Keep copied nested options free of the parent
contextandrootFunc; leaking either value changes the meaning of:is,:not,:has, or filtered:nth-*selectors. - Keep the always-true and always-false predicate shortcuts compatible with every caller of
compileToken.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
Relative selector starts with a traversal while relativeSelector is disabled | Compilation throws instead of producing a predicate | Validate the option before compiling traversal-led alternatives |
| Sibling metadata is not propagated to query preparation | Sibling selectors may miss following siblings | Preserve shouldTestNextSiblings through compilation and prepareContext |
| Parent context leaks into nested compilation | Nested pseudos match against the wrong scope or terminal condition | Use isolated options for nested selector compilation |
A context-dependent :has result is cached as if it were context-free | One candidate’s result can be reused for another candidate | Skip parent-result caching for traversal- or scope-dependent subselectors |
| A selector group compiles to the always-false predicate | The alternative is skipped; if all alternatives fail, the query returns no matches | Keep false-result checks in the alternative loop |
Key files
| File | Why to read it |
|---|---|
| src/compile.ts | Main orchestration flow for token ordering, relative-selector normalization, context handling, and alternative combination. |
| src/…/selectors.ts | Quality ranking, traversal recognition, and scope detection used to choose evaluation order. |
| src/general.ts | The rule wrappers that give each compiled token its element and traversal behavior. |
| src/…/subselects.ts | Nested selector compilation and candidate-sensitive :has handling. |
| src/index.ts | Boundary between compiled predicates and candidate preparation for public query operations. |
| src/types.ts | Definitions of internal selector tokens, compiled queries, options, and the compiler contract. |