From b1061594c5e3ea2d8dcacdaeeb8040a40e3bcfe8 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 21:21:22 -0300 Subject: [PATCH 1/5] lint: nodiscard results reads only the declarations of namespaces and classes, so a local written T name(arguments); in a function's body is no function; it reads an alias of result, a using-declaration of it and a trailing return type too, and not a member's out-of-line definition, which its declaration answers for A { opens a scope of declarations only after a namespace's, a class's or an extern block's head, the class's attributes and export macros let through; a function's body, a lambda, an initializer and an enum do not, nor anything nested in them, and parentheses hide parameters. Preprocessor lines are left out. Aliases are gathered across the library's headers. A finding is reported at the function's name. lint_test plants the false positives and the gaps. --- tools/lint/lint.sh | 4 +- tools/lint/lint_test.py | 109 +++++++++++- tools/lint/rules.py | 372 +++++++++++++++++++++++++++++++++++----- 3 files changed, 438 insertions(+), 47 deletions(-) diff --git a/tools/lint/lint.sh b/tools/lint/lint.sh index fa1211ad..73c41132 100755 --- a/tools/lint/lint.sh +++ b/tools/lint/lint.sh @@ -858,7 +858,9 @@ fi # 20. A library that asks for it in its meta/lint.json, "nodiscard-results" and the reason, # declares every function of its headers that returns boost::system::result [[nodiscard]]: # boost::system::result carries no [[nodiscard]] of its own, so a dropped result, a -# verification's or an open's, compiles silently otherwise (tools/lint/rules.py). +# verification's or an open's, compiles silently otherwise (tools/lint/rules.py). The rule +# reads the declarations of namespaces and classes, an alias's result and a trailing return +# type too, and not a function's body, where T name(arguments); is a variable. rule 'nodiscard results' if python3 tools/lint/rules.py nodiscard-results < "${work_directory}/files"; then printf 'every library that asks for it declares its results [[nodiscard]]\n' diff --git a/tools/lint/lint_test.py b/tools/lint/lint_test.py index 16ca5423..50e1cf8d 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -2168,8 +2168,11 @@ def test_include_boundaries_missing_key(root): def plant_results(root) -> None: - """Writes NODISCARD_HEADER: functions returning boost::system::result with and without - [[nodiscard]], and results that are no function's.""" + """Writes NODISCARD_HEADER: functions returning boost::system::result, by its name, an alias + of it or a trailing return type, with and without [[nodiscard]]; members declared in their + class and defined out of it; and results that are no function's: locals written with + parentheses in the bodies of functions and of members, a lambda's, a commented-out one and a + variable's type.""" write(root, NODISCARD_HEADER, CPP + '\n' '#ifndef WEBCPP_DEMO_RESULTS_HPP\n' '#define WEBCPP_DEMO_RESULTS_HPP\n' @@ -2198,14 +2201,84 @@ def plant_results(root) -> None: ' return T{};\n' '}\n' '\n' + 'inline boost::system::result>> dropped_nested() {\n' + ' return std::pair>{};\n' + '}\n' + '\n' + '[[nodiscard]] inline boost::system::result>> ' + 'kept_nested() {\n' + ' return std::pair>{};\n' + '}\n' + '\n' + 'using outcome = boost::system::result;\n' + '\n' + 'template \n' + 'using outcome_of = boost::system::result;\n' + '\n' + 'inline outcome dropped_alias() {\n' + ' return 1;\n' + '}\n' + '\n' + '[[nodiscard]] inline outcome kept_alias() {\n' + ' return 1;\n' + '}\n' + '\n' + 'template \n' + 'outcome_of dropped_alias_template() {\n' + ' return T{};\n' + '}\n' + '\n' + 'inline auto dropped_trailing() -> boost::system::result {\n' + ' return 1;\n' + '}\n' + '\n' + '[[nodiscard]] inline auto kept_trailing() noexcept -> boost::system::result {\n' + ' return 1;\n' + '}\n' + '\n' + 'inline auto const lambda_value = []() -> boost::system::result { return 1; };\n' + '\n' + 'inline int local_with_parentheses() {\n' + ' boost::system::result local_outcome(kept_free());\n' + ' outcome const local_alias(kept_alias());\n' + ' return local_outcome.has_value() && local_alias.has_value() ? *local_outcome : 0;\n' + '}\n' + '\n' 'class holder {\n' 'public:\n' ' [[nodiscard]] static boost::system::result kept_member() { return {}; }\n' '\n' + ' [[nodiscard]] static boost::system::result kept_declared();\n' + '\n' + ' static boost::system::result dropped_declared();\n' + '\n' + ' [[nodiscard]] static int member_body() {\n' + ' boost::system::result member_local(kept_declared());\n' + ' return member_local.has_value() ? *member_local : 0;\n' + ' }\n' + '\n' 'protected:\n' ' static boost::system::result dropped_member() { return {}; }\n' '};\n' '\n' + 'inline boost::system::result holder::kept_declared() {\n' + ' return 1;\n' + '}\n' + '\n' + 'inline boost::system::result holder::dropped_declared() {\n' + ' return 2;\n' + '}\n' + '\n' + 'namespace unqualified {\n' + '\n' + 'using boost::system::result;\n' + '\n' + 'inline result dropped_unqualified() {\n' + ' return 1;\n' + '}\n' + '\n' + '} // namespace unqualified\n' + '\n' '// boost::system::result commented_out();\n' 'inline boost::system::result const constant_value{1};\n' '\n' @@ -2217,21 +2290,43 @@ def plant_results(root) -> None: def test_nodiscard_results(root): prepare(root) # A library that asks for it in meta/lint.json declares each function returning a result - # [[nodiscard]]: a free function, a template's and a member after an access specifier fail - # at their lines, with the library's reason; what is kept, commented out or a variable's type - # does not. + # [[nodiscard]]: a free function, a template's, one whose result nests templates, one + # returning an alias of a result, one with a trailing return type, a member after an access + # specifier, a member declared in its class, and one naming result after a using-declaration + # fail at their lines, with the library's reason. What is kept, a member's out-of-line + # definition, which its declaration answers for, a lambda, a local written with parentheses + # in a function's or a member's body, a comment and a variable's type do not. write(root, 'libs/demo/meta/lint.json', '{"nodiscard-results": "a dropped result is lost"}\n') plant_results(root) message = 'a function returning boost::system::result without [[nodiscard]]: ' - expect_alone(lint(root), 'nodiscard results', [ + result = lint(root) + expect_alone(result, 'nodiscard results', [ at(root, NODISCARD_HEADER, 'dropped_free') + ' ' + message + 'a dropped result is lost', at(root, NODISCARD_HEADER, 'dropped_template') + ' ' + message, + at(root, NODISCARD_HEADER, 'dropped_nested') + ' ' + message, + at(root, NODISCARD_HEADER, 'dropped_alias()') + ' ' + message, + at(root, NODISCARD_HEADER, 'dropped_alias_template') + ' ' + message, + at(root, NODISCARD_HEADER, 'dropped_trailing') + ' ' + message, + at(root, NODISCARD_HEADER, ' dropped_declared();') + ' ' + message, at(root, NODISCARD_HEADER, 'dropped_member') + ' ' + message, - ], spared=(at(root, NODISCARD_HEADER, 'kept_free'), + at(root, NODISCARD_HEADER, 'dropped_unqualified') + ' ' + message, + ], spared=(at(root, NODISCARD_HEADER, 'kept_free() noexcept'), at(root, NODISCARD_HEADER, 'kept_template'), + at(root, NODISCARD_HEADER, 'kept_nested'), + at(root, NODISCARD_HEADER, 'outcome kept_alias()'), + at(root, NODISCARD_HEADER, 'kept_trailing'), + at(root, NODISCARD_HEADER, 'lambda_value'), + at(root, NODISCARD_HEADER, 'local_outcome('), + at(root, NODISCARD_HEADER, 'local_alias('), at(root, NODISCARD_HEADER, 'kept_member'), + at(root, NODISCARD_HEADER, ' kept_declared();'), + at(root, NODISCARD_HEADER, 'member_local('), + at(root, NODISCARD_HEADER, 'holder::kept_declared'), + at(root, NODISCARD_HEADER, 'holder::dropped_declared'), at(root, NODISCARD_HEADER, 'commented_out'), at(root, NODISCARD_HEADER, 'constant_value'))) + # Those nine and nothing else of the header. + assert result.stdout.count(message) == 9, result.stdout[-6000:] def test_nodiscard_results_is_asked_for(root): diff --git a/tools/lint/rules.py b/tools/lint/rules.py index f358d49f..66a4e5d3 100755 --- a/tools/lint/rules.py +++ b/tools/lint/rules.py @@ -37,7 +37,9 @@ include-boundaries a library keeps to the include boundaries its own libs//meta/include-boundaries.json declares, when it has one; nodiscard-results a library whose libs//meta/lint.json asks for it declares every - function of its headers that returns boost::system::result [[nodiscard]]. + function of its headers that returns boost::system::result, or an alias + of it, [[nodiscard]]: a namespace's or a class's, not a local of a + function's body written with parentheses. """ from __future__ import annotations @@ -731,51 +733,338 @@ def include_boundaries(paths: list[str]) -> Iterator[Finding]: LINT_CONFIG_KEYS = frozenset({'nodiscard-results'}) -def results_without_nodiscard(path: str, text: str) -> Iterator[int]: - """The line of each function a C++ header declares returning boost::system::result<...> - (system::result<...> too) with no [[nodiscard]] among the words of its declaration before - the return type: back to the ;, { or } before it, or to an access specifier's colon. A - result that is a variable's type, a cast's or a constructor call's, has no name and a - parenthesis after the >, and is not read.""" +# The keys of a class head: what opens a class's scope, whose members are declarations. +CLASS_KEYS = frozenset({'class', 'struct', 'union'}) + +# The words of a class head between its key and its name. +CLASS_ATTRIBUTES = frozenset({'alignas', '__declspec', '__attribute__'}) + +# The words that may stand between a function's parameter list and its trailing return type. +FUNCTION_QUALIFIERS = frozenset({'const', 'volatile', 'noexcept', 'throw'}) + +# A word that is no function's name, though a parenthesis follows it. +NOT_A_NAME = frozenset({'operator', 'decltype', 'noexcept', 'alignas', 'requires', 'sizeof', + 'static_assert', 'throw'}) + + +def declaration_tokens(text: str) -> list[Token]: + """The tokens of the C++ text that the rule nodiscard-results reads: neither a comment nor + any token of a preprocessor directive, whose braces and parentheses open nothing, its lines + continued with a backslash too.""" tokens = [token for token in cpp_tokens(text) if not token[0].endswith('-comment')] - count = len(tokens) - for index, (kind, word, line) in enumerate(tokens): - qualified = (index >= 3 and tokens[index - 1][1] == ':' and tokens[index - 2][1] == ':' - and tokens[index - 3][1] == 'system') - if kind != 'word' or word != 'result' or not qualified: - continue - if index + 1 >= count or tokens[index + 1][1] != '<': - continue - depth, close = 0, index + 1 - while close < count: - depth += {'<': 1, '>': -1}.get(tokens[close][1], 0) + lines = text.splitlines() + first_of_line: dict[int, str] = {} + for _, token, line in tokens: + first_of_line.setdefault(line, token) + directive: set[int] = set() + for line, token in first_of_line.items(): + if token == '#': + while True: + directive.add(line) + if line > len(lines) or not lines[line - 1].endswith('\\'): + break + line += 1 + return [token for token in tokens if token[2] not in directive] + + +def closing_angle(tokens: list[Token], opening: int) -> int | None: + """The index of the > that closes the < at opening: < and > inside parentheses, and the > of + an ->, count for nothing, so that >> closes two. None when a ;, { or } comes first.""" + depth = parentheses = 0 + for index in range(opening, len(tokens)): + token = tokens[index][1] + if token in (';', '{', '}'): + return None + if token == '(': + parentheses += 1 + elif token == ')': + parentheses -= 1 + elif parentheses == 0 and token == '<': + depth += 1 + elif parentheses == 0 and token == '>' and tokens[index - 1][1] != '-': + depth -= 1 if depth == 0: + return index + return None + + +def is_scope(tokens: list[Token], index: int) -> bool: + """Whether the tokens at index are ::, a scope resolution.""" + return (index + 1 < len(tokens) and tokens[index][1] == ':' and tokens[index + 1][1] == ':') + + +def after_name(tokens: list[Token], index: int) -> tuple[int, bool, int]: + """Past the name that starts at index, qualified or not, each of its parts a word with its + template arguments, if any: the index after it, whether it was qualified, and the index of + its last word.""" + position, qualified, last = index, False, index + while position < len(tokens) and tokens[position][0] == 'word': + last = position + position += 1 + if position < len(tokens) and tokens[position][1] == '<': + close = closing_angle(tokens, position) + if close is None: break - close += 1 - name = close + 1 - if not (name + 1 < count and tokens[name][0] == 'word' and tokens[name][1] != 'operator' - and tokens[name + 1][1] == '('): + position = close + 1 + if not (is_scope(tokens, position) and position + 2 < len(tokens) + and tokens[position + 2][0] == 'word'): + break + position += 2 + qualified = True + return position, qualified, last + + +def is_class_head(head: list[Token]) -> bool: + """Whether head, the tokens before a {, is a class's: its last class, struct or union outside + angle brackets and parentheses, not an enum's, then its attributes, alignas(...) and export + macros, BOOST_SYMBOL_VISIBLE or WEBCPP_X_DECL(...), its name, final, and nothing but its base + clause before the {. A function that returns struct x * is not one, nor a variable + struct x y {...}.""" + key = None + angles = parentheses = 0 + for index, (_, token, _) in enumerate(head): + if token == '(': + parentheses += 1 + elif token == ')': + parentheses -= 1 + elif token == '<' and parentheses == 0: + angles += 1 + elif token == '>' and parentheses == 0 and angles > 0: + angles -= 1 + elif (token in CLASS_KEYS and angles == 0 and parentheses == 0 + and (index == 0 or head[index - 1][1] != 'enum')): + key = index + if key is None: + return False + position = key + 1 + while position < len(head): + token = head[position][1] + if token == '[' and position + 1 < len(head) and head[position + 1][1] == '[': + while position < len(head) and not (head[position][1] == ']' + and head[position - 1][1] == ']'): + position += 1 + position += 1 + elif (head[position][0] == 'word' and position + 1 < len(head) + and head[position + 1][0] == 'word' and head[position + 1][1] != 'final'): + position += 1 + elif ((token in CLASS_ATTRIBUTES or token.isupper()) and position + 1 < len(head) + and head[position + 1][1] == '('): + depth = 0 + position += 1 + while position < len(head): + depth += {'(': 1, ')': -1}.get(head[position][1], 0) + position += 1 + if depth == 0: + break + else: + break + position, _, _ = after_name(head, position) + if position < len(head) and head[position][1] == 'final': + position += 1 + # The name took any :: that qualifies it: a colon after it opens the base clause, whose first + # base may be ::qualified. + return position == len(head) or head[position][1] == ':' + + +def opens_declarations(tokens: list[Token], brace: int) -> bool: + """Whether the { at brace opens a scope whose statements are declarations: a namespace's, a + class's, a struct's, a union's, or an extern "C" block. A function's body, a lambda's, an + initializer, an enum and a requires expression do not.""" + start = brace + while start > 0 and tokens[start - 1][1] not in (';', '{', '}'): + start -= 1 + head = tokens[start:brace] + if any(token == 'namespace' for _, token, _ in head): + return True + if len(head) >= 2 and head[-2][1] == 'extern' and head[-1][0] == 'literal': + return True + return is_class_head(head) + + +def declaration_level(tokens: list[Token]) -> list[bool]: + """For each token, whether it stands where a namespace, a class or an extern "C" block + declares its members: inside no function body, lambda, initializer or enum, at any depth, and + inside no parenthesis opened in its scope, where a parameter is.""" + level: list[bool] = [] + scopes = [(True, 0)] + parentheses = 0 + for index, (_, token, _) in enumerate(tokens): + declares, base = scopes[-1] + level.append(declares and parentheses == base) + if token == '{': + scopes.append((declares and parentheses == base and opens_declarations(tokens, index), + parentheses)) + elif token == '}' and len(scopes) > 1: + scopes.pop() + elif token == '(': + parentheses += 1 + elif token == ')': + parentheses -= 1 + return level + + +def result_type(tokens: list[Token], index: int, aliases: dict[str, bool]) -> int | None: + """When the word at index names a boost::system::result: the index of the type's last token. + It is system::result<...>, qualified further or not, or the name of an alias of a result, + with its template arguments when the alias is a template's. None otherwise.""" + kind, word, _ = tokens[index] + if kind != 'word' or index > 0 and tokens[index - 1][1] == '.': + return None + templated = aliases.get(word) + named = (word == 'result' and index >= 3 and is_scope(tokens, index - 2) + and tokens[index - 3][1] == 'system') + if named: + templated = True + if templated is None: + return None + if not templated: + return index + if index + 1 < len(tokens) and tokens[index + 1][1] == '<': + return closing_angle(tokens, index + 1) + return None + + +def type_start(tokens: list[Token], index: int) -> int: + """The index of the first token of the qualified name whose last word is at index.""" + start = index + while start >= 2 and is_scope(tokens, start - 2): + start -= 2 + if start >= 1 and tokens[start - 1][0] == 'word': + start -= 1 + return start + + +def past_typename(tokens: list[Token], index: int) -> int: + """The index of the first word of the type that starts at index, past typename and a leading + ::.""" + while index < len(tokens) and tokens[index][1] in ('typename', ':'): + index += 1 + return index + + +def result_aliases(tokens: list[Token]) -> dict[str, bool]: + """The names that the tokens give boost::system::result, each with whether it takes template + arguments: an alias declaration's, using name = ...;, or a typedef's whose type is a result, + an alias of such an alias too; and result itself after using boost::system::result; or using + namespace boost::system;.""" + aliases: dict[str, bool] = {} + while True: + found = dict(aliases) + for index, (_, word, _) in enumerate(tokens[:-2]): + following = tokens[index + 1][1] + if word == 'using' and following != 'namespace' and tokens[index + 2][1] == '=': + position, _, last = after_name(tokens, past_typename(tokens, index + 3)) + if (result_type(tokens, last, found) == position - 1 and position < len(tokens) + and tokens[position][1] == ';'): + found[following] = index > 0 and tokens[index - 1][1] == '>' + elif word == 'using': + namespace = following == 'namespace' + position, _, _ = after_name(tokens, past_typename(tokens, index + 1 + namespace)) + named = [token for _, token, _ in tokens[index + 1:position]] + wanted = ['system'] if namespace else ['system', ':', ':', 'result'] + if (position < len(tokens) and tokens[position][1] == ';' + and named[-len(wanted):] == wanted): + found['result'] = True + elif word == 'typedef': + position, _, last = after_name(tokens, past_typename(tokens, index + 1)) + if (result_type(tokens, last, found) == position - 1 and position + 1 < len(tokens) + and tokens[position][0] == 'word' and tokens[position + 1][1] == ';'): + found[tokens[position][1]] = False + if found == aliases: + return aliases + aliases = found + + +def is_nodiscard(tokens: list[Token], before: int) -> bool: + """Whether [[nodiscard]] is among the tokens of the declaration that ends at before, back to + the ;, { or } before it, or to an access specifier's colon.""" + while before >= 0: + token = tokens[before][1] + if token in (';', '{', '}'): + return False + if token == ':' and not is_scope(tokens, before) and not ( + before > 0 and is_scope(tokens, before - 1)): + return False + if token == 'nodiscard': + return True + before -= 1 + return False + + +def trailing_name(tokens: list[Token], arrow: int) -> int | None: + """The index of the name of the function whose trailing return type follows the -> whose - + is at arrow, back over its qualifiers and noexcept(...) to its parameter list. None when no + plain name comes before the list: a lambda's, an operator's or a qualified name's.""" + position = arrow - 1 + while position >= 0: + token = tokens[position][1] + if token in FUNCTION_QUALIFIERS or token == '&': + position -= 1 continue - before = index - 4 - words: set[str] = set() - while before >= 0: - token = tokens[before][1] - if token in (';', '{', '}'): - break - if (token == ':' and tokens[before - 1][1] != ':' - and (before + 1 >= count or tokens[before + 1][1] != ':')): + if token != ')': + return None + depth = 0 + while position >= 0: + depth += {')': 1, '(': -1}.get(tokens[position][1], 0) + if depth == 0: break - words.add(token) - before -= 1 - if 'nodiscard' not in words: - yield line + position -= 1 + name = position - 1 + if name >= 0 and tokens[name][1] in ('noexcept', 'throw'): + position = name - 1 + continue + if (name < 0 or tokens[name][0] != 'word' or tokens[name][1] in NOT_A_NAME + or (name >= 2 and is_scope(tokens, name - 2))): + return None + return name + return None + + +def results_without_nodiscard(path: str, text: str, + aliases: dict[str, bool] | None = None) -> Iterator[int]: + """The line of the name of each function a C++ header declares returning a + boost::system::result, before its name or after it as a trailing return type, with no + [[nodiscard]] among the words of its declaration: back to the ;, { or } before it, or to an + access specifier's colon. The result is system::result<...>, or an alias of it: one of + aliases, else one the header declares. Only a namespace's, a class's and an extern "C" + block's declarations are read: a variable written T name(arguments); inside a function's body + is no declaration of a function. A qualified name, holder::member(...) or ns::function(...), + redeclares what its first declaration answers for, and is not read; nor is an operator, a + lambda or an explicit specialization, f(...). A result that is a variable's type, a + cast's or a constructor call's has no name and a parenthesis after it.""" + tokens = declaration_tokens(text) + if aliases is None: + aliases = result_aliases(tokens) + level = declaration_level(tokens) + for index in range(len(tokens)): + if not level[index]: + continue + end = result_type(tokens, index, aliases) + if end is None: + continue + start = type_start(tokens, index) + if start >= 2 and tokens[start - 1][1] == '>' and tokens[start - 2][1] == '-': + trailing = trailing_name(tokens, start - 2) + if trailing is None: + continue + name, declaration = trailing, trailing + else: + name = end + 1 + after, qualified, _ = after_name(tokens, name) + if (qualified or after != name + 1 or after >= len(tokens) + or tokens[name][1] in NOT_A_NAME or tokens[after][1] != '('): + continue + declaration = start + if not is_nodiscard(tokens, declaration - 1): + yield tokens[name][2] def nodiscard_results(paths: list[str]) -> Iterator[Finding]: """Each library of libs/ whose meta/lint.json holds "nodiscard-results", its reason, is held - to it: a function of its include/ headers that returns boost::system::result and is not - [[nodiscard]] fails at its line, with the reason. A malformed file, or an unknown key, fails - naming the file. A library without the file, or without the key, passes silently.""" + to it: a function of its include/ headers that returns boost::system::result, or an alias of + it any of them declares, and is not [[nodiscard]] fails at its line, with the reason. A + malformed file, or an unknown key, fails naming the file. A library without the file, or + without the key, passes silently.""" for config_path in sorted(paths): if not LINT_CONFIG.fullmatch(config_path): continue @@ -795,11 +1084,16 @@ def nodiscard_results(paths: list[str]) -> Iterator[Finding]: if why is None: continue prefix = config_path[:-len('meta/lint.json')] + 'include/' + headers: dict[str, str] = {} for path in sorted(paths): if path.startswith(prefix) and LIBRARY_HEADER.fullmatch(path): with open(path, encoding='utf-8', errors='replace') as file: - header = file.read() - for line in results_without_nodiscard(path, header): + headers[path] = file.read() + # An alias one header declares names a result in every header of the library. + aliases = result_aliases([token for header in headers.values() + for token in declaration_tokens(header)]) + for path, header in headers.items(): + for line in results_without_nodiscard(path, header, aliases): yield (path, line, f'a function returning boost::system::result without ' f'[[nodiscard]]: {why}') From 7e80974f7536c7a552ec696af0a0ea69503356d8 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 22:41:07 -0300 Subject: [PATCH 2/5] lint: nodiscard results skips a friend declaration without a body, which takes no attribute (clang refuses one, GCC ignores it) and which the function's first declaration answers for; a hidden friend defined in its class is still read The declaration's words are now read back from the result type itself, so a leading :: after friend no longer hides the friend: cobalt's pipe.hpp declares friend ::boost::system::result<...> pipe(...). lint_test plants a friend declaration, spared, and a hidden friend, reported. --- tools/lint/lint_test.py | 30 ++++++++++++++++++++-------- tools/lint/rules.py | 43 ++++++++++++++++++++++++++++++----------- 2 files changed, 54 insertions(+), 19 deletions(-) diff --git a/tools/lint/lint_test.py b/tools/lint/lint_test.py index 50e1cf8d..112f4ca0 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -2172,7 +2172,8 @@ def plant_results(root) -> None: of it or a trailing return type, with and without [[nodiscard]]; members declared in their class and defined out of it; and results that are no function's: locals written with parentheses in the bodies of functions and of members, a lambda's, a commented-out one and a - variable's type.""" + variable's type; a friend declaration, which takes no attribute, and the hidden friend + defined in the class, which does.""" write(root, NODISCARD_HEADER, CPP + '\n' '#ifndef WEBCPP_DEMO_RESULTS_HPP\n' '#define WEBCPP_DEMO_RESULTS_HPP\n' @@ -2244,8 +2245,17 @@ class and defined out of it; and results that are no function's: locals written ' return local_outcome.has_value() && local_alias.has_value() ? *local_outcome : 0;\n' '}\n' '\n' + 'class holder;\n' + '\n' + '[[nodiscard]] boost::system::result befriended(holder const& granting);\n' + '\n' 'class holder {\n' 'public:\n' + ' friend boost::system::result befriended(holder const& granting);\n' + '\n' + ' friend boost::system::result dropped_friend(holder const& /*granting*/) ' + '{ return 1; }\n' + '\n' ' [[nodiscard]] static boost::system::result kept_member() { return {}; }\n' '\n' ' [[nodiscard]] static boost::system::result kept_declared();\n' @@ -2292,10 +2302,12 @@ def test_nodiscard_results(root): # A library that asks for it in meta/lint.json declares each function returning a result # [[nodiscard]]: a free function, a template's, one whose result nests templates, one # returning an alias of a result, one with a trailing return type, a member after an access - # specifier, a member declared in its class, and one naming result after a using-declaration - # fail at their lines, with the library's reason. What is kept, a member's out-of-line - # definition, which its declaration answers for, a lambda, a local written with parentheses - # in a function's or a member's body, a comment and a variable's type do not. + # specifier, a member declared in its class, a hidden friend defined in its class, and one + # naming result after a using-declaration fail at their lines, with the library's reason. + # What is kept, a member's out-of-line definition and a friend declaration without a body, + # which the first declaration answers for and which take no attribute, a lambda, a local + # written with parentheses in a function's or a member's body, a comment and a variable's + # type do not. write(root, 'libs/demo/meta/lint.json', '{"nodiscard-results": "a dropped result is lost"}\n') plant_results(root) message = 'a function returning boost::system::result without [[nodiscard]]: ' @@ -2310,7 +2322,9 @@ def test_nodiscard_results(root): at(root, NODISCARD_HEADER, ' dropped_declared();') + ' ' + message, at(root, NODISCARD_HEADER, 'dropped_member') + ' ' + message, at(root, NODISCARD_HEADER, 'dropped_unqualified') + ' ' + message, - ], spared=(at(root, NODISCARD_HEADER, 'kept_free() noexcept'), + at(root, NODISCARD_HEADER, 'dropped_friend') + ' ' + message, + ], spared=(at(root, NODISCARD_HEADER, 'friend boost::system::result befriended'), + at(root, NODISCARD_HEADER, 'kept_free() noexcept'), at(root, NODISCARD_HEADER, 'kept_template'), at(root, NODISCARD_HEADER, 'kept_nested'), at(root, NODISCARD_HEADER, 'outcome kept_alias()'), @@ -2325,8 +2339,8 @@ def test_nodiscard_results(root): at(root, NODISCARD_HEADER, 'holder::dropped_declared'), at(root, NODISCARD_HEADER, 'commented_out'), at(root, NODISCARD_HEADER, 'constant_value'))) - # Those nine and nothing else of the header. - assert result.stdout.count(message) == 9, result.stdout[-6000:] + # Those ten and nothing else of the header. + assert result.stdout.count(message) == 10, result.stdout[-6000:] def test_nodiscard_results_is_asked_for(root): diff --git a/tools/lint/rules.py b/tools/lint/rules.py index 66a4e5d3..a81c587b 100755 --- a/tools/lint/rules.py +++ b/tools/lint/rules.py @@ -975,19 +975,31 @@ def result_aliases(tokens: list[Token]) -> dict[str, bool]: aliases = found -def is_nodiscard(tokens: list[Token], before: int) -> bool: - """Whether [[nodiscard]] is among the tokens of the declaration that ends at before, back to - the ;, { or } before it, or to an access specifier's colon.""" +def declaration_words(tokens: list[Token], before: int) -> set[str]: + """The tokens of the declaration that ends at before, back to the ;, { or } before it, or to + an access specifier's colon.""" + words: set[str] = set() while before >= 0: token = tokens[before][1] if token in (';', '{', '}'): - return False + break if token == ':' and not is_scope(tokens, before) and not ( before > 0 and is_scope(tokens, before - 1)): - return False - if token == 'nodiscard': - return True + break + words.add(token) before -= 1 + return words + + +def has_body(tokens: list[Token], parameters: int) -> bool: + """Whether the function whose parameter list opens at parameters is defined there: a { comes + after the list, its qualifiers and its trailing return type, before a ;.""" + depth = 0 + for index in range(parameters, len(tokens)): + token = tokens[index][1] + depth += {'(': 1, ')': -1}.get(token, 0) + if depth == 0 and token in (';', '{', '}'): + return token == '{' return False @@ -1029,8 +1041,9 @@ def results_without_nodiscard(path: str, text: str, aliases, else one the header declares. Only a namespace's, a class's and an extern "C" block's declarations are read: a variable written T name(arguments); inside a function's body is no declaration of a function. A qualified name, holder::member(...) or ns::function(...), - redeclares what its first declaration answers for, and is not read; nor is an operator, a - lambda or an explicit specialization, f(...). A result that is a variable's type, a + redeclares what its first declaration answers for, and is not read; nor is a friend + declaration without a body, which takes no attribute, an operator, a lambda or an explicit + specialization, f(...). A result that is a variable's type, a cast's or a constructor call's has no name and a parenthesis after it.""" tokens = declaration_tokens(text) if aliases is None: @@ -1054,8 +1067,16 @@ def results_without_nodiscard(path: str, text: str, if (qualified or after != name + 1 or after >= len(tokens) or tokens[name][1] in NOT_A_NAME or tokens[after][1] != '('): continue - declaration = start - if not is_nodiscard(tokens, declaration - 1): + # The walk back reads the type's own qualifiers too, and stops at none of them: a + # leading :: may follow a word that is no qualifier, friend ::boost::... + declaration = index + words = declaration_words(tokens, declaration - 1) + # A friend declaration without a body takes no attribute (clang refuses one, GCC + # ignores it): the function's first declaration answers for it. A friend defined in the + # class is its first declaration, and is read. + if 'friend' in words and not has_body(tokens, name + 1): + continue + if 'nodiscard' not in words: yield tokens[name][2] From 7e0abc81d0a25a6ffbaf911c79117dbcfa861987 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 20:54:02 -0300 Subject: [PATCH 3/5] CODING-GUIDELINES: asio, beast, cobalt, hash and trystero ask for the nodiscard results rule too --- CODING-GUIDELINES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 64fc8dde..973467e8 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -658,7 +658,7 @@ with `lint: failed: ` for each rule that failed. | bare throw | a `throw` expression in a library's public header (`libs/*/include/**`), outside comments and literals, at its line: inside `#ifndef WEBCPP__NO_EXCEPTIONS` too, in a template that nothing instantiates, which clang-tidy's analysis without exceptions does not see, and as a rethrow, `throw;`; `boost::throw_exception` is the one way to raise, `std::rethrow_exception` the one way to rethrow (above) | | changelog form | a library's changelog or a version's release notes out of `AGENTS.md` chapter 5's form: a section or a region missing or out of order, a line that starts with no verb of the list, a cross-reference, an inline anchor such as `[[nodiscard]]` outside a passthrough, more than ten lines for a library and a version, text outside a bullet | | canary pins | a `WEBCPP_CRYPTO__COMMIT` of crypto's `detail/canary.h` that is not the first seven digits of the commit the superproject records for its submodule (`ctaes`: `bitcoin`) | -| nodiscard results | a function of a library's `include/` that returns `boost::system::result` without `[[nodiscard]]`, at its line, when the library asks for the rule in its `meta/lint.json` (`"nodiscard-results"` and its reason; crypto and hash do): `boost::system::result` carries no `[[nodiscard]]` of its own; and a malformed file or an unknown key | +| nodiscard results | a function of a library's `include/` that returns `boost::system::result` without `[[nodiscard]]`, at its line, when the library asks for the rule in its `meta/lint.json` (`"nodiscard-results"` and its reason; asio, beast, cobalt, crypto, hash and trystero do): `boost::system::result` carries no `[[nodiscard]]` of its own; and a malformed file or an unknown key | A source b2 expects not to compile (`webcpp.compile-fail`), and one that must stop with the error it states (`webcpp.compile-diagnostic`), are left From b1477dfef1b73d334b5a67ca6c0e69c476284ddb Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 23:02:56 -0300 Subject: [PATCH 4/5] Jamroot: a GCC 15 that a user-config.jam configures compiles and runs tools/ci/actions/gcc/coroutine_probe.cpp before anything builds, once per compiler and run of b2, and one that fails it, as GCC 15.2 does (GCC PR121643), stops the build naming the compiler and GCC 15.3 --- AGENTS.md | 6 +++- CODING-GUIDELINES.md | 12 ++++--- Jamroot | 66 ++++++++++++++++++++++++++++++++++++++ doc/releases/0.1.0.adoc | 1 + tools/test/jamroot_test.py | 64 ++++++++++++++++++++++++++++++++++-- 5 files changed, 141 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a9ec98f5..b554b894 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -230,7 +230,11 @@ Jamroot is its build configuration, and `libs/` is its repository. - the GCC 15 CI lane uses pinned GCC 15.3, since the Ubuntu runner's GCC 15.2 has coroutine default-argument regression PR121643. Its action extracts the official Linux-X64 image's relocatable toolchain, verifies a compile/run probe - after installation and cache restoration, and selects its matching runtime; + after installation and cache restoration, and selects its matching runtime. + Locally, the Jamroot compiles and runs the same probe, + `tools/ci/actions/gcc/coroutine_probe.cpp`, with the GCC 15 a user-config.jam + configures, once per compiler and run of b2, and a GCC 15.2 stops the build + before it compiles anything, naming PR121643 and asking for GCC 15.3 or newer; - Python 3.9 or newer; - for WebAssembly: wasi-sdk 34 and wasmtime 50.0.1; - for WebAssembly components, such as wasi's: wit-bindgen 0.62.0, which diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 973467e8..0a04594f 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -7457,10 +7457,14 @@ GCC 15.2's default-argument `await_suspend` regression (GCC PR121643) prevents unmodified native Cobalt `race` applications from compiling. The GCC 15 CI lane therefore provisions GCC 15.3 from a pinned official image and validates an independent compile/run coroutine probe, including after cache restoration. -It does not change the native core or omit those tests. GCC 14's separate known -coroutine-allocation false positive (boostorg/cobalt#7) is scoped to the affected -test functions; the two immutable original application probes retain the warning -as nonfatal for GCC 14 alone. Consumers inherit no warning-suppression flags. +The lane does not change the native core or omit those tests. +A local build probes the GCC 15 its user-config.jam configures the same way: the +Jamroot's `gcc-probe` compiles and runs that probe once per compiler and run of b2, +and a compiler that fails it stops the build with a message naming PR121643 and +GCC 15.3, before a lane would end in internal compiler errors. GCC 14's separate +known coroutine-allocation false positive (boostorg/cobalt#7) is scoped to the +affected test functions; the two immutable original application probes retain the +warning as nonfatal for GCC 14 alone. Consumers inherit no warning-suppression flags. The 2026-11-07 report covers 12 original applications in 432 cells, keeping counterparts, unavailable facilities and upstream defects separate. Shared Release diff --git a/Jamroot b/Jamroot index dc98774e..43e7ca8e 100644 --- a/Jamroot +++ b/Jamroot @@ -10,6 +10,7 @@ # install, and lists the targets and the lanes the libraries declare # (declared-targets, declared-lanes). import boost ; +import common ; import errors ; import feature ; import modules ; @@ -18,6 +19,7 @@ import numbers ; import os ; import package ; import path ; +import property-set ; import toolset ; import type ; @@ -250,6 +252,68 @@ rule boost-check ( properties * ) } } +# GCC 15.2 crashes on an await_suspend that has a default argument, as +# unmodified Cobalt race code has (GCC PR121643, fixed in GCC 15.3). The CI +# installs GCC 15.3 and probes it (tools/ci/actions/gcc); a GCC 15 that a +# user-config.jam configures is probed here, once per compiler and run of b2: +# it compiles and runs the CI's probe, and a compiler that crashes on it, or +# builds a program that fails, stops the build before anything compiles, as +# a lane otherwise ends in internal compiler errors. Another GCC, or a build +# on Windows, is not probed. Not a check-target-builds: its answer, cached by +# properties, would outlive the compiler it measured. +rule gcc-probe ( properties * ) +{ + if gcc in $(properties) && ! off in $(properties) + && [ os.name ] != NT + { + local settings = [ toolset.set-target-variables-aux gcc + : [ property-set.create $(properties) ] ] ; + local command ; + while $(settings) + { + if $(settings[1]) = CONFIG_COMMAND + { + command += $(settings[2]) ; + } + settings = $(settings[3-]) ; + } + local compiler = $(command:J=" ") ; + command = [ common.make-command-string $(command) ] ; + if $(command) && ! $(.gcc-probed.$(command)) + { + .gcc-probed.$(command) = true ; + local version = [ SHELL "$(command) -dumpfullversion -dumpversion" + : strip-eol ] ; + if [ MATCH "^(15)\\." : $(version) ] + { + local probe = [ path.native [ path.join + [ path.root [ path.make $(WEBCPP_ROOT) ] [ path.pwd ] ] + tools/ci/actions/gcc/coroutine_probe.cpp ] ] ; + # The flags of install.py; the program goes to a directory + # of its own, removed as the shell exits. + local script = + "directory=`mktemp -d` && trap 'rm -rf \"$directory\"' EXIT &&" + "$(command) -std=c++20 -O0 -Wall -Wextra -Werror \"$(probe)\"" + "-o \"$directory/probe\" 2>&1 && \"$directory/probe\" 2>&1" ; + local result = [ SHELL $(script:J=" ") : exit-status ] ; + if $(result[2]) != 0 + { + local config = [ modules.binding user-config ] ; + config ?= user-config.jam ; + errors.user-error "GCC $(version) ($(compiler)) fails" + "tools/ci/actions/gcc/coroutine_probe.cpp, which every GCC 15" + "must compile and run: GCC PR121643, the await_suspend" + "default-argument regression of GCC 15.2, crashes it on" + "Cobalt's race. Configure GCC 15.3 or newer in $(config)" + "in its place, `using gcc : 15 : /path/to/g++-15 ;`." + "The probe printed:" + : $(result[1]) ; + } + } + } + } +} + project /webcpp : requirements 20 @@ -308,6 +372,8 @@ project /webcpp clang-wasip3,on:"-fwasm-exceptions -mllvm -wasm-use-legacy-eh=false" clang-wasip3,on:"-fwasm-exceptions -lunwind" # end::wasi-exceptions[] + # The compiler first: a broken one would fail Boost's check too. + @gcc-probe @boost-check : default-build debug : build-dir bin diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 0a0a9c06..cfd6753e 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -77,6 +77,7 @@ None. * Added tests of a missing /third_party// name, of the BIPs' pin and of Emscripten without a crypto backend. * Fixed BearSSL's entropy defines on a Windows target built by Clang or GCC. * Added the lint rule nodiscard results, which a library asks for in its meta/lint.json. +* Added a probe of a configured GCC 15, which stops a build on GCC 15.2 (GCC PR121643) and names GCC 15.3. * Changed the pages' tables to stack as on a phone when they do not fit, and long names in them to break between their parts. * Changed the pages' tables to keep names whole where they fit, and a table of eight columns or more to scroll rather than stack. * Added the role key-column, which keeps a table's first column wide enough for its words. diff --git a/tools/test/jamroot_test.py b/tools/test/jamroot_test.py index 75cbd6dc..3f5f54cc 100755 --- a/tools/test/jamroot_test.py +++ b/tools/test/jamroot_test.py @@ -7,9 +7,10 @@ """Checks the Jamroot: it finds the installed Boost and searches it first, refuses a missing or older one by naming the fix, refuses one whose version it cannot read, checks again when Boost -changes, keeps Boost's warnings out of -Werror, refuses CPATH, reaches third_party/ through both -of its project ids, and installs the headers. Each case builds a scratch superproject with the -fixture library demo. Run with the names of some cases to run only those.""" +changes, keeps Boost's warnings out of -Werror, refuses CPATH, refuses a GCC 15 that fails the +coroutine probe of GCC PR121643, reaches third_party/ through both of its project ids, and +installs the headers. Each case builds a scratch superproject with the fixture library demo. Run +with the names of some cases to run only those.""" from __future__ import annotations @@ -169,6 +170,60 @@ def test_cpath_set_is_refused(root): harness.expect(result, False, 'CPATH is set') +# A line of a user-config.jam that configures gcc. +USING_GCC_LINE = re.compile(r'^[ \t]*using[ \t]+gcc\b[^;]*;[ \t]*\n?', re.MULTILINE) + + +def fake_gcc(root, version): + """Configures, in place of any gcc of root's user-config.jam, `using gcc : 15` on a fake + g++-15 whose -dumpfullversion says version, and which crashes on every compilation as GCC + 15.2 crashes on tools/ci/actions/gcc/coroutine_probe.cpp (GCC PR121643). Returns its path.""" + compiler = root / 'fake gcc/g++-15' + compiler.parent.mkdir(exist_ok=True) + compiler.write_text( + '#!/bin/sh\n' + 'case "$1" in\n' + f' -dumpfullversion|-dumpversion) echo {version} ;;\n' + ' -dumpmachine) c++ -dumpmachine ;;\n' + ' -print-prog-name=*) echo "${1#-print-prog-name=}" ;;\n' + ' *) echo "probe.cpp:39:30: internal compiler error: in make_decl_rtl" >&2; exit 4 ;;\n' + 'esac\n') + compiler.chmod(0o755) + text = USING_GCC_LINE.sub('', harness.user_config(root).read_text()) + harness.configure(root, text + f'using gcc : 15 : "{compiler}" ;\n') + return compiler + + +def test_a_gcc_15_that_fails_the_coroutine_probe_is_refused(root): + # GCC 15.2 crashes on the await_suspend default argument of unmodified Cobalt race code (GCC + # PR121643). The build stops before it compiles anything, naming the compiler and the fix. + # The probe decides, not the version: a 15.3 that crashes is refused too. + for version in ('15.2.0', '15.3.0'): + compiler = fake_gcc(root, version) + result = harness.run_b2(root, 'toolset=gcc-15', 'libs/demo/test') + harness.expect(result, False, f'GCC {version}', str(compiler), 'GCC PR121643', + 'tools/ci/actions/gcc/coroutine_probe.cpp', 'internal compiler error', + 'GCC 15.3 or newer') + assert '**passed**' not in result.stdout, result.stdout[-4000:] + assert 'gcc.compile.c++' not in result.stdout, result.stdout[-4000:] + + +def test_a_gcc_other_than_15_is_not_probed(root): + # The probe guards GCC 15 alone: another GCC goes on to Boost's check, which the fake fails. + fake_gcc(root, '14.2.0') + result = harness.run_b2(root, 'toolset=gcc-15', 'libs/demo/test') + harness.expect(result, False, 'Boost 1.92.0 was found in') + assert 'PR121643' not in result.stdout, result.stdout[-4000:] + + +def test_a_working_gcc_passes_the_coroutine_probe(root): + # The gcc the checkout configures, GCC 15.3 where it is a GCC 15, builds; on a machine that + # configures none, as the CI's tools job, there is nothing to probe. + gcc = harness.gcc_request(root) + if gcc: + harness.expect(harness.run_b2(root, *gcc, 'libs/demo/test'), True, '**passed**') + + def test_a_relative_user_config_is_found(root): # WEBCPP_USER_CONFIG relative to the directory the tests run from, while b2 runs in root. shutil.rmtree(root / '.local', ignore_errors=True) @@ -246,6 +301,9 @@ def test_third_party_refuses_a_name_it_does_not_have(root): test_boost_warnings_are_not_ours, test_configured_boost_is_searched_first, test_cpath_set_is_refused, + test_a_gcc_15_that_fails_the_coroutine_probe_is_refused, + test_a_gcc_other_than_15_is_not_probed, + test_a_working_gcc_passes_the_coroutine_probe, test_a_relative_user_config_is_found, test_install_copies_headers_to_prefix, test_third_party_has_both_ids, From 8c7b886052ffa81a230c320cfa2e9842a0a10a9b Mon Sep 17 00:00:00 2001 From: R Date: Mon, 16 Nov 2026 02:42:57 -0300 Subject: [PATCH 5/5] libs/asio, libs/beast, libs/cobalt, libs/trystero: their nodiscard-results branches, which ask for the nodiscard results rule Each library's meta/lint.json asks for the rule, and every function of its include/ that returns boost::system::result is [[nodiscard]]: asio's make_tls_client_context, beast's set_server_name, cobalt's shipped Wasm backend and native SSL wrapper (declared so by upstream/sync.py), trystero's app::join. asio's branch stacks on fix/diagnostic-directives, trystero's on crypto/secp256k1, beast's and cobalt's on their main. --- libs/asio | 2 +- libs/beast | 2 +- libs/cobalt | 2 +- libs/trystero | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/libs/asio b/libs/asio index 9ff34177..3569dc42 160000 --- a/libs/asio +++ b/libs/asio @@ -1 +1 @@ -Subproject commit 9ff34177b9f9cf3a4d668c3acb71b89b5b6114c7 +Subproject commit 3569dc4276f871828c1e5ad397fe5c31ee9d6d85 diff --git a/libs/beast b/libs/beast index 6c53f854..0cfc0a50 160000 --- a/libs/beast +++ b/libs/beast @@ -1 +1 @@ -Subproject commit 6c53f854070a4eebd844f21c29692e938181f8f6 +Subproject commit 0cfc0a505597c55b1f6c9b3a96f48f94dd819114 diff --git a/libs/cobalt b/libs/cobalt index 79da1f68..a1a10204 160000 --- a/libs/cobalt +++ b/libs/cobalt @@ -1 +1 @@ -Subproject commit 79da1f6803df549aea8ddc7683d65ee459f3a6bc +Subproject commit a1a1020416cdf222e716374fba4f8451920f453b diff --git a/libs/trystero b/libs/trystero index 833bb3f1..6ff5416d 160000 --- a/libs/trystero +++ b/libs/trystero @@ -1 +1 @@ -Subproject commit 833bb3f182198b84a20fd431245bcb60e117dd81 +Subproject commit 6ff5416dbb5307263ddf407deb7f121c15d08754