Skip to content
Open
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
4 changes: 3 additions & 1 deletion SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ Bazel aquery jsonproto ──extract_bazel.py───────┘

`canonicalize.py` strips noise before comparing flags. Universal mechanics
(driver/wrapper paths, `-c`/`-o`, sysroot, reproducibility defines) are dropped
in code — never your concern. `-O*`/`-g*` are dropped from the per-TU
in code — never your concern. `-O*`/`-g*` are dropped by default from the per-TU
comparison too, but the level still matters: `levels` in `diff.json` reports
each side's, and `differs: true` there is real. Judgment calls (warning-set or
cosmetic differences) go in `any2bazel.json`'s `ignore`. Correctness flags
Expand All @@ -98,6 +98,7 @@ whether its frontend reads it:
"dep_map": { "Catch2Main": "catch2_main" },
"exclude_targets": ["benchmark", "some_tool"],
"include_tests": false,
"compare_debug_flags": false,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think what we'll want longer term is various categories of sensitivity:

  • Warnings
  • Optimizations
  • Debug info

For an initial migration diff, folks probably don't care about warnings. However, when I was managing migrations, we did care about making sure warning enforcement stayed in sync everywhere.

It's likely this parameter will shift, but if I move it I'll retain backwards compatibility for a bit. I think this is fine as is for today.

"ignore": {
"defines": ["BORINGSSL_DISPATCH_TEST"],
"flags": ["-fvisibility=hidden"],
Expand Down Expand Up @@ -139,6 +140,7 @@ Fields:
test sources are compared as their own project-wide TU-set union (like
libraries) and a coarse test-binary count check runs. See
[Diff tests](#diff-tests).
- **`compare_debug_flags`** (default `false`) — include `-g` compile options.
- **`ignore.{defines,flags,flags_prefixes}`** — reviewer-approved compile
flag/define differences. `flags`/`defines` match exact tokens; `flags_prefixes`
by prefix.
Expand Down
10 changes: 7 additions & 3 deletions scripts/canonicalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,7 @@

# Flags that carry no correctness meaning for a parity check on either side.
IGNORABLE_FLAG_PREFIXES = (
"-g", # debug info level -- build-type driven, not a source diff
"-O", # optimization level -- ditto
"-O", # optimization level -- build-type driven, not a source diff
"-fdebug-prefix-map=",
"-ffile-prefix-map=",
"-ffile-compilation-dir=", # reproducibility; output-path derived
Expand Down Expand Up @@ -228,6 +227,7 @@ def canonicalize_flags(
repo_root: str,
*,
is_bazel: bool,
compare_debug_flags: bool = False,
) -> Tuple[Tuple[str, ...], Tuple[str, ...], Tuple[str, ...]]:
"""Return (defines, includes, other_flags) in canonical form.

Expand All @@ -237,6 +237,10 @@ def canonicalize_flags(
- other_flags: correctness-relevant only (ignorable + bazel-default dropped),
sorted for stable comparison
"""
ignored_prefixes = IGNORABLE_FLAG_PREFIXES
if not compare_debug_flags:
ignored_prefixes += ("-g",)

defines: List[str] = []
includes: List[str] = []
other: List[str] = []
Expand Down Expand Up @@ -296,7 +300,7 @@ def canonicalize_flags(
if is_bazel and _matches_any(tok, BAZEL_NOISE_FLAG_PREFIXES):
i += 1; continue
# drop universally-ignorable flags on both sides
if _matches_any(tok, IGNORABLE_FLAG_PREFIXES):
if _matches_any(tok, ignored_prefixes):
i += 1; continue

other.append(tok); i += 1
Expand Down
2 changes: 2 additions & 0 deletions scripts/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ class MigrationConfig:
# compared as their own project-wide TU-set union (like libraries), plus a
# test-binary existence/count check. See PARTICIPATING_ROLES in diff.py.
include_tests: bool = False
compare_debug_flags: bool = False

def flag_ignored(self, flag: str) -> bool:
return (flag in self.ignore_flags
Expand Down Expand Up @@ -187,6 +188,7 @@ def load(path: str) -> MigrationConfig:
exclude_targets=set(obj.get("exclude_targets", [])),
bazel_args=tuple(obj.get("bazel_args", [])),
include_tests=bool(obj.get("include_tests", False)),
compare_debug_flags=bool(obj.get("compare_debug_flags", False)),
)


Expand Down
14 changes: 6 additions & 8 deletions scripts/diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,13 +424,14 @@ def diff_models(a: CanonicalModel, b: CanonicalModel,
cfg = MigrationConfig()
# Reconstruct raw actions into comparable views (TUs + link flags + deps),
# build-system-specific interpretation keyed on each model's tag.
a_views = reconstruct(a)
a_views = reconstruct(a, compare_debug_flags=cfg.compare_debug_flags)
renames = _bazel_renames(a, b, cfg)
# Target renames come from the shared decision. Explicit target_map entries
# also rename DEPENDENCY references, even with no target node to rename.
view_map = dict(cfg.target_map)
view_map.update({name: label for label, name in renames.items()})
b_views = _apply_target_map(reconstruct(b), view_map)
b_views = _apply_target_map(
reconstruct(b, compare_debug_flags=cfg.compare_debug_flags), view_map)
a_names = _participating(a_views, cfg)
b_names = _participating(b_views, cfg)

Expand Down Expand Up @@ -632,9 +633,8 @@ def by_reason(model: CanonicalModel, renames: Dict[str, str]) -> dict:
"bazel": by_reason(b, _bazel_renames(a, b, cfg))}


# Optimization / debug level flags. canonicalize.py drops -O*/-g* from the
# per-TU comparison (build type is a build-wide setting, and diffing it per TU
# would be noise), so levels_summary reads them from the RAW argv instead.
# Build-type flags are skipped in per-TU comparisons by default. The levels
# summary reads them from the raw command lines.
_OPT_LEVEL = re.compile(r"^-O([0-3sgz]|fast)?$")
# Debug LEVEL (how much is emitted: -g1 has no locals, -g3 adds macros) and
# debug FORMAT (-gdwarf-N) are separate: `-g3 -gdwarf-4` and `-g1 -gdwarf-4`
Expand Down Expand Up @@ -689,9 +689,7 @@ def _compile_levels(model: CanonicalModel, cfg: "MigrationConfig",
for lang, h in sorted(out.items())}


LEVELS_NOTE = ("-O*/-g* are dropped from the per-TU comparison, so a different "
"optimization or debug level never shows up as a discrepancy. "
"This is what each side actually compiles at (TU counts).")
LEVELS_NOTE = "Optimization and debug levels for each side (TU counts)."


def levels_summary(a: CanonicalModel, b: CanonicalModel,
Expand Down
12 changes: 7 additions & 5 deletions scripts/reconstruct.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,8 +233,8 @@ def _infer_deps_from_link(actions, existing) -> List[Dependency]:

# ---- the reconstruct entry points ------------------------------------------

def reconstruct_target(t: Target, build_system: BuildSystem,
repo_root: str) -> TargetView:
def reconstruct_target(t: Target, build_system: BuildSystem, repo_root: str, *,
compare_debug_flags: bool = False) -> TargetView:
is_bazel = build_system == BuildSystem.BAZEL
view = TargetView(name=t.name, kind=t.kind, role=t.role)

Expand All @@ -246,7 +246,8 @@ def reconstruct_target(t: Target, build_system: BuildSystem,
if not src:
continue
cdef, cinc, cfl = canonicalize_flags(
list(act.arguments), repo_root, is_bazel=is_bazel)
list(act.arguments), repo_root, is_bazel=is_bazel,
compare_debug_flags=compare_debug_flags)
view.tus.append(TranslationUnit(
source=_rel(src, repo_root), defines=cdef,
includes=cinc, flags=cfl))
Expand All @@ -269,7 +270,8 @@ def reconstruct_target(t: Target, build_system: BuildSystem,
return view


def reconstruct(model: CanonicalModel) -> dict:
def reconstruct(model: CanonicalModel, *, compare_debug_flags: bool = False) -> dict:
"""Reconstruct every target into a TargetView, keyed by target name."""
return {name: reconstruct_target(t, model.build_system, model.repo_root)
return {name: reconstruct_target(t, model.build_system, model.repo_root,
compare_debug_flags=compare_debug_flags)
for name, t in model.targets.items()}
2 changes: 1 addition & 1 deletion scripts/triage.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def render(t: dict, top: int = 25) -> str:
def fmt(h):
return " ".join(f"{v} x{n}" for v, n in h.items())
tag = "DIFFERS" if lv.get("differs") else "same"
lines.append(f"opt/debug levels ({tag}; not part of the diff):")
lines.append(f"opt/debug levels ({tag}):")
for lang in sorted(set(lv.get("cmake") or {}) | set(lv.get("bazel") or {})):
for side in ("cmake", "bazel"):
h = (lv.get(side) or {}).get(lang)
Expand Down
16 changes: 15 additions & 1 deletion tests/test_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "scripts"))

from config import MigrationConfig
from config import MigrationConfig, load
from diff import DiffNotes, Severity, diff_models, summarize
from model import (Action, BuildSystem, CanonicalModel, Dependency, Target,
TargetKind, TargetRole)
Expand Down Expand Up @@ -143,6 +143,20 @@ def test_missing_cmake_flag_is_caught():
assert "NEEDED=1" in dd.cmake_only


def test_compare_debug_flags_is_opt_in(tmp_path):
reference_flags = ["-g2", "-gdwarf-4", "-gsplit-dwarf"]
reference = _model(tu_from_raw("src/a.cpp", reference_flags, False))
bazel = _model(tu_from_raw("src/a.cpp", ["-g0"], True), is_bazel=True)
assert diff_models(reference, bazel) == []

config_path = tmp_path / "any2bazel.json"
config_path.write_text('{"compare_debug_flags": true}')
config = load(config_path)
[discrepancy] = diff_models(reference, bazel, config)
assert discrepancy.kind == "flags_diff"
assert discrepancy.cmake_only == reference_flags


def test_undefine_cancels_earlier_defines_last_wins():
from canonicalize import canonicalize_flags
def canon(raw):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_triage.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def test_render_shows_levels():
"bazel": {"CXX": {"opt": {"-O2": 94}, "debug": {"-g0": 94},
"debug_format": {"(none)": 94}}}}}
text = render(triage(diff))
assert "opt/debug levels (DIFFERS; not part of the diff):" in text
assert "opt/debug levels (DIFFERS):" in text
assert "opt: -O3 x94" in text and "opt: -O2 x94" in text
assert "format: (none) x94" in text

Expand Down