diff --git a/devtools/code_health/style.py b/devtools/code_health/style.py index 5ef28d03d3..61b48101cf 100644 --- a/devtools/code_health/style.py +++ b/devtools/code_health/style.py @@ -617,14 +617,24 @@ def structures(parsed): match = re.match(r'struct\s+(\w+)\b', statement.text) if match and statement.end == '{': found[match.group(1)] = {} - elif enclosing and enclosing[-1][0] == 'class' and statement.end == ';': + elif enclosing and enclosing[-1][0] == 'class': fields = found.get(enclosing[-1][1]) - field = re.fullmatch(r'([\w:<> ,]+?)\s+(\w+)\s*(?:=.*)?', statement.text) + field = field_declaration(statement) if fields is not None and field: fields[field.group(2)] = field.group(1) return found +def field_declaration(statement): + """`Type name;`, `Type name = value;`, or a brace initializer (`Type name = {}`, `Type name{}`), + which the statement splitter cuts at its `{`.""" + if statement.end == ';': + return re.fullmatch(r'([\w:<> ,]+?)\s+(\w+)\s*(?:=.*)?', statement.text) + if statement.end == '{' and not re.match(r'(?:enum|class|struct|union|namespace)\b', statement.text): + return re.fullmatch(r'([\w:<> ,]+?)\s+(\w+)\s*=?', statement.text) + return None + + def case_type(test_name, parsed): """The single aggregate parameter of this UnitTest constructor, if present.""" for statement, enclosing in scopes(parsed): diff --git a/devtools/code_health/tests/test_contracts.py b/devtools/code_health/tests/test_contracts.py index eb40d89675..e04d9c7863 100644 --- a/devtools/code_health/tests/test_contracts.py +++ b/devtools/code_health/tests/test_contracts.py @@ -57,6 +57,29 @@ class Test_Value : public UnitTest{ self.assertTrue(any('test-case' in m for m in self.messages(bad, CPP))) self.assertFalse(any('test-case' in m for m in self.messages(good, CPP))) + def test_case_fields_may_be_value_initialized(self): + # Windows clang (-Wmissing-designated-field-initializers) wants `= {}` on every field. + source = '''struct Case{ + struct Input{ int value = {}; }; + struct Expectation{ int value{}; }; + std::string name = {}; + Input input = {}; + Expectation expectation{}; +}; +class Test_Value : public UnitTest{ +public: + explicit Test_Value(Case scenario) : UnitTest(scenario.name){} +}; +const Case CASES[] = {{.name = "one", .input = {.value = 1}, .expectation = {.value = 2}}}; +void add_tests(){ + for (const Case& scenario : CASES){ database.add(scenario); } +} +''' + self.assertFalse(any('test-case' in m for m in self.messages(source, CPP))) + name_in_input = source.replace('struct Input{ int value = {}; };', + 'struct Input{ std::string name = {}; int value = {}; };') + self.assertTrue(any('test-case' in m for m in self.messages(name_in_input, CPP))) + def test_case_name_is_its_own_field_not_in_the_input(self): name_in_input = '''struct Input{ std::string name; int value; }; struct Expectation{ int value; };