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
7 changes: 7 additions & 0 deletions devtools/code_health/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,3 +246,10 @@ generated declarations or C++ overloads like a compiler. Shared fixture types
should remain beside the tests or need a deliberate parser extension, not an
unexplained bypass. Header parameter spans, game movement policies and comment
quality still require design review. These rules do not force a default policy.

Namespace moves retain previous metric ceilings only when the declaration text
is unchanged, stays in the same file, matches one old and one current function,
and the old qualified symbol is gone. Copies and ambiguous matches receive no
allowance, and increases beyond the previous metrics still fail. Namespace
comments are also recognized after declarations such as
`Q_DECLARE_METATYPE(...)` that do not end with a semicolon.
8 changes: 7 additions & 1 deletion devtools/code_health/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from contextlib import redirect_stderr
from dataclasses import dataclass
from io import StringIO
from hashlib import sha256

import lizard

Expand All @@ -19,6 +20,9 @@ class Metric:
# (std::function to MoveOnlyFunction, #90) must not turn an old long
# function into a new one held to the limit.
name: str = None
# Unchanged declaration text for a uniquely identified namespace move.
# The old qualified symbol must disappear; copies cannot inherit its debt.
declaration_identity: str = None

@property
def key(self):
Expand Down Expand Up @@ -56,7 +60,9 @@ def measure(path, source):
('nesting', max(0, getattr(function, 'brace_peak', 1) - 1), 4),
('parameters', function.parameter_count, 7),
)
declaration = '\n'.join(lines[function.start_line - 1:function.end_line]).split('{', 1)[0]
declaration_identity = sha256(declaration.encode('utf-8')).hexdigest()
for check, value, limit in values:
result.append(Metric(path, function.long_name, check, value, limit,
function.start_line, function.name))
function.start_line, function.name, declaration_identity))
return result
31 changes: 26 additions & 5 deletions devtools/code_health/policy.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,43 @@
"""Compare changed C++ with its base revision; no stored debt registry."""
from collections import Counter, defaultdict

from .allow import ceiling as bypass_ceiling
from .config import ADVISORY, HINTS
from .findings import Finding


def base_values(previous):
def base_values(previous, current=()):
old = {}
current_keys = {metric.key for metric in current}
current_moves = Counter(move_key(metric) for metric in current if metric.declaration_identity)
moved = defaultdict(dict)
for metric in previous:
old[metric.key] = max(old.get(metric.key, 0), metric.value)
if metric.declaration_identity is not None and metric.key not in current_keys:
moved[move_key(metric)][metric.key] = metric.value
for key, candidates in moved.items():
if len(candidates) == 1 and current_moves[key] == 1:
old[key] = next(iter(candidates.values()))
return old


def move_key(metric):
"""A same-file namespace move with an unchanged, unambiguous declaration."""
return ('namespace_move', metric.path, metric.declaration_identity, metric.check)


def base_value(metric, old, default):
return old.get(metric.key, old.get(move_key(metric), default))


def evaluate(metrics, previous, allowed=None):
"""Failures for values above both the limit and the base; `allowed` maps metrics to tags."""
old = base_values(previous)
metrics = list(metrics)
old = base_values(previous, metrics)
allowed = allowed or {}
failures = []
for metric in metrics:
ceiling = max(metric.limit, old.get(metric.key, metric.limit))
ceiling = max(metric.limit, base_value(metric, old, metric.limit))
if metric.value <= ceiling:
continue
message = (f'{metric.symbol or "<file>"}: {metric.check}={metric.value}, '
Expand Down Expand Up @@ -56,11 +76,12 @@ def advisories(metrics, previous):
"""New or changed values between an advisory floor and the limit; legacy excess is not repeated.

Every changed file above its floor is reported: the file changed even if its length did not."""
old = base_values(previous)
metrics = list(metrics)
old = base_values(previous, metrics)
notes = []
for metric in metrics:
floor = ADVISORY.get(metric.check)
if floor is None or (metric.check != 'file_lines' and old.get(metric.key) == metric.value):
if floor is None or (metric.check != 'file_lines' and base_value(metric, old, None) == metric.value):
continue
if floor < metric.value <= metric.limit:
notes.append(Finding(metric.path, metric.line, f'{metric.symbol or "<file>"}: '
Expand Down
2 changes: 1 addition & 1 deletion devtools/code_health/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,7 @@ def scopes(parsed):
kind = brace_kind(statement.text)
if re.fullmatch(r'extern\s*"\s*"', statement.text):
kind = 'linkage'
match = re.fullmatch(r'(?:inline\s+)?namespace\s*([\w:]*)', statement.text)
match = re.search(r'\b(?:inline\s+)?namespace\s*([\w:]*)$', statement.text)
if kind == 'class':
match = re.search(r'\b(?:class|struct|union)\s+(\w+)', statement.text)
stack.append((kind, match.group(1) if match else ''))
Expand Down
7 changes: 7 additions & 0 deletions devtools/code_health/tests/test_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ def messages(self, source, path=HEADER, previous=None):
return [finding.message for finding in check(path, source, previous)[0]
if not finding.message.startswith('style:')]

def test_namespace_name_after_a_metatype_macro_without_semicolon(self):
source = ('Q_DECLARE_METATYPE(std::string)\nnamespace Project{\nnamespace{\n'
'} // namespace\n} // namespace Project\n')
self.assertEqual([], self.messages(source, path=CPP))
broken = source.replace('// namespace Project', '// namespace Wrong')
self.assertTrue(any('namespace-close' in m for m in self.messages(broken, path=CPP)))

def test_namespace_close_requires_matching_comment(self):
self.assertTrue(any('namespace-close' in m for m in self.messages('namespace Pokemon{\n}\n')))
self.assertEqual([], self.messages('namespace Pokemon{\n} // namespace Pokemon\n'))
Expand Down
27 changes: 27 additions & 0 deletions devtools/code_health/tests/test_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,33 @@ def test_changed_parameter_types_keep_the_base(self):
grown = measure('Common/test.cpp', 'void A::f(MoveOnlyFunction<void()> f){\n' + 'x();\n' * 61 + '}\n')
self.assertTrue(evaluate(grown, old))

def test_namespace_move_retains_only_an_unambiguous_removed_function_base(self):
body = 'void f(){\n' + ' x();\n' * 60 + '}\n'
old = measure('Common/test.cpp', body)
moved = measure('Common/test.cpp', 'namespace Project{\nnamespace{\n' + body + '}\n}\n')
self.assertEqual([], evaluate(moved, old))
changed = measure('Common/test.cpp', 'namespace Project{\n' + body.replace('x();', 'y();') + '}\n')
self.assertEqual([], evaluate(changed, old))
grown = measure('Common/test.cpp', 'namespace Project{\n' + body.replace('x();\n', 'x();\ny();\n') + '}\n')
self.assertTrue(evaluate(grown, old))
copied = measure('Common/test.cpp', body + 'namespace Project{\n' + body + '}\n')
self.assertTrue(evaluate(copied, old))

def test_ambiguous_namespace_moves_do_not_transfer_debt(self):
body = 'void f(){\n' + 'x();\n' * 60 + '}\n'
old = measure('Common/test.cpp', body + 'namespace A{\n' + body + '}\n')
new = measure('Common/test.cpp', 'namespace B{\n' + body + '}\n')
self.assertTrue(evaluate(new, old))
single_old = measure('Common/test.cpp', body)
multiple_new = measure('Common/test.cpp', 'namespace B{\n' + body + '}\nnamespace C{\n' + body + '}\n')
self.assertTrue(evaluate(multiple_new, single_old))

def test_namespace_move_does_not_transfer_debt_across_files(self):
body = 'void f(){\n' + 'x();\n' * 60 + '}\n'
old = measure('Common/old.cpp', body)
moved = measure('Common/new.cpp', 'namespace Project{\n' + body + '}\n')
self.assertTrue(evaluate(moved, old))

def test_growth_below_limit_is_allowed(self):
self.assertEqual([], evaluate([function(50)], [function(25)]))

Expand Down
Loading