diff --git a/beman_tidy/lib/checks/beman_standard/cpp.py b/beman_tidy/lib/checks/beman_standard/cpp.py index c5019470..2e61a320 100644 --- a/beman_tidy/lib/checks/beman_standard/cpp.py +++ b/beman_tidy/lib/checks/beman_standard/cpp.py @@ -2,11 +2,13 @@ # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception import re +from pathlib import Path from beman_tidy.lib.checks.base.base_check import BaseCheck from beman_tidy.lib.checks.base.file_base_check import FileBaseCheck, BatchFileBaseCheck from beman_tidy.lib.checks.beman_standard.readme import ReadmeBaseCheck from beman_tidy.lib.checks.system.registry import register_beman_standard_check -from beman_tidy.lib.utils.file import get_beman_include_headers +from beman_tidy.lib.utils.comments import determine_comment_type +from beman_tidy.lib.utils.file import get_beman_include_headers, get_non_test_cpp_files from beman_tidy.lib.utils.string import normalize_path_for_display @register_beman_standard_check("cpp.namespace") @@ -104,7 +106,97 @@ def fix(self): return True -# TODO cpp.no_flag_forking +@register_beman_standard_check("cpp.no_flag_forking") +class CppNoFlagForkingCheck(BatchFileBaseCheck): + """ + [cpp.no_flag_forking] + Requirement: C++ preprocessing must produce identical output regardless of compiler flags. + Feature test macros such as __cpp_* must not be used directly in preprocessor conditionals. + + The library's own include/beman//config.hpp is exempt: the Beman Standard + designates it as the place that wraps config_generated.hpp and provides fallback + defaults for users who vendor the include/ directory. + """ + + # #if, #elif, #ifdef, #ifndef, #elifdef, #elifndef (C++23) + _CONDITIONAL_DIRECTIVE_RE = re.compile(r"^\s*#\s*(?:if|elif|ifdef|ifndef|elifdef|elifndef)\b") + _FEATURE_TEST_MACRO_RE = re.compile(r"\b__cpp_\w+") + _BLOCK_COMMENT_RE = re.compile(r"/\*.*?\*/") + # A block comment opened on the directive line and closed on a later line. + _UNTERMINATED_BLOCK_COMMENT_RE = re.compile(r"/\*.*$") + _LINE_COMMENT_RE = re.compile(r"//.*$") + + def __init__(self, repo_info, beman_standard_check_config): + super().__init__(repo_info, beman_standard_check_config) + self.file_check_class = self.CppNoFlagForkingCheckImpl + self.file_path_generator = get_non_test_cpp_files + + class CppNoFlagForkingCheckImpl(FileBaseCheck): + """ + Implementation of the "cpp.no_flag_forking" check for a single file. + """ + + def __init__(self, repo_info, beman_standard_check_config, relative_path): + super().__init__( + repo_info, beman_standard_check_config, relative_path, name="cpp.no_flag_forking" + ) + + def _is_config_header(self): + return self.relative_path == Path("include") / "beman" / self.short_name / "config.hpp" + + def _find_violations(self): + """ + Returns a list of (line_number, macro) for each conditional directive that uses a + __cpp_* feature test macro. Continuation lines are joined and comments are ignored. + """ + outer = CppNoFlagForkingCheck + lines = self.read_lines() + violations = [] + line_index = 0 + while line_index < len(lines): + start_index = line_index + directive = lines[line_index].rstrip("\n") + while directive.rstrip().endswith("\\") and line_index + 1 < len(lines): + line_index += 1 + directive = directive.rstrip()[:-1] + " " + lines[line_index].rstrip("\n") + line_index += 1 + + if not outer._CONDITIONAL_DIRECTIVE_RE.match(directive): + continue + if determine_comment_type(lines, start_index) is not None: + continue + + directive = outer._BLOCK_COMMENT_RE.sub(" ", directive) + directive = outer._LINE_COMMENT_RE.sub("", directive) + directive = outer._UNTERMINATED_BLOCK_COMMENT_RE.sub("", directive) + match = outer._FEATURE_TEST_MACRO_RE.search(directive) + if match: + violations.append((start_index + 1, match.group(0))) + return violations + + def check(self): + if self._is_config_header(): + return True + + display_path = normalize_path_for_display(self.path, self.repo_path) + violations = self._find_violations() + for line_number, macro in violations: + self.log( + f"Direct use of compiler feature-test macro {macro} in {display_path} at line {line_number}. " + f"Use CMake-detected config.hpp macros instead of __cpp_* in preprocessor conditionals. " + f"See https://github.com/bemanproject/beman/blob/main/docs/beman_standard.md#cppno_flag_forking" + ) + return not violations + + def fix(self): + display_path = normalize_path_for_display(self.path, self.repo_path) + self.log( + f"Please manually replace __cpp_* feature-test macros in {display_path} with " + f"CMake-detected config.hpp macros. " + f"See https://github.com/bemanproject/beman/blob/main/docs/beman_standard.md#cppno_flag_forking" + ) + return False + @register_beman_standard_check("cpp.min_std_version") class CppMinStdVersionCheck(ReadmeBaseCheck): diff --git a/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/compound/include/beman/exemplar/uses_compound.hpp b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/compound/include/beman/exemplar/uses_compound.hpp new file mode 100644 index 00000000..ba2ce68a --- /dev/null +++ b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/compound/include/beman/exemplar/uses_compound.hpp @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#if __cplusplus >= 202302L && __cpp_lib_ranges >= 202207L // P2494R2 +void use_ranges(); +#endif diff --git a/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/continuation/include/beman/exemplar/uses_continuation.hpp b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/continuation/include/beman/exemplar/uses_continuation.hpp new file mode 100644 index 00000000..1e83855d --- /dev/null +++ b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/continuation/include/beman/exemplar/uses_continuation.hpp @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#if defined(BEMAN_EXEMPLAR_USE_CONCEPTS) && \ + defined(__cpp_lib_ranges) +void use_ranges(); +#endif diff --git a/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/defined/include/beman/exemplar/uses_feature_test_macro.hpp b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/defined/include/beman/exemplar/uses_feature_test_macro.hpp new file mode 100644 index 00000000..09cbe2e3 --- /dev/null +++ b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/defined/include/beman/exemplar/uses_feature_test_macro.hpp @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#ifndef USES_FEATURE_TEST_MACRO_HPP +#define USES_FEATURE_TEST_MACRO_HPP + +#if defined(__cpp_explicit_this_parameter) +void use_deducing_this(); +#elif defined(__cpp_concepts) +void use_concepts(); +#else +#if __cpp_lib_format >= 201907L +void use_format(); +#endif +#endif + +#endif diff --git a/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/detail_config/include/beman/exemplar/detail/config.hpp b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/detail_config/include/beman/exemplar/detail/config.hpp new file mode 100644 index 00000000..a11f83f2 --- /dev/null +++ b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/detail_config/include/beman/exemplar/detail/config.hpp @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +// Only include/beman//config.hpp is exempt, not nested config headers. +#if defined(__cpp_lib_three_way_comparison) +#define BEMAN_EXEMPLAR_DETAIL_USE_SPACESHIP 1 +#endif diff --git a/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/elif_bare/include/beman/exemplar/uses_elif_bare_feature_test.hpp b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/elif_bare/include/beman/exemplar/uses_elif_bare_feature_test.hpp new file mode 100644 index 00000000..cb7c265f --- /dev/null +++ b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/elif_bare/include/beman/exemplar/uses_elif_bare_feature_test.hpp @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#ifndef USES_ELIF_BARE_FEATURE_TEST_HPP +#define USES_ELIF_BARE_FEATURE_TEST_HPP + +#if defined(BEMAN_MY_LIB_USE_DEDUCING_THIS) +void use_deducing_this(); +#elif __cpp_concepts +void use_concepts(); +#endif + +#endif diff --git a/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/elifdef/include/beman/exemplar/uses_elifdef.hpp b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/elifdef/include/beman/exemplar/uses_elifdef.hpp new file mode 100644 index 00000000..adcaac90 --- /dev/null +++ b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/elifdef/include/beman/exemplar/uses_elifdef.hpp @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#if defined(BEMAN_EXEMPLAR_USE_CONCEPTS) +void use_concepts(); +#elifdef __cpp_lib_ranges +void use_ranges(); +#endif diff --git a/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/example/examples/example.cpp b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/example/examples/example.cpp new file mode 100644 index 00000000..c0fb9b3e --- /dev/null +++ b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/example/examples/example.cpp @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#if __cpp_lib_print >= 202207L +int main() { return 0; } +#endif diff --git a/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/ifdef/include/beman/exemplar/uses_ifdef.hpp b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/ifdef/include/beman/exemplar/uses_ifdef.hpp new file mode 100644 index 00000000..907f1f7d --- /dev/null +++ b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/ifdef/include/beman/exemplar/uses_ifdef.hpp @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#ifdef __cpp_lib_execution +void use_execution(); +#endif diff --git a/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/ifndef/include/beman/exemplar/uses_ifndef.hpp b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/ifndef/include/beman/exemplar/uses_ifndef.hpp new file mode 100644 index 00000000..dc716604 --- /dev/null +++ b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/ifndef/include/beman/exemplar/uses_ifndef.hpp @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#ifndef __cpp_lib_jthread +void use_fallback_stop_token(); +#endif diff --git a/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/indented/include/beman/exemplar/uses_indented.hpp b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/indented/include/beman/exemplar/uses_indented.hpp new file mode 100644 index 00000000..cb2551de --- /dev/null +++ b/tests/lib/checks/beman_standard/cpp/no_flag_forking/invalid/indented/include/beman/exemplar/uses_indented.hpp @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +namespace beman::exemplar { + # if __cpp_concepts > 202002L + void use_concepts(); + # endif +} diff --git a/tests/lib/checks/beman_standard/cpp/no_flag_forking/valid/include/beman/exemplar/config.hpp b/tests/lib/checks/beman_standard/cpp/no_flag_forking/valid/include/beman/exemplar/config.hpp new file mode 100644 index 00000000..dd9c075f --- /dev/null +++ b/tests/lib/checks/beman_standard/cpp/no_flag_forking/valid/include/beman/exemplar/config.hpp @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +#ifndef BEMAN_EXEMPLAR_CONFIG_HPP +#define BEMAN_EXEMPLAR_CONFIG_HPP + +// The library's config.hpp may probe feature test macros in its fallback for users +// who vendor the include/ directory without config_generated.hpp. +#if !defined(__has_include) || __has_include() + #include +#else + #include + #if defined(__cpp_explicit_this_parameter) && __cpp_explicit_this_parameter >= 202110L + #define BEMAN_EXEMPLAR_USE_DEDUCING_THIS() 1 + #else + #define BEMAN_EXEMPLAR_USE_DEDUCING_THIS() 0 + #endif +#endif + +#endif diff --git a/tests/lib/checks/beman_standard/cpp/no_flag_forking/valid/include/beman/exemplar/uses_config.hpp b/tests/lib/checks/beman_standard/cpp/no_flag_forking/valid/include/beman/exemplar/uses_config.hpp new file mode 100644 index 00000000..6f17ddc6 --- /dev/null +++ b/tests/lib/checks/beman_standard/cpp/no_flag_forking/valid/include/beman/exemplar/uses_config.hpp @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#ifndef USES_CONFIG_HPP +#define USES_CONFIG_HPP + +#include + +#if BEMAN_MY_LIB_USE_DEDUCING_THIS +void use_deducing_this(); +#endif + +// Do not flag __cpp_* mentions in comments, e.g. __cpp_explicit_this_parameter +/* +#if __cpp_concepts +#endif +*/ + +#if BEMAN_MY_LIB_USE_RANGES // replaces __cpp_lib_ranges +void use_ranges(); +#endif + +#if BEMAN_MY_LIB_USE_FORMAT /* replaces __cpp_lib_format */ +void use_format(); +#endif + +// Identifiers that merely contain __cpp_ are not feature test macros. +#if 202207 <= disabled__cpp_lib_forward_like +void use_forward_like(); +#endif + +#if __cplusplus >= 202002L +void use_cpp20(); +#endif + +inline constexpr const char* ftm_name = "__cpp_concepts"; + +#if BEMAN_MY_LIB_USE_CONCEPTS /* replaces __cpp_concepts, + see config.hpp */ +void use_concepts(); +#endif + +// Other predefined macros and operators that merely contain "cpp" are fine. +#if defined(__has_cpp_attribute) && __has_cpp_attribute(nodiscard) +void use_nodiscard(); +#endif + +#endif diff --git a/tests/lib/checks/beman_standard/cpp/no_flag_forking/valid/tests/beman/exemplar/uses_feature_test_macro.test.cpp b/tests/lib/checks/beman_standard/cpp/no_flag_forking/valid/tests/beman/exemplar/uses_feature_test_macro.test.cpp new file mode 100644 index 00000000..84922c02 --- /dev/null +++ b/tests/lib/checks/beman_standard/cpp/no_flag_forking/valid/tests/beman/exemplar/uses_feature_test_macro.test.cpp @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// Test code is out of scope for cpp.no_flag_forking. +#if __cpp_lib_format >= 201907L +int main() { return 0; } +#endif diff --git a/tests/lib/checks/beman_standard/cpp/test_cpp.py b/tests/lib/checks/beman_standard/cpp/test_cpp.py index eeec0040..4311174f 100644 --- a/tests/lib/checks/beman_standard/cpp/test_cpp.py +++ b/tests/lib/checks/beman_standard/cpp/test_cpp.py @@ -9,6 +9,7 @@ CppNamespaceCheck, CppExtensionIdentifiersCheck, CppMinStdVersionCheck, + CppNoFlagForkingCheck, ) test_data_prefix = Path("tests/lib/checks/beman_standard/cpp/namespace") @@ -44,6 +45,75 @@ def test__cpp_namespace__fix_inplace(repo_info, beman_standard_check_config, tmp assert check.check() is True +no_flag_forking_prefix = Path("tests/lib/checks/beman_standard/cpp/no_flag_forking") +no_flag_forking_valid_prefix = no_flag_forking_prefix / "valid" +no_flag_forking_invalid_prefix = no_flag_forking_prefix / "invalid" + + +def test__cpp_no_flag_forking__valid(repo_info, beman_standard_check_config): + """ + Test that headers using config.hpp macros pass, that __cpp_* in comments, strings, tests/ + and in the library's own include/beman//config.hpp fallback is not flagged. + """ + repo_info["top_level"] = no_flag_forking_valid_prefix + + check = CppNoFlagForkingCheck(repo_info, beman_standard_check_config) + assert check.check() is True + + # The config.hpp exemption is per library: another library's config.hpp is not exempt. + repo_info["short_name"] = "other_library" + check = CppNoFlagForkingCheck(repo_info, beman_standard_check_config) + assert check.check() is False + + +@pytest.mark.parametrize( + "case, expected_violations", + [ + # #if defined(__cpp_...), #elif defined(__cpp_...), #if __cpp_... >= N: all reported + ( + "defined", + [ + (6, "__cpp_explicit_this_parameter"), + (8, "__cpp_concepts"), + (11, "__cpp_lib_format"), + ], + ), + ("elif_bare", [(8, "__cpp_concepts")]), # #elif __cpp_... + ("ifdef", [(3, "__cpp_lib_execution")]), # #ifdef __cpp_... + ("ifndef", [(3, "__cpp_lib_jthread")]), # #ifndef __cpp_... + ("elifdef", [(5, "__cpp_lib_ranges")]), # #elifdef __cpp_... (C++23) + ("compound", [(3, "__cpp_lib_ranges")]), # #if __cplusplus >= N && __cpp_... // comment + ("continuation", [(3, "__cpp_lib_ranges")]), # __cpp_... on a continuation line + ("indented", [(4, "__cpp_concepts")]), # indented directive with space after '#' + ("detail_config", [(4, "__cpp_lib_three_way_comparison")]), # nested config.hpp + ("example", [(3, "__cpp_lib_print")]), # examples/ are in scope + ], +) +def test__cpp_no_flag_forking__invalid( + repo_info, beman_standard_check_config, case, expected_violations +): + """ + Test that each way of using a __cpp_* feature test macro in a preprocessor conditional fails, + and that every offending directive is reported with its line number. + """ + case_prefix = no_flag_forking_invalid_prefix / case + repo_info["top_level"] = case_prefix + + check = CppNoFlagForkingCheck(repo_info, beman_standard_check_config) + assert check.check() is False + + (relative_path,) = [p.relative_to(case_prefix) for p in case_prefix.rglob("*") if p.is_file()] + file_check = CppNoFlagForkingCheck.CppNoFlagForkingCheckImpl( + repo_info, beman_standard_check_config, relative_path + ) + assert file_check._find_violations() == expected_violations + + +@pytest.mark.skip(reason="not implemented") +def test__cpp_no_flag_forking__fix_inplace(repo_info, beman_standard_check_config): + pass + + def test__cpp_extension_identifiers__is_always_skipped(repo_info, beman_standard_check_config): """ Test that cpp.extension_identifiers is always skipped.