Skip to content
Draft
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
96 changes: 94 additions & 2 deletions beman_tidy/lib/checks/beman_standard/cpp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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/<short_name>/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
Comment on lines +164 to +165
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)
Comment on lines +164 to +170
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
Comment on lines +178 to +179

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):
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

// Only include/beman/<library>/config.hpp is exempt, not nested config headers.
#if defined(__cpp_lib_three_way_comparison)
#define BEMAN_EXEMPLAR_DETAIL_USE_SPACESHIP 1
#endif
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#if __cpp_lib_print >= 202207L
int main() { return 0; }
#endif
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#ifdef __cpp_lib_execution
void use_execution();
#endif
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#ifndef __cpp_lib_jthread
void use_fallback_stop_token();
#endif
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

namespace beman::exemplar {
# if __cpp_concepts > 202002L
void use_concepts();
# endif
}
Original file line number Diff line number Diff line change
@@ -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(<beman/exemplar/config_generated.hpp>)
#include <beman/exemplar/config_generated.hpp>
#else
#include <version>
#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
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#ifndef USES_CONFIG_HPP
#define USES_CONFIG_HPP

#include <beman/my_lib/config.hpp>

#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
Original file line number Diff line number Diff line change
@@ -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
70 changes: 70 additions & 0 deletions tests/lib/checks/beman_standard/cpp/test_cpp.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
CppNamespaceCheck,
CppExtensionIdentifiersCheck,
CppMinStdVersionCheck,
CppNoFlagForkingCheck,
)

test_data_prefix = Path("tests/lib/checks/beman_standard/cpp/namespace")
Expand Down Expand Up @@ -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/<library>/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
Comment thread
neatudarius marked this conversation as resolved.
Resolved


def test__cpp_extension_identifiers__is_always_skipped(repo_info, beman_standard_check_config):
"""
Test that cpp.extension_identifiers is always skipped.
Expand Down
Loading