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
3 changes: 2 additions & 1 deletion devtools/code_health/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ function or class exceed their limit. Checks are the metric names in the table a
`file_lines`, `function_lines`, `nesting`, `parameters`, `public_methods`, `public_data`,
`single_method_interface`, `header_symbols`. Style findings that take a tag too: `char_pointer`,
`overload_prefix`, `out_param_order`, `string_concat`, `param_comment`, `test_only_api`, `extern_template`,
`free_function`, `uncalled_method`, `one_user_alias` and `bool_with_failure`, for a C API
`free_function`, `uncalled_method`, `one_user_alias`, `bool_with_failure` and `enum_string_switch`, for a C API
or a fixed interface that needs them; so do `learned_rule_test` and `special_case` (see
[Systematic fixes](#systematic-fixes)). Other style and layering
findings have no bypass.
Expand Down Expand Up @@ -191,6 +191,7 @@ lexer, not a parser: rules that need types stay in review.
| A public method a header adds to a class without bases, not virtual, that no file outside the class's .h/.cpp and tests calls as `.name`, `->name` or `::name`; a call counts only in a file that, or whose own header, names the class or includes its header. Not reported: `begin`/`end` and kin | advisory (tag: `uncalled_method`) | same (#648: `registry()`, `run_checkpoint`) |
| A namespace-scope `using X = ...;` a header adds that one other header uses (or, with no header, one other module), counting files that include the header (`review_rules.py`) | advisory (tag: `one_user_alias`) | same (#648: `EventLogger`) |
| A struct with a `bool` completed/passed/ok/succeeded/success/failed next to an `Outcome`, `*Report`, `*Result` or `*failure*`/`*error*` member: one `std::optional<Failure>` | advisory (tag: `bool_with_failure`) | same (#648: `CheckpointReport`, `StoryEngineReport`) |
| A `switch` an added line starts whose cases are `Enum::VALUE` labels (several may share one return; `default:` too) and whose every statement is `return "<literal>";`: a hand-written enum-to-string function. The reverse (string to enum) is not checked (`review_rules.py`) | advisory (tag: `enum_string_switch`) | user review on fork #667 (`screen_event_name`, `warp_fade_name`): use `EnumStringMap<T>` (`Common/Cpp/EnumStringMap.h`) |

Advisories print as `Advisory:` lines and `::warning` annotations and never fail.

Expand Down
2 changes: 1 addition & 1 deletion devtools/code_health/allow.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
# Style findings a tag can bypass; they attach like a function's tag, to the finding's line.
STYLE_CHECKS = ('char_pointer', 'overload_prefix', 'out_param_order', 'string_concat', 'param_comment',
'test_only_api', 'learned_rule_test', 'special_case', 'extern_template', 'free_function',
'uncalled_method', 'one_user_alias', 'bool_with_failure')
'uncalled_method', 'one_user_alias', 'bool_with_failure', 'enum_string_switch')
# File-level metrics: the tag goes in the first FILE_TAG_LINES lines.
FILE_CHECKS = ('file_lines',) + tuple(HEADER_LIMITS)
CHECKS = (('file_lines', 'function_lines', 'nesting', 'parameters') + tuple(CLASS_LIMITS)
Expand Down
43 changes: 43 additions & 0 deletions devtools/code_health/review_rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
no header, one other module) uses, counting files that include the header: it lives with that user.
- `bool_with_failure`: a struct with a `bool` completed/passed/ok/... next to an `Outcome` or a
`*failure*`/`*error*` member: one `std::optional<Failure>` instead.

In any file, on added lines:
- `enum_string_switch`: a `switch` over `Enum::VALUE` cases whose every case returns a string
literal (a hand-written enum-to-string function, #667 `screen_event_name`): use
`EnumStringMap<Enum>` (Common/Cpp/EnumStringMap.h). The reverse (string to enum) is not checked.
"""
import re
from pathlib import PurePosixPath
Expand All @@ -25,6 +30,11 @@
CITE = 'fork AGENTS.md "Types, names and comments"'
FLAGS = {'completed', 'passed', 'ok', 'succeeded', 'success', 'failed'}
ITERATION = {'begin', 'end', 'cbegin', 'cend', 'rbegin', 'rend'} # called by range-for
SWITCH = re.compile(r'\bswitch\s*\(')
CASE = re.compile(r'\b(?:case\s+[\w:]*::\w+|default)\s*:(?!:)')
STRING_RETURN = re.compile(r'return\s*"[^"\n]*"\s*;')
FUNCTION = re.compile(r'([A-Za-z_][\w:]*)\s*\([^;{}()]*\)\s*(?:const\s*)?(?:noexcept\s*)?\{')
KEYWORDS = {'if', 'for', 'while', 'switch', 'catch'}
ALIAS = re.compile(r'(?:template\s*<.*>\s*)?using\s+([A-Za-z_]\w*)\s*=')


Expand Down Expand Up @@ -138,6 +148,38 @@ def alias_findings(path, source, previous_source, added, users, read):
return found


def closing_brace(code, start):
"""Index of the '}' matching the '{' at `start`, or -1."""
depth = 0
for i in range(start, len(code)):
depth += {'{': 1, '}': -1}.get(code[i], 0)
if depth == 0:
return i
return -1


def enum_string_findings(path, source, added):
code = '\n'.join(strip_code(normalize(source)))
found = []
for match in SWITCH.finditer(code):
line = code.count('\n', 0, match.start()) + 1
open_brace = code.find('{', match.end())
close = closing_brace(code, open_brace) if open_brace >= 0 else -1
if line not in added or close < 0:
continue
body = code[open_brace + 1:close]
labels = CASE.findall(body)
rest = STRING_RETURN.sub('', CASE.sub('', body)).strip()
if rest or len(STRING_RETURN.findall(body)) < 2 or not any('::' in label for label in labels):
continue
functions = [f for f in FUNCTION.findall(code, 0, match.start()) if f not in KEYWORDS]
name = functions[-1].split('::')[-1] if functions else 'switch'
found.append(Finding(path, line, rule(
f"'{name}' maps enum values to string literals in a switch; use EnumStringMap<T> "
'(Common/Cpp/EnumStringMap.h)', 'user review on fork #667'), check='enum_string_switch'))
return found


def check(path, source, previous_source, users, read):
"""Advisories on what this change adds. `users(names)` -> {name: files}; `read(file)` -> text."""
added = added_lines(normalize(source).split('\n'),
Expand All @@ -146,4 +188,5 @@ def check(path, source, previous_source, users, read):
return []
found = class_findings(path, source, previous_source, added, users, read)
found += alias_findings(path, source, previous_source, added, users, read)
found += enum_string_findings(path, source, added)
return sorted(found, key=lambda f: f.line)
14 changes: 14 additions & 0 deletions devtools/code_health/tests/test_review_rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,20 @@ def test_bool_with_outcome(self):
findings('struct Report{\n bool completed = false;\n Outcome result;\n};'))
self.assertEqual([], findings('struct Report{\n bool saved = false;\n Outcome result;\n};'))

def test_enum_to_string_switch(self):
# Fork #667 before its review: screen_event_name in CommonTools/ScreenEvents.
names = """std::string screen_event_name(ScreenEvent event){
switch (event){
case ScreenEvent::FADE_BLACK: return "black fade";
case ScreenEvent::FADE_WHITE:
case ScreenEvent::DIALOG_BOX: return "other";
}
return "?";
}"""
self.assertEqual([('enum_string_switch', 'screen_event_name')], findings(names, path=CALLER))
computed = names.replace('return "other";', 'return describe(event);')
self.assertEqual([], findings(computed, path=CALLER))


if __name__ == '__main__':
unittest.main()
Loading