Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions docs/src/convert.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,11 @@ not translate under "Decisions required" in the report. Each is an entry of
`decisions.bzl` with `decision.UNDECIDED` as its value: replace the value and
run the same command again. The outputs are written even while decisions are
missing, so the project can be looked at, but a conversion is complete only
when the file answers every question.
when the file answers every question. `UNDECIDED` is the placeholder the
converter writes, not an answer: a run that finds one still in the file stops
with an error naming the keys, and neither `DEFAULTS` nor the bundled
decisions answer for it. Every key gets an explicit decision, `IGNORE` when
the construct is to stay out.

The file is read with a parser, never evaluated; its header names the
rules_cc_autoconf that wrote it. New entries are added in key order with a
Expand All @@ -85,7 +89,7 @@ converter stops asking for are reported as unused. A `checks.X(...)` value reads
as in a BUILD file: add `load("@rules_cc_autoconf//autoconf:checks.bzl",
"checks")` at the top.

A `DEFAULTS` table answers every undecided key of a kind at once, for a
A `DEFAULTS` table answers every key of a kind the table has no entry for, for a
construct that never matters for the module (a firmware compiler's probes, a
toolchain's warning flags); the report lists what a default answered:

Expand Down Expand Up @@ -134,8 +138,8 @@ The questions every gnulib project raises the same way, the gettext probes
and substitutions of a project that builds no message catalogs, gnulib's
own witness variables, are answered once, in `gnulib/m4/decisions.bzl`
beside the ports. The converter reads it beneath the project's decisions
file: a key the project's file answers wins, a key it leaves out or
`UNDECIDED` takes the bundled answer, and only then does `DEFAULTS` apply.
file: a key the project's file answers wins, a key it leaves out takes the
bundled answer, and only then does `DEFAULTS` apply.
The report lists every answer taken from it under "Decisions inherited",
so nothing applies silently; the bundled file's own keys never count as
unused. `--bundled-decisions FILE` reads another file, `none` reads none;
Expand Down
3 changes: 2 additions & 1 deletion gnulib/m4/decisions.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ Reference: https://periareon.github.io/rules_cc_autoconf/convert.html#decisions

# The words a decision may be, besides a literal, a select() or checks.X(...).
decision = struct(
# Not decided yet: the construct stays out and the run exits 3.
# The placeholder written for a key the converter asks about; not an answer.
# The next run rejects the file while one remains.
UNDECIDED = "UNDECIDED",
# Leave the construct out for good.
IGNORE = "IGNORE",
Expand Down
41 changes: 25 additions & 16 deletions tools/convert/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
from tools.convert import project as project_mod
from tools.convert import source as source_mod
from tools.convert.common import DEFAULT_COMMAND, TOP_HEADERS
from tools.convert.decisions import MIGRATION_GUIDE, Decisions
from tools.convert.decisions import MIGRATION_GUIDE, DecisionError, Decisions
from tools.convert.index import PortIndex, ports_checkout
from tools.convert.ir import Package
from tools.convert.ports import PortSnapshot
Expand Down Expand Up @@ -876,7 +876,8 @@ def _write_report(
"",
"The constructs below have no mechanical translation and were left out. Decide each",
f"key in `{decisions_path}` (the migration guide, {MIGRATION_GUIDE}, is the reference",
"for how each construct maps) and run the same command again"
"for how each construct maps) and run the same command again; an entry left `UNDECIDED`"
" is an error on that run"
+ (f" ({len(added)} new entries were added with `UNDECIDED` as the value)." if added else "."),
"",
]
Expand All @@ -895,7 +896,7 @@ def _write_report(
"",
f"## Decisions taken by default ({len(decisions.defaulted)})",
"",
"Keys the table leaves undecided that `DEFAULTS` answered by kind; an entry for a key",
"Keys the table has no entry for that `DEFAULTS` answered by kind; an entry for a key",
"overrides its kind's default.",
"",
] + decisions.defaulted_lines()
Expand All @@ -910,7 +911,10 @@ def _write_report(
print(f"wrote {path}")
print(f"report: {out / 'CONVERSION_REPORT.md'}")
if pending:
print(f"{len(pending)} decision(s) required; fill in {decisions_path} and rerun", file=sys.stderr)
print(
f"{len(pending)} decision(s) required; answer every UNDECIDED entry in {decisions_path} and rerun",
file=sys.stderr,
)
return 3
return 0

Expand Down Expand Up @@ -1611,21 +1615,26 @@ def build_parser() -> argparse.ArgumentParser:

def main(argv: list[str] | None = None) -> int:
"""Run the command line. The exit code is 0, 1 when the expansion fails, 2 on a usage or
environment error, 3 when decisions are required.
environment error or a decisions file the converter rejects (an entry still `UNDECIDED`,
a value of the wrong shape), 3 when decisions are required.
"""
args = build_parser().parse_args(argv)
command: Callable[[argparse.Namespace], int] = args.func
if args.profile:
profile_path = _resolve(args.profile)
profiler = cProfile.Profile()
code = profiler.runcall(command, args)
profiler.dump_stats(profile_path)
with profile_path.with_suffix(profile_path.suffix + ".txt").open("w", encoding="utf-8") as out:
stats = pstats.Stats(profiler, stream=out).sort_stats("cumulative")
stats.print_stats(40)
stats.sort_stats("tottime").print_stats(25)
return code
return command(args)
try:
if args.profile:
profile_path = _resolve(args.profile)
profiler = cProfile.Profile()
code = profiler.runcall(command, args)
profiler.dump_stats(profile_path)
with profile_path.with_suffix(profile_path.suffix + ".txt").open("w", encoding="utf-8") as out:
stats = pstats.Stats(profiler, stream=out).sort_stats("cumulative")
stats.print_stats(40)
stats.sort_stats("tottime").print_stats(25)
return code
return command(args)
except DecisionError as error:
print(f"error: {error}", file=sys.stderr)
return 2


if __name__ == "__main__":
Expand Down
67 changes: 41 additions & 26 deletions tools/convert/decisions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@
construct up in a decisions file by a stable key. A missing decision is
reported, the construct is left out of the output, and the key is added to
the decisions file with its context as comments and `UNDECIDED` as its
value; nothing is guessed. Regenerating with the same sources and the same
decisions file reproduces the same output.
value; nothing is guessed. `UNDECIDED` is that placeholder and not an
answer: a file that still holds one is rejected at load, so every key gets
an explicit decision (`IGNORE` when the construct is to stay out).
Regenerating with the same sources and the same decisions file reproduces
the same output.

The decisions file is Starlark, written in the vocabulary of the output and
read with Python's `ast` module (never executed). It defines the `decision`
Expand All @@ -26,10 +29,10 @@
"flag:gcc_warnings": False,
}

A value is a word of the struct (`decision.UNDECIDED`, `decision.IGNORE`,
`decision.ACCEPT`, `decision.ACCEPT_PARTIAL`, `decision.ALWAYS`,
`decision.NEVER`, `decision.MANUAL`; the bare word is still read, for files
written before the struct); a literal; a `select({...})` over configuration labels; or
A value is a word of the struct (`decision.IGNORE`, `decision.ACCEPT`,
`decision.ACCEPT_PARTIAL`, `decision.ALWAYS`, `decision.NEVER`,
`decision.MANUAL`; the bare word is still read, for files written before
the struct); a literal; a `select({...})` over configuration labels; or
`checks.*` / `macros.*` / `utils.*` calls exactly as they would appear in
`BUILD.bazel` (one call or a list of calls). Which of these a key accepts
depends on its kind; see `FORMS`.
Expand Down Expand Up @@ -359,6 +362,24 @@ def _parse(text: str, source: str) -> tuple[dict[str, DecisionValue], ast.Dict |
return table, node, defaults


def _reject_undecided(table: dict[str, DecisionValue], node: ast.Dict | None, source: str) -> None:
"""`UNDECIDED` is the placeholder the skeleton writes for a key the converter asked about,
not an answer: a file that still holds one is rejected, naming the keys, so that every
question gets an explicit decision rather than a silent omission or a default."""
undecided = [key for key, value in table.items() if isinstance(value, Word) and value.name == "UNDECIDED"]
if not undecided:
return
lines = {k.value: k.lineno for k in node.keys if isinstance(k, ast.Constant)} if node is not None else {}
where = f"{source}:{lines[undecided[0]]}" if undecided[0] in lines else source
count = f"{len(undecided)} {'entry is' if len(undecided) == 1 else 'entries are'}"
shown = ", ".join(undecided[:6]) + (", ..." if len(undecided) > 6 else "")
raise DecisionError(
f"{where}: {count} still {STRUCT_NAME}.UNDECIDED ({shown}); that is the placeholder the "
f"converter writes, not an answer: decide each ({STRUCT_NAME}.IGNORE leaves the construct out) "
"and run again"
)


def _attr_value(value: DecisionValue, where: str) -> AttrValue:
"""A decision value as a call's argument: a Starlark value. A word, a `select()` or a rule
call has no place inside `checks.X(...)` (the emitter renders none of them) and is an error."""
Expand Down Expand Up @@ -689,11 +710,13 @@ def load(cls, path: Path | None) -> Decisions:
return cls(source=str(path) if path else None)
text = path.read_text(encoding="utf-8").replace("\r\n", "\n")
data, node, defaults = _parse(text, str(path))
_reject_undecided(data, node, str(path))
return cls(data, str(path), node, text, defaults)

@classmethod
def from_text(cls, text: str, source: str = "<decisions>") -> Decisions:
data, node, defaults = _parse(text, source)
_reject_undecided(data, node, source)
return cls(data, source, node, text, defaults)

def _record(self, request: Request) -> None:
Expand All @@ -704,9 +727,7 @@ def resolve(self, request: Request) -> Decision | None:
"""The normalized decision for `request`: the key's, else the kind's default (recorded
under `defaulted`), else None and the request is pending."""
value = self.data.get(request.key)
if value is not None:
self.used.add(request.key)
if value is None or (isinstance(value, Word) and value.name == "UNDECIDED"):
if value is None:
shared = self._shared(request.key)
if shared is not None:
return normalize(request.kind, request.key, shared)
Expand All @@ -715,6 +736,7 @@ def resolve(self, request: Request) -> Decision | None:
return normalize(request.kind, request.key, self.defaults[request.kind])
self._record(request)
return None
self.used.add(request.key)
return normalize(request.kind, request.key, value)

def lookup(self, key: str) -> DecisionValue | None:
Expand All @@ -738,7 +760,7 @@ def _shared(self, key: str) -> DecisionValue | None:
if self.shared is None:
return None
value = self.shared.data.get(key)
if value is None or (isinstance(value, Word) and value.name == "UNDECIDED"):
if value is None:
return None
self.shared.used.add(key)
self.inherited.setdefault(key, _spell(value))
Expand All @@ -747,31 +769,22 @@ def _shared(self, key: str) -> DecisionValue | None:
def optional(self, key: str, kind: str) -> Decision | None:
"""A decision that is applied when present and never requested."""
value = self.data.get(key)
if value is None or (isinstance(value, Word) and value.name == "UNDECIDED"):
if value is None:
shared = self._shared(key)
return normalize(kind, key, shared) if shared is not None else None
self.used.add(key)
return normalize(kind, key, value)

def decided(self, key: str) -> bool:
"""Whether the file, or the bundled one beneath it, answers `key`: an entry whose value is
not `UNDECIDED`. Reading the tables directly, it does not count the key as used
(`optional` and `resolve` do)."""
value = self.data.get(key)
if value is not None and not (isinstance(value, Word) and value.name == "UNDECIDED"):
return True
return self.shared is not None and self.shared.decided(key)
"""Whether the file, or the bundled one beneath it, has an entry for `key`. Reading the
tables directly, it does not count the key as used (`optional` and `resolve` do)."""
return key in self.data or (self.shared is not None and self.shared.decided(key))

@property
def unused(self) -> list[str]:
"""Decisions the conversion never asked for."""
return sorted(k for k in self.data if k not in self.used)

@property
def missing(self) -> list[str]:
"""Pending keys that are not in the file at all (as opposed to UNDECIDED)."""
return sorted(k for k in self.pending if k not in self.data)

# -- writing the skeleton -------------------------------------------------

def entries(self, keys: list[str] | None = None) -> str:
Expand All @@ -795,8 +808,9 @@ def write_needed(self, path: Path, title: str | None = None, version: str = "?")

The table stays sorted by key (buildifier's `unsorted-dict-items`): a new entry goes in
front of the first existing key that sorts after it, above that key's comment block,
or at the end when none does."""
keys = self.missing
or at the end when none does. Every pending key is absent from the file: an entry
still `UNDECIDED` from an earlier run is rejected at load."""
keys = sorted(self.pending)
if not keys:
return []
if self._node is None or not self._text:
Expand Down Expand Up @@ -869,7 +883,8 @@ def _spell(value: DecisionValue) -> str:

STRUCT = """# The words a decision may be, besides a literal, a select() or checks.X(...).
decision = struct(
# Not decided yet: the construct stays out and the run exits 3.
# The placeholder written for a key the converter asks about; not an answer.
# The next run rejects the file while one remains.
UNDECIDED = "UNDECIDED",
# Leave the construct out for good.
IGNORE = "IGNORE",
Expand Down
Loading
Loading