preprocessor.py¶
clew/preprocessor.py
The PREPROCESSOR CONFIGURATION a build indexes — declared, never guessed.
_stated_only
tuple[str, ...] clew.preprocessor._stated_only(tuple[str,...] declared, tuple[str,...] harvested)
The declared macro NAMES the repository's own config header does not define.
Source · 19 lines
def _stated_only(declared: tuple[str, ...], harvested: tuple[str, ...]) -> tuple[str, ...]:
"""COMPARED BY BARE NAME, never by token. Both sides are rendered doxygen PREDEFINED tokens —
`'"NAME"'` or `'"NAME=value"'` — so a token comparison would call `"X"` and `"X=1"` different
macros and report a symbol as operator-only when the header defines it with a value. That is
the exact drift `defined_names` was consolidated to prevent, and this is a third caller.
EMPTY WHEN NO HEADER WAS READ, which is correct and not a degenerate case: with nothing
harvested there is no statement about the repository's own defaults to make, so claiming every
declared macro ships OFF would be inventing a fact. Absence stays absence.
@brief Names stated by the operator and absent from the repo's config header.
@return Sorted bare names.
@version 1
"""
if not harvested:
return ()
return tuple(sorted(bare_macro_names(declared) - bare_macro_names(harvested)))
Activity · 3 steps
Requirements
as_meta
dict[str, str] clew.preprocessor.PreprocessorConfig.as_meta(self)
Flatten to string values for build_meta persistence.
Source · 35 lines
def as_meta(self) -> dict[str, str]:
"""gh#17 part 3, and the part that stands on its own. An index of a
multi-variant codebase is an index of one variant; before this, nothing in the
database said which, so two indexes of one repo could disagree about whether a
function EXISTS with no field to explain it.
Empty strings are returned rather than omitted keys because
`write_build_signature` drops falsy values — so a build that declared nothing
writes no `preprocessor.*` rows at all, and an absent key honestly reads as "not
recorded". `macro_count` is the deliberate exception: it is `"0"` when a
configuration was declared and produced nothing, and `"0"` is truthy where `0`
is not. That is the measured-zero rule `coverage.as_meta` documents.
The macro list is written IN FULL, untruncated. It is the answer to "which
variant is this", and a truncated answer to that is not one.
@brief Preprocessor configuration as build_meta values.
@return Unprefixed key -> string value.
@version 2
"""
if not self.declared:
return {}
return {
"source": self.source,
"config_header": self.config_header or "",
"macro_count": str(len(self.macros)),
"predefined": " ".join(self.macros),
"searched": ", ".join(self.searched),
## Written even when empty is NOT possible here — `write_build_signature` drops falsy
## values — so an absent key honestly reads as "this build made no statement about the
## repository's own defaults", which is the case when no config header was read.
"stated_only": ", ".join(self.stated_only),
}
Activity · 3 steps
Requirements
bare_macro_names
frozenset[str] clew.preprocessor.bare_macro_names(Iterable[str] tokens)
The bare NAMES of a set of rendered doxygen PREDEFINED tokens.
Source · 27 lines
def bare_macro_names(tokens: Iterable[str]) -> frozenset[str]:
"""ONE SPELLING FOR TWO STRING OPERATIONS, extracted because the second caller drifted on
exactly one of them. `macros` holds already-rendered doxygen PREDEFINED tokens — the quoting
is there because rendering the Doxyfile is what they were built for — so answering "is X
defined" needs BOTH the quotes and any `=value` removed.
`kconfig_gates` had its own version that removed the value and left the quotes, so
`'"MBEDTLS_THREADING_C"' != 'MBEDTLS_THREADING_C'` and every declared macro was labelled
`undeclared`: the `origin` field reported an entire configuration as absent from the build
that declared it. Found by a control asking one build to distinguish a satisfied gate from an
unsatisfied one; invisible to that function's own test, which fed it unquoted input.
An empty result for an empty input is correct and not a fallback — a build that declares
nothing defines nothing.
@brief Reduce rendered PREDEFINED tokens to their names.
@return Frozen set of names.
@version 1
"""
names = set()
for token in tokens:
bare = token.strip('"').split("=", 1)[0].strip()
if bare:
names.add(bare)
return frozenset(names)
Activity · 6 steps
Requirements
declared
bool clew.preprocessor.PreprocessorConfig.declared(self)
Whether the target stated a preprocessor configuration at all.
Source · 12 lines
def declared(self) -> bool:
"""NOT `bool(self.macros)`. A declared config header that yielded zero macros is
a DECLARATION that produced nothing — which is what a misspelled path or an
unbuilt `autoconf.h` looks like — and it must be recorded, not read as "the owner
said nothing".
@brief Did the target state a configuration?
@return True when source is anything but none.
@version 1
"""
return self.source != SOURCE_NONE
Activity · 1 steps
Requirements
defined_names
frozenset[str] clew.preprocessor.PreprocessorConfig.defined_names(self)
The bare macro NAMES this configuration defines.
Source · 26 lines
def defined_names(self) -> frozenset[str]:
"""`macros` holds already-rendered doxygen PREDEFINED tokens — `'"NAME"'` or
`'"NAME=value"'`, double quotes included — because rendering the Doxyfile is what
it was built for. Asking "is X defined" of that shape needs the quoting and the
value stripped, and doing it HERE keeps every caller from respelling the same two
string operations and drifting on one of them.
A macro defined to `0` still counts as DEFINED, because that is what `defined(X)`
means to the preprocessor. Evaluating `#if X` as arithmetic is a different question
this type deliberately does not answer — see `evaluate_guard`, which reports
UNKNOWN rather than guessing.
THE OPERATION MOVED TO `bare_macro_names` AND THE WARNING ABOVE IS WHY. A second caller
did respell it and did drift on one of the two: `kconfig_gates.declared_macro_names`
stripped `=value` and NOT the quoting, so every macro a build actually declared was
labelled `undeclared` in `kconfig_gates.origin` — a whole configuration reported absent,
confidently. It survived because its own test fed it UNQUOTED input, which is the
recorded shape "the fixture matched the detector rather than the world". Both callers now
share one function, so a fix reaches both.
@brief Bare names of the defined macros.
@return Frozen set of macro names.
@version 2
"""
return bare_macro_names(self.macros)
Activity · 1 steps
Requirements
doxyfile_lines
str clew.preprocessor.doxyfile_lines(PreprocessorConfig config)
The Doxyfile lines that supply a resolved configuration to doxygen.
Called by _doxygen_stage
Tested by
Calls none
Source · 26 lines
def doxyfile_lines(config: PreprocessorConfig) -> str:
"""`PREDEFINED +=`, NEVER `PREDEFINED =`, and that is a correctness requirement
rather than a style choice. Doxygen takes the last assignment to a key, so `=` here
would silently DISCARD the `PREDEFINED` list a target's own Doxyfile declares —
turning a feature that widens an index into one that narrows it for exactly the repos
already doing the right thing. Appending means a declaration ADDS to the repo's own
statement, and every existing target keeps building identically.
`ENABLE_PREPROCESSING = YES` rides along because `PREDEFINED` has no effect without
it. It is doxygen's default, so this is a no-op almost everywhere — but a repo that
turned it off would otherwise get a declaration silently ignored, which is the
reported-success-with-defaults failure the no-hardcoding mandate is about.
`MACRO_EXPANSION` is deliberately NOT forced: it changes how bodies are parsed
everywhere, not just which branches are taken, and gh#17 asks for the configuration
to be supplied, not for the parse to be altered.
One line per macro, so a diff of the hashed content names the macro that changed.
@brief Render a resolved configuration as Doxyfile text.
@return Text to append to the Doxyfile, or "" when there is nothing to supply.
@version 1
"""
if not config.macros:
return ""
lines = "".join(f"PREDEFINED += {token}\n" for token in config.macros)
return f"\nENABLE_PREPROCESSING = YES\n{lines}"1 more lines, not shown
Activity · 4 steps
Requirements
evaluate_condition
bool | None clew.preprocessor.evaluate_condition(str text, frozenset[str] defined)
Evaluate a preprocessor #if condition against a declared configuration.
Called by _atom, _guard_holds
Tested by
Calls _atom, _combine, _split_top, _unwrap
Source · 28 lines
def evaluate_condition(text: str, defined: frozenset[str]) -> bool | None:
"""gh#35's decision procedure. Handles `defined(X)`, `!defined(X)`, `&&`, `||` and
parentheses — which is the whole of what guards a conditional binding in practice —
and reports None for everything else.
NONE IS THE LOAD-BEARING RETURN. It is the difference between "this branch is dead,
drop its edge" and "we do not know which branch is live, so grade both down". A
version of this that fell back to False would silently DELETE the live edge of any
binding guarded by an expression it could not parse, which is strictly worse than the
over-complete graph gh#35 is fixing. `||` is folded short-circuit for the same
reason: an unknown operand beside a decisive one must not weaken a known answer.
OR binds looser than AND in C, so `||` is split first and `&&` within each operand.
@brief Decide whether a preprocessor condition holds under a configuration.
@return True, False, or None when undecidable.
@version 1
"""
stripped = _unwrap(text.strip())
ors = _split_top(stripped, "||")
if len(ors) > 1:
return _combine([evaluate_condition(p, defined) for p in ors], decisive=True)
ands = _split_top(stripped, "&&")
if len(ands) > 1:
return _combine([evaluate_condition(p, defined) for p in ands], decisive=False)
return _atom(stripped, defined)
Activity · 8 steps
Requirements
macros_from_header
tuple[str, ...] clew.preprocessor.macros_from_header(Path path)
Harvest object-like #define s from a config header, honouring #undef .
Source · 36 lines
def macros_from_header(path: Path) -> tuple[str, ...]:
"""A FLAT SCAN, not a preprocessor: `#if` blocks are walked through without being
evaluated, so a define inside a conditional is harvested whether or not that
conditional would hold. Stated rather than discovered — see the module docstring.
It is the right trade for the job gh#17 names, because a config header states its
configuration as top-level defines and comments out the alternatives, so a commented
`//#define MBEDTLS_X` is correctly NOT harvested.
`#undef` is honoured. A header that revokes a macro and is read as defining it would
be worse than not reading the header at all.
Unreadable degrades to empty WITH a warning rather than raising: the caller has
already been told the file exists, and failing an index build over a metadata read
would take a whole doxygen run with it.
@brief Read a config header's object-like defines as PREDEFINED tokens.
@return Ordered, deduplicated macro tokens.
@version 1
"""
try:
text = path.read_text(encoding="utf-8", errors="replace")
except OSError as exc:
logger.warning("preprocessor: %s is unreadable (%s) — no macros harvested", path, exc)
return ()
defined: dict[str, str] = {}
for line in text.splitlines():
undef = _UNDEF.match(line)
if undef is not None:
defined.pop(undef.group(1), None)
continue
parsed = _define_from_line(line)
if parsed is not None:
defined[parsed[0]] = parsed[1]
return tuple(_token(name, value) for name, value in defined.items())
Activity · 15 steps
Requirements
resolve_preprocessor
PreprocessorConfig clew.preprocessor.resolve_preprocessor(Path|str|None repo_root, dict[str, Any]|None declaration, list[str]|None explicit=None)
Resolve the preprocessor configuration for a build: flag, else declaration.
Called by _build_stages
Tested by 9 tests
test_a_declared_config_header_outside_the_repository_is_refused, test_a_declared_macro_wins_over_the_header, test_a_missing_named_header_is_still_recorded, test_a_scalar_predefined_is_refused, test_an_explicit_list_keeps_the_declared_config_header, test_auto_discovery_finds_one_conventional_header, test_auto_discovery_ignores_a_mock_config_header, test_auto_discovery_refuses_two_candidates, test_provenance_names_the_source
Calls _declared_macros, _merged, _resolve_config_header, _source_of, _stated_only, _token, macros_from_header
Source · 83 lines
def resolve_preprocessor(
repo_root: Path | str | None,
declaration: dict[str, Any] | None,
explicit: list[str] | None = None,
) -> PreprocessorConfig:
"""An explicit `--predefined` WINS OUTRIGHT and does not merge, matching
`_entry_patterns`' rule for a flag that replaces a list: the declaration is the
repo's standing statement about which variant it ships, and an operator passing a
macro list is deliberately indexing a different one. Merging would produce a third
configuration nobody asked for.
Reachable from BOTH entry points with nothing passed, because it works from
`repo_root` and the declaration alone. That is the point rather than a convenience —
CLAUDE.md's rule is that a declaration reachable only from argv is not a
declaration, and the MCP build passes no override arguments.
Returns an all-empty config when nothing is declared, which is what makes this
change byte-identical to the previous behaviour for every existing target: no
`PREDEFINED` line is emitted, no `build_meta` row is written, and the Doxyfile
doxygen receives is unchanged.
@brief Resolve the build's preprocessor configuration with its provenance.
@return The resolved configuration.
@version 4
"""
section = (declaration or {}).get(SECTION_PREPROCESSOR)
if explicit:
## THE MACRO LIST IS REPLACED; THE REPOSITORY'S OWN HEADER IS NOT A MACRO LIST. This branch
## used to `return` before reading `section` at all, so a declaration stating
## `config_header:` beside `predefined:` had that header silently discarded the moment a
## flag was passed — and `clew/cli.py` promotes a declared `predefined:` to this very
## `explicit` argument, so the acceptance build discarded its own declared header on every
## run. An accepted-but-unread key is this project's most repeated defect; this was one.
##
## What the flag legitimately overrides is WHICH VARIANT gets indexed. Where the repository
## states its own default is a fact ABOUT THE REPOSITORY and survives the override, which
## is what lets `stated_only` be computed: the overridden names the header does NOT define
## are exactly the ones that ship OFF.
macros = tuple(_token(*(m.split("=", 1) if "=" in m else (m, ""))) for m in explicit)
header, searched = (
_resolve_config_header(
Path(repo_root).expanduser().resolve(), section.get(KEY_CONFIG_HEADER)
)
if repo_root is not None and isinstance(section, dict) and section
else (None, ())
)
root = Path(repo_root).expanduser().resolve() if repo_root is not None else None
harvested = macros_from_header(header) if header is not None else ()
return PreprocessorConfig(
macros=macros,
source=SOURCE_FLAG,
config_header=str(header.relative_to(root)) if header is not None and root else None,
searched=searched,
## Computed against the OVERRIDDEN list, not the declared one: the question a reader
## has is "of the macros this index was built with, which does the repo not ship?"
## `_stated_only` bare-names both sides itself, so the rendered tokens go in as-is.
stated_only=_stated_only(macros, harvested),
)
if repo_root is None or not isinstance(section, dict) or not section:
return PreprocessorConfig()
root = Path(repo_root).expanduser().resolve()
declared = _declared_macros(section)
header, searched = _resolve_config_header(root, section.get(KEY_CONFIG_HEADER))
harvested = macros_from_header(header) if header is not None else ()
config = PreprocessorConfig(
macros=_merged(declared, harvested),
source=_source_of(section, declared, harvested),
config_header=str(header.relative_to(root)) if header is not None else None,
searched=searched,
stated_only=_stated_only(declared, harvested),
)
## Said out loud at INFO, because this decides WHICH VARIANT of the target gets
## indexed and every count downstream is relative to it. A resolution that produced
## nothing is the case most worth seeing, so it is logged too rather than skipped.
logger.info(
"preprocessor: %d macro(s) from %s%s",
len(config.macros),
config.source,
f" ({config.config_header})" if config.config_header else "",
)
return config