From 51cbff36f0073275c831e1737310b19da2a4517a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Darius=20Nea=C8=9Bu?= Date: Wed, 15 Jul 2026 21:04:59 +0300 Subject: [PATCH 1/3] [beman-tidy] Implement cmake.passive_projects check (#78) --- beman_tidy/lib/checks/beman_standard/cmake.py | 70 ++++++++++++++++++- beman_tidy/lib/utils/file.py | 27 +++++++ .../CMakeLists.txt | 9 +++ .../CMakeLists.txt | 9 +++ .../CMakeLists.txt | 9 +++ .../valid/passive_projects-v1/CMakeLists.txt | 18 +++++ .../valid/passive_projects-v2/CMakeLists.txt | 11 +++ .../valid/passive_projects-v3/CMakeLists.txt | 9 +++ .../infra/cmake/toolchain.cmake | 5 ++ .../checks/beman_standard/cmake/test_cmake.py | 50 +++++++++++++ 10 files changed, 214 insertions(+), 3 deletions(-) create mode 100644 tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v1/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v2/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v3/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v1/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v2/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v3/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v3/infra/cmake/toolchain.cmake diff --git a/beman_tidy/lib/checks/beman_standard/cmake.py b/beman_tidy/lib/checks/beman_standard/cmake.py index e8823c68..2cd3e98f 100644 --- a/beman_tidy/lib/checks/beman_standard/cmake.py +++ b/beman_tidy/lib/checks/beman_standard/cmake.py @@ -4,6 +4,11 @@ from abc import ABC from collections.abc import Iterable +import re +from ..base.base_check import BaseCheck +from ...utils.config import get_ignores +from ...utils.file import get_cmake_files + import cmake_parser from cmake_parser.ast import AstNode, Command @@ -160,9 +165,6 @@ def fix(self): return False -# TODO cmake.passive_projects - - @register_beman_standard_check("cmake.library_name") class CMakeLibraryNameCheck(CMakeBaseCheck): def __init__(self, repo_info, beman_standard_check_config): @@ -282,6 +284,68 @@ def fix(self): return False +@register_beman_standard_check("cmake.passive_projects") +class CMakePassiveProjectsCheck(BaseCheck): + """ + [cmake.passive_projects] + Requirement: CMake projects must not adjust user-specified compilation flags. + """ + + _COMMENT_RE = re.compile(r"#[^\n]*") + _FORBIDDEN_SET_PATTERNS = ( + (re.compile(r"set\s*\(\s*CMAKE_CXX_FLAGS\b", re.IGNORECASE), "CMAKE_CXX_FLAGS"), + (re.compile(r"set\s*\(\s*CMAKE_CXX_STANDARD\b", re.IGNORECASE), "CMAKE_CXX_STANDARD"), + ( + re.compile(r"set\s*\(\s*CMAKE_CXX_STANDARD_REQUIRED\b", re.IGNORECASE), + "CMAKE_CXX_STANDARD_REQUIRED", + ), + ) + + def _get_cmake_ignores(self): + ignores = list(get_ignores(self.repo_info)) + if "infra/" not in ignores: + ignores.append("infra/") + return ignores + + def _read_cmake_files(self): + ignores = self._get_cmake_ignores() + result = {} + for rel_path in get_cmake_files(self.repo_path, ignores=ignores): + abs_path = self.repo_path / rel_path + try: + content = abs_path.read_text(encoding="utf-8", errors="ignore") + result[rel_path] = self._COMMENT_RE.sub("", content) + except OSError: + pass + return result + + def check(self): + cmake_files = self._read_cmake_files() + all_passed = True + + for rel_path, content in cmake_files.items(): + for pattern, variable_name in self._FORBIDDEN_SET_PATTERNS: + if pattern.search(content): + self.log( + f"{rel_path}: CMake must not set {variable_name}; " + "this overrides user compilation flags. " + "Please update CMake files according to the Beman Standard. " + "See https://github.com/bemanproject/beman/blob/main/docs/beman_standard.md#cmakepassive_projects " + "for more information." + ) + all_passed = False + + return all_passed + + def fix(self): + self.log( + "Please remove set(CMAKE_CXX_FLAGS), set(CMAKE_CXX_STANDARD), and " + "set(CMAKE_CXX_STANDARD_REQUIRED) from CMake files. " + "See https://github.com/bemanproject/beman/blob/main/docs/beman_standard.md#cmakepassive_projects " + "for more information." + ) + return False + # TODO cmake.passive_targets diff --git a/beman_tidy/lib/utils/file.py b/beman_tidy/lib/utils/file.py index ab6461df..6264cb3f 100644 --- a/beman_tidy/lib/utils/file.py +++ b/beman_tidy/lib/utils/file.py @@ -106,6 +106,33 @@ def get_non_test_cpp_files(repo_path, ignores=None): return non_test_files +def get_cmake_files(repo_path, ignores=None): + """ + Get all CMake files (CMakeLists.txt and *.cmake) in the repository. + """ + if ignores is None: + ignores = get_repo_ignorable_subdirectories() + + matched_files = [] + repo_path = Path(repo_path) + + for root, dirs, files in os.walk(repo_path): + rel_root = Path(root).relative_to(repo_path) + + for d in list(dirs): + d_path = rel_root / d + if _is_ignored(d_path, ignores): + dirs.remove(d) + + for f in files: + f_path = rel_root / f + if f_path.suffix == ".cmake" or f_path.name == "CMakeLists.txt": + if not _is_ignored(f_path, ignores): + matched_files.append(f_path) + + return sorted(list(set(matched_files))) + + def get_beman_include_headers(repo_path, ignores=None): """ Get all header files in the repository under an include/beman directory. diff --git a/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v1/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v1/CMakeLists.txt new file mode 100644 index 00000000..d29cbbe2 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v1/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 20) + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v2/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v2/CMakeLists.txt new file mode 100644 index 00000000..8b7cecce --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v2/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +set(CMAKE_CXX_FLAGS "-Wall") + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v3/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v3/CMakeLists.txt new file mode 100644 index 00000000..5a93d2b9 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v3/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v1/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v1/CMakeLists.txt new file mode 100644 index 00000000..9f500878 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v1/CMakeLists.txt @@ -0,0 +1,18 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project( + beman.exemplar + DESCRIPTION "A Beman Library Exemplar" + LANGUAGES CXX + VERSION 0.1.0 +) + +add_library(beman.exemplar INTERFACE) +add_library(beman::exemplar ALIAS beman.exemplar) + +target_sources( + beman.exemplar + PUBLIC FILE_SET HEADERS BASE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/include" +) diff --git a/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v2/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v2/CMakeLists.txt new file mode 100644 index 00000000..21f40106 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v2/CMakeLists.txt @@ -0,0 +1,11 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +# set(CMAKE_CXX_STANDARD 20) +# set(CMAKE_CXX_FLAGS "-Wall") +# set(CMAKE_CXX_STANDARD_REQUIRED ON) + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v3/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v3/CMakeLists.txt new file mode 100644 index 00000000..5e8a7caf --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v3/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +include(infra/cmake/toolchain.cmake) + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v3/infra/cmake/toolchain.cmake b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v3/infra/cmake/toolchain.cmake new file mode 100644 index 00000000..70505f60 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v3/infra/cmake/toolchain.cmake @@ -0,0 +1,5 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_FLAGS "-Wall") +set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/tests/lib/checks/beman_standard/cmake/test_cmake.py b/tests/lib/checks/beman_standard/cmake/test_cmake.py index 2af61d81..6cf6aaa0 100644 --- a/tests/lib/checks/beman_standard/cmake/test_cmake.py +++ b/tests/lib/checks/beman_standard/cmake/test_cmake.py @@ -14,6 +14,7 @@ CMakeLibraryNameCheck, CMakeLibraryAliasCheck, CMakeTargetNamesCheck, + CMakePassiveProjectsCheck, ) test_data_prefix = "tests/lib/checks/beman_standard/cmake/data" @@ -215,3 +216,52 @@ def test__cmake_target_names__fix_inplace(repo_info, beman_standard_check_config Note: Skipping this test as it is not implemented. """ pass + + +def test__cmake_passive_projects__valid(repo_info, beman_standard_check_config): + """ + Test that CMake files without forbidden project-level flags pass. + Fixtures under infra/ are excluded from this check. + """ + valid_cmake_paths = [ + Path(f"{valid_prefix}/passive_projects-v1"), + Path(f"{valid_prefix}/passive_projects-v2"), + Path(f"{valid_prefix}/passive_projects-v3"), + ] + + run_check_for_each_path( + True, + valid_cmake_paths, + CMakePassiveProjectsCheck, + repo_info, + beman_standard_check_config, + ) + + +def test__cmake_passive_projects__invalid(repo_info, beman_standard_check_config): + """ + Test that CMake files setting project-level compilation flags fail. + """ + invalid_cmake_paths = [ + Path(f"{invalid_prefix}/invalid-passive_projects-v1"), + Path(f"{invalid_prefix}/invalid-passive_projects-v2"), + Path(f"{invalid_prefix}/invalid-passive_projects-v3"), + ] + + run_check_for_each_path( + False, + invalid_cmake_paths, + CMakePassiveProjectsCheck, + repo_info, + beman_standard_check_config, + ) + + +def test__cmake_passive_projects__fix_inplace(repo_info, beman_standard_check_config): + """ + Test that fix() is not auto-applicable for passive_projects violations. + """ + repo_info["top_level"] = Path(f"{invalid_prefix}/invalid-passive_projects-v1") + check = CMakePassiveProjectsCheck(repo_info, beman_standard_check_config) + assert check.check() is False + assert check.fix() is False From a73df981d5eca8209cba3cde87a73e5e4c0b0691 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Darius=20Nea=C8=9Bu?= Date: Thu, 19 Nov 2026 00:13:49 +0200 Subject: [PATCH 2/3] [beman-tidy] Skip toolchains and defaults in cmake.passive_projects Parse CMake files instead of regex matching. Skip toolchain files and the files they include, and set() calls guarded by if(NOT DEFINED ). Report file:line. Exempt toolchains by name instead of all of infra/. --- beman_tidy/lib/checks/beman_standard/cmake.py | 147 ++++++++++++++---- beman_tidy/lib/utils/file.py | 33 ++-- .../CMakeLists.txt | 7 + .../examples/CMakeLists.txt | 9 ++ .../CMakeLists.txt | 9 ++ .../cmake/flags.cmake | 4 + .../CMakeLists.txt | 13 ++ .../valid/passive_projects-v4/CMakeLists.txt | 7 + .../passive_projects-v4/etc/gcc-flags.cmake | 5 + .../etc/gcc-toolchain.cmake | 6 + .../valid/passive_projects-v5/CMakeLists.txt | 12 ++ .../checks/beman_standard/cmake/test_cmake.py | 32 +++- 12 files changed, 225 insertions(+), 59 deletions(-) create mode 100644 tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v4/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v4/examples/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v5/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v5/cmake/flags.cmake create mode 100644 tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v6/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v4/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v4/etc/gcc-flags.cmake create mode 100644 tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v4/etc/gcc-toolchain.cmake create mode 100644 tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v5/CMakeLists.txt diff --git a/beman_tidy/lib/checks/beman_standard/cmake.py b/beman_tidy/lib/checks/beman_standard/cmake.py index e285517e..4c3bc499 100644 --- a/beman_tidy/lib/checks/beman_standard/cmake.py +++ b/beman_tidy/lib/checks/beman_standard/cmake.py @@ -4,13 +4,15 @@ from abc import ABC from collections.abc import Iterable +import os import re +from pathlib import Path from ..base.base_check import BaseCheck from ...utils.config import get_ignore_matcher from ...utils.file import get_cmake_files import cmake_parser -from cmake_parser.ast import AstNode, Command, If, Option +from cmake_parser.ast import AstNode, Command, If, Include, Option, Set from beman_tidy.lib.utils.cmake import ( cmake_build_skip_subdir_option_pattern, @@ -376,47 +378,123 @@ class CMakePassiveProjectsCheck(BaseCheck): """ [cmake.passive_projects] Requirement: CMake projects must not adjust user-specified compilation flags. + + Flags set() in toolchain files (and in the files they include) are user + settings, so they are not reported. Neither is a default set only when the + user did not provide one, i.e. inside if(NOT DEFINED ). """ - _COMMENT_RE = re.compile(r"#[^\n]*") - _FORBIDDEN_SET_PATTERNS = ( - (re.compile(r"set\s*\(\s*CMAKE_CXX_FLAGS\b", re.IGNORECASE), "CMAKE_CXX_FLAGS"), - (re.compile(r"set\s*\(\s*CMAKE_CXX_STANDARD\b", re.IGNORECASE), "CMAKE_CXX_STANDARD"), - ( - re.compile(r"set\s*\(\s*CMAKE_CXX_STANDARD_REQUIRED\b", re.IGNORECASE), - "CMAKE_CXX_STANDARD_REQUIRED", - ), + _FORBIDDEN_VARIABLES = ( + "CMAKE_CXX_FLAGS", + "CMAKE_CXX_STANDARD", + "CMAKE_CXX_STANDARD_REQUIRED", ) + _TOOLCHAIN_NAME_RE = re.compile(r"toolchain", re.IGNORECASE) + _CURRENT_LIST_DIR_RE = re.compile(r"\$\{CMAKE_CURRENT_LIST_DIR\}/?") - def _read_cmake_files(self): + def _get_cmake_files(self): ignores = get_ignore_matcher(self.repo_info) - result = {} - for rel_path in get_cmake_files(self.repo_path, ignores=ignores): - if rel_path.parts and rel_path.parts[0] == "infra": - continue - abs_path = self.repo_path / rel_path - try: - content = abs_path.read_text(encoding="utf-8", errors="ignore") - result[rel_path] = self._COMMENT_RE.sub("", content) - except OSError: - pass - return result + return get_cmake_files(self.repo_path, ignores=ignores) + + def _parse(self, rel_path): + """ + Returns the parse tree of a CMake file, or None if it cannot be read or parsed. + """ + try: + content = (self.repo_path / rel_path).read_text( + encoding="utf-8", errors="ignore" + ) + return list(cmake_parser.parser.parse_tree(content, skip_comments=True)) + except Exception as e: + self.log(f"{rel_path}: cannot parse CMake file, skipping it ({e}).") + return None + + @classmethod + def _walk(cls, nodes): + for node in nodes or []: + yield node + if isinstance(node, If): + yield from cls._walk(node.if_true) + yield from cls._walk(node.if_false) + else: + yield from cls._walk(getattr(node, "body", None)) + + def _get_toolchain_files(self, cmake_files, trees): + """ + Returns the toolchain files: files named like a toolchain and the CMake + files they include, transitively. + """ + known = set(cmake_files) + toolchains = {p for p in cmake_files if self._TOOLCHAIN_NAME_RE.search(p.name)} + pending = list(toolchains) + while pending: + current = pending.pop() + for node in self._walk(trees.get(current)): + if not isinstance(node, Include) or not node.args: + continue + target = self._CURRENT_LIST_DIR_RE.sub("", node.args[0].value) + if "${" in target: + continue + included = Path(os.path.normpath(current.parent / target)) + if included in known and included not in toolchains: + toolchains.add(included) + pending.append(included) + return toolchains + + @staticmethod + def _is_default_guard(if_args, variable): + """ + True for if(NOT DEFINED ), which only sets a default. + """ + values = [arg.value.upper() for arg in if_args or []] + return values == ["NOT", "DEFINED", variable] + + @classmethod + def _find_forbidden_sets(cls, nodes, defaulted=frozenset()): + """ + Yields (line, variable) for each set() of a forbidden variable that + overrides the user's value. + """ + for node in nodes or []: + is_set = isinstance(node, Set) or ( + isinstance(node, Command) and node.identifier.lower() == "set" + ) + if is_set: + if node.args: + variable = node.args[0].value + if variable in cls._FORBIDDEN_VARIABLES and variable not in defaulted: + yield node.line, variable + elif isinstance(node, If): + guarded = { + v for v in cls._FORBIDDEN_VARIABLES if cls._is_default_guard(node.args, v) + } + yield from cls._find_forbidden_sets(node.if_true, defaulted | guarded) + yield from cls._find_forbidden_sets(node.if_false, defaulted) + else: + yield from cls._find_forbidden_sets(getattr(node, "body", None), defaulted) def check(self): - cmake_files = self._read_cmake_files() - all_passed = True + cmake_files = self._get_cmake_files() + trees = {} + for rel_path in cmake_files: + tree = self._parse(rel_path) + if tree is not None: + trees[rel_path] = tree + toolchains = self._get_toolchain_files(cmake_files, trees) - for rel_path, content in cmake_files.items(): - for pattern, variable_name in self._FORBIDDEN_SET_PATTERNS: - if pattern.search(content): - self.log( - f"{rel_path}: CMake must not set {variable_name}; " - "this overrides user compilation flags. " - "Please update CMake files according to the Beman Standard. " - "See https://github.com/bemanproject/beman/blob/main/docs/beman_standard.md#cmakepassive_projects " - "for more information." - ) - all_passed = False + all_passed = True + for rel_path, tree in trees.items(): + if rel_path in toolchains: + continue + for line, variable in self._find_forbidden_sets(tree): + self.log( + f"{rel_path}:{line}: CMake must not set {variable}; " + "this overrides user compilation flags. " + "Please update CMake files according to the Beman Standard. " + "See https://github.com/bemanproject/beman/blob/main/docs/beman_standard.md#cmakepassive_projects " + "for more information." + ) + all_passed = False return all_passed @@ -429,6 +507,7 @@ def fix(self): ) return False + # TODO cmake.passive_targets diff --git a/beman_tidy/lib/utils/file.py b/beman_tidy/lib/utils/file.py index 792145aa..00f9ce6b 100644 --- a/beman_tidy/lib/utils/file.py +++ b/beman_tidy/lib/utils/file.py @@ -96,24 +96,10 @@ def get_cpp_files(repo_path, ignores=None): return get_matched_paths(repo_path, get_cpp_extensions(), ignores=ignores) -def get_non_test_cpp_files(repo_path, ignores=None): - """ - Get all C++ source and header files NOT under a tests/ directory. - """ - all_files = get_cpp_files(repo_path, ignores=ignores) - - non_test_files = [] - for path in all_files: - if "tests" not in path.parts: - non_test_files.append(path) - - return non_test_files - - def get_cmake_files(repo_path, ignores=None): """ Get all CMake files (CMakeLists.txt and *.cmake) in the repository. - Ignores paths specified in 'ignores'. + Ignores paths specified in 'ignores' (an IgnoreMatcher or patterns). """ repo_path = Path(repo_path) matcher = _as_matcher(ignores, repo_path) @@ -124,8 +110,7 @@ def get_cmake_files(repo_path, ignores=None): rel_root = Path(root).relative_to(repo_path) for d in list(dirs): - d_path = rel_root / d - if matcher.is_ignored(d_path, is_dir=True): + if matcher.is_ignored(rel_root / d, is_dir=True): dirs.remove(d) for f in files: @@ -137,6 +122,20 @@ def get_cmake_files(repo_path, ignores=None): return sorted(set(matched_files)) +def get_non_test_cpp_files(repo_path, ignores=None): + """ + Get all C++ source and header files NOT under a tests/ directory. + """ + all_files = get_cpp_files(repo_path, ignores=ignores) + + non_test_files = [] + for path in all_files: + if "tests" not in path.parts: + non_test_files.append(path) + + return non_test_files + + def get_beman_include_headers(repo_path, ignores=None): """ Get all header files in the repository under an include/beman directory. diff --git a/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v4/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v4/CMakeLists.txt new file mode 100644 index 00000000..be211cc7 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v4/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v4/examples/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v4/examples/CMakeLists.txt new file mode 100644 index 00000000..ac9c8291 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v4/examples/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman_exemplar.example LANGUAGES CXX) + +if(PROJECT_IS_TOP_LEVEL) + SET(CMAKE_CXX_STANDARD 23) +endif() diff --git a/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v5/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v5/CMakeLists.txt new file mode 100644 index 00000000..c4a62b38 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v5/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +include(cmake/flags.cmake) + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v5/cmake/flags.cmake b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v5/cmake/flags.cmake new file mode 100644 index 00000000..b1c75b01 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v5/cmake/flags.cmake @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +# Included from CMakeLists.txt, not from a toolchain file. +set(CMAKE_CXX_FLAGS "-Wall") diff --git a/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v6/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v6/CMakeLists.txt new file mode 100644 index 00000000..20439c4f --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v6/CMakeLists.txt @@ -0,0 +1,13 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +if(NOT DEFINED CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 23) +else() + set(CMAKE_CXX_STANDARD 20) +endif() + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v4/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v4/CMakeLists.txt new file mode 100644 index 00000000..be211cc7 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v4/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v4/etc/gcc-flags.cmake b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v4/etc/gcc-flags.cmake new file mode 100644 index 00000000..ed48d177 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v4/etc/gcc-flags.cmake @@ -0,0 +1,5 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +# Only included from gcc-toolchain.cmake. +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_FLAGS "-Wall -Wextra" CACHE STRING "CXX_FLAGS" FORCE) diff --git a/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v4/etc/gcc-toolchain.cmake b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v4/etc/gcc-toolchain.cmake new file mode 100644 index 00000000..b0af5e40 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v4/etc/gcc-toolchain.cmake @@ -0,0 +1,6 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +# Toolchain file: user-provided settings are allowed here. +set(CMAKE_CXX_COMPILER g++) + +include("${CMAKE_CURRENT_LIST_DIR}/gcc-flags.cmake") diff --git a/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v5/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v5/CMakeLists.txt new file mode 100644 index 00000000..4b4fdd96 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v5/CMakeLists.txt @@ -0,0 +1,12 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +# Only a default: the user's CMAKE_CXX_STANDARD wins. +if(NOT DEFINED CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 23) +endif() + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/test_cmake.py b/tests/lib/checks/beman_standard/cmake/test_cmake.py index 895fc7d2..988e4cd6 100644 --- a/tests/lib/checks/beman_standard/cmake/test_cmake.py +++ b/tests/lib/checks/beman_standard/cmake/test_cmake.py @@ -367,13 +367,20 @@ def test__cmake_skip_examples__fix_inplace(repo_info, beman_standard_check_confi def test__cmake_passive_projects__valid(repo_info, beman_standard_check_config): """ - Test that CMake files without forbidden project-level flags pass. - Fixtures under infra/ are excluded from this check. + Test that CMake files which don't override user compilation flags pass the + cmake.passive_projects check. """ valid_cmake_paths = [ + # No compilation flags set at all. Path(f"{valid_prefix}/passive_projects-v1"), + # Forbidden set() calls only in comments. Path(f"{valid_prefix}/passive_projects-v2"), + # Flags set only in a toolchain file (user settings). Path(f"{valid_prefix}/passive_projects-v3"), + # Flags set in a file included only from a toolchain file. + Path(f"{valid_prefix}/passive_projects-v4"), + # CMAKE_CXX_STANDARD set only as a default, inside if(NOT DEFINED ...). + Path(f"{valid_prefix}/passive_projects-v5"), ] run_check_for_each_path( @@ -387,12 +394,22 @@ def test__cmake_passive_projects__valid(repo_info, beman_standard_check_config): def test__cmake_passive_projects__invalid(repo_info, beman_standard_check_config): """ - Test that CMake files setting project-level compilation flags fail. + Test that CMake files overriding user compilation flags fail the + cmake.passive_projects check. """ invalid_cmake_paths = [ + # set(CMAKE_CXX_STANDARD 20) Path(f"{invalid_prefix}/invalid-passive_projects-v1"), + # set(CMAKE_CXX_FLAGS "-Wall") Path(f"{invalid_prefix}/invalid-passive_projects-v2"), + # set(CMAKE_CXX_STANDARD_REQUIRED ON) Path(f"{invalid_prefix}/invalid-passive_projects-v3"), + # Uppercase SET() in examples/CMakeLists.txt, under if(PROJECT_IS_TOP_LEVEL). + Path(f"{invalid_prefix}/invalid-passive_projects-v4"), + # Flags set in a .cmake file included from CMakeLists.txt, not a toolchain. + Path(f"{invalid_prefix}/invalid-passive_projects-v5"), + # Unconditional set() in the else() branch of if(NOT DEFINED ...). + Path(f"{invalid_prefix}/invalid-passive_projects-v6"), ] run_check_for_each_path( @@ -404,11 +421,10 @@ def test__cmake_passive_projects__invalid(repo_info, beman_standard_check_config ) +@pytest.mark.skip(reason="not implemented") def test__cmake_passive_projects__fix_inplace(repo_info, beman_standard_check_config): """ - Test that fix() is not auto-applicable for passive_projects violations. + Test that the fix method corrects an invalid CMake file. + Note: Skipping this test as it is not implemented. """ - repo_info["top_level"] = Path(f"{invalid_prefix}/invalid-passive_projects-v1") - check = CMakePassiveProjectsCheck(repo_info, beman_standard_check_config) - assert check.check() is False - assert check.fix() is False + pass From e2344314218d4cc17c6872eefe3a33e2c0e5389a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Darius=20Nea=C8=9Bu?= Date: Thu, 3 Dec 2026 21:44:07 +0200 Subject: [PATCH 3/3] [beman-tidy] Catch more flag overrides in cmake.passive_projects Also report CMAKE_CXX_FLAGS_, CMAKE_CXX_EXTENSIONS and string()/list() appends, set() inside function bodies and CACHE ... FORCE. Don't report toolchains named in CMake presets, files they include relative to the source dir, if(NOT ) defaults or CACHE without FORCE. Skip unparseable files. Move the check to its place in the rule order. --- beman_tidy/lib/checks/beman_standard/cmake.py | 383 +++++++++++------- .../CMakeLists.txt | 13 + .../CMakeLists.txt | 9 + .../CMakeLists.txt | 9 + .../CMakeLists.txt | 9 + .../CMakeLists.txt | 9 + .../CMakeLists.txt | 9 + .../valid/passive_projects-v6/CMakeLists.txt | 7 + .../passive_projects-v6/CMakePresets.json | 10 + .../valid/passive_projects-v6/cmake/ci.cmake | 7 + .../passive_projects-v6/cmake/warnings.cmake | 4 + .../valid/passive_projects-v7/CMakeLists.txt | 13 + .../valid/passive_projects-v8/CMakeLists.txt | 7 + .../passive_projects-v8/cmake/broken.cmake | 5 + .../checks/beman_standard/cmake/test_cmake.py | 19 + 15 files changed, 372 insertions(+), 141 deletions(-) create mode 100644 tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v10/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v11/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v12/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v7/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v8/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v9/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/CMakePresets.json create mode 100644 tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/cmake/ci.cmake create mode 100644 tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/cmake/warnings.cmake create mode 100644 tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v7/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v8/CMakeLists.txt create mode 100644 tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v8/cmake/broken.cmake diff --git a/beman_tidy/lib/checks/beman_standard/cmake.py b/beman_tidy/lib/checks/beman_standard/cmake.py index 4c3bc499..a434ee58 100644 --- a/beman_tidy/lib/checks/beman_standard/cmake.py +++ b/beman_tidy/lib/checks/beman_standard/cmake.py @@ -1,15 +1,12 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -from abc import ABC -from collections.abc import Iterable - +import json import os import re +from abc import ABC +from collections.abc import Iterable from pathlib import Path -from ..base.base_check import BaseCheck -from ...utils.config import get_ignore_matcher -from ...utils.file import get_cmake_files import cmake_parser from cmake_parser.ast import AstNode, Command, If, Include, Option, Set @@ -20,7 +17,10 @@ ) from ..system.registry import register_beman_standard_check +from ..base.base_check import BaseCheck from ..base.file_base_check import FileBaseCheck +from ...utils.config import get_ignore_matcher +from ...utils.file import get_cmake_files # [cmake.*] checks category. # All checks in this file extend the CMakeBaseCheck class. @@ -254,6 +254,242 @@ def fix(self): return False +@register_beman_standard_check("cmake.passive_projects") +class CMakePassiveProjectsCheck(BaseCheck): + """ + [cmake.passive_projects] + Requirement: CMake projects must not adjust user-specified compilation flags. + + Reports CMake code that overrides the user's compilation flags or C++ + standard settings: set() of such a variable (unless it is a CACHE entry + without FORCE, which keeps the user's value), and string()/list() calls + that append to or prepend to it. + + Not reported, because they don't override the user's settings: + - toolchain files (files named like a toolchain, or used as toolchainFile / + CMAKE_TOOLCHAIN_FILE in CMake presets) and the CMake files they include, + - defaults set only when the user gave none, i.e. inside + if(NOT DEFINED ) or if(NOT ). + """ + + _FLAGS_VARIABLE_RE = re.compile(r"^CMAKE_CXX_FLAGS(_[A-Z0-9_]+)?$") + _STANDARD_VARIABLES = ( + "CMAKE_CXX_STANDARD", + "CMAKE_CXX_STANDARD_REQUIRED", + "CMAKE_CXX_EXTENSIONS", + ) + _MODIFY_COMMANDS = { + "string": ("APPEND", "PREPEND"), + "list": ("APPEND", "PREPEND", "INSERT", "REMOVE_ITEM", "TRANSFORM"), + } + _TOOLCHAIN_NAME_RE = re.compile(r"toolchain", re.IGNORECASE) + _PRESET_FILES = ("CMakePresets.json", "CMakeUserPresets.json") + _LIST_DIR_PREFIX_RE = re.compile(r"^\$\{CMAKE_CURRENT_LIST_DIR\}/?") + _SOURCE_DIR_PREFIX_RE = re.compile( + r"^\$\{(?:sourceDir|CMAKE_SOURCE_DIR|CMAKE_CURRENT_SOURCE_DIR|PROJECT_SOURCE_DIR)\}/?" + ) + + @classmethod + def _is_forbidden_variable(cls, name): + return name in cls._STANDARD_VARIABLES or bool( + cls._FLAGS_VARIABLE_RE.match(name) + ) + + def _parse(self, rel_path): + """ + Returns the parse tree of a CMake file, or None if it cannot be read or parsed. + """ + try: + content = (self.repo_path / rel_path).read_text( + encoding="utf-8", errors="ignore" + ) + return list(cmake_parser.parser.parse_tree(content, skip_comments=True)) + except Exception as e: + self.log(f"{rel_path}: cannot parse CMake file, skipping it ({e}).") + return None + + @classmethod + def _walk(cls, nodes): + for node in nodes or []: + yield node + if isinstance(node, If): + yield from cls._walk(node.if_true) + yield from cls._walk(node.if_false) + else: + yield from cls._walk(getattr(node, "body", None)) + + def _resolve(self, path, base_dir, known): + """ + Resolves a path from include() or a preset to a known repository-relative + CMake file, or returns None. + """ + if self._SOURCE_DIR_PREFIX_RE.match(path): + candidates = [Path(self._SOURCE_DIR_PREFIX_RE.sub("", path))] + elif self._LIST_DIR_PREFIX_RE.match(path): + candidates = [base_dir / self._LIST_DIR_PREFIX_RE.sub("", path)] + else: + # A relative include() is relative to the current source directory, + # which for a toolchain file is the top-level one; also accept paths + # relative to the including file. + candidates = [Path(path), base_dir / path] + + for candidate in candidates: + if "${" in str(candidate) or candidate.is_absolute(): + continue + normalized = Path(os.path.normpath(candidate)) + if normalized in known: + return normalized + return None + + def _get_preset_toolchain_paths(self): + """ + Returns the toolchain file paths named in the repository's CMake presets. + """ + paths = [] + for preset_file in self._PRESET_FILES: + try: + presets = json.loads( + (self.repo_path / preset_file).read_text(encoding="utf-8") + ) + except (OSError, ValueError): + continue + for preset in ( + presets.get("configurePresets", []) if isinstance(presets, dict) else [] + ): + if not isinstance(preset, dict): + continue + toolchain = preset.get("toolchainFile") + cache_variables = preset.get("cacheVariables") + if not toolchain and isinstance(cache_variables, dict): + toolchain = cache_variables.get("CMAKE_TOOLCHAIN_FILE") + if isinstance(toolchain, dict): + toolchain = toolchain.get("value") + if isinstance(toolchain, str): + paths.append(toolchain) + return paths + + def _get_toolchain_files(self, cmake_files, trees): + """ + Returns the toolchain files and the CMake files they include, transitively. + """ + known = set(cmake_files) + toolchains = {p for p in cmake_files if self._TOOLCHAIN_NAME_RE.search(p.name)} + for path in self._get_preset_toolchain_paths(): + resolved = self._resolve(path, Path("."), known) + if resolved is not None: + toolchains.add(resolved) + + pending = list(toolchains) + while pending: + current = pending.pop() + for node in self._walk(trees.get(current)): + if not isinstance(node, Include) or not node.args: + continue + included = self._resolve(node.args[0].value, current.parent, known) + if included is not None and included not in toolchains: + toolchains.add(included) + pending.append(included) + return toolchains + + @staticmethod + def _get_default_guarded_variable(if_args): + """ + Returns for if(NOT DEFINED ) and if(NOT ), + whose body only sets a default, or None. + """ + values = [arg.value for arg in if_args or []] + if ( + len(values) == 3 + and values[0].upper() == "NOT" + and values[1].upper() == "DEFINED" + ): + return values[2] + if len(values) == 2 and values[0].upper() == "NOT": + return values[1] + return None + + @classmethod + def _get_overridden_variable(cls, node): + """ + Returns the forbidden variable that a set(), string() or list() node + overrides, or None. + """ + args = [arg.value for arg in node.args or []] + if isinstance(node, Set): + if not args or not cls._is_forbidden_variable(args[0]): + return None + upper_args = [arg.upper() for arg in args[1:]] + if "CACHE" in upper_args and "FORCE" not in upper_args: + # A cache entry without FORCE never replaces the user's value. + return None + return args[0] + if isinstance(node, Command): + modes = cls._MODIFY_COMMANDS.get(node.identifier.lower()) + if modes and len(args) >= 2 and args[0].upper() in modes: + if cls._is_forbidden_variable(args[1]): + return args[1] + return None + + @classmethod + def _find_overrides(cls, nodes, defaulted=frozenset()): + """ + Yields (line, variable) for each node overriding a forbidden variable. + """ + for node in nodes or []: + if isinstance(node, If): + guarded = cls._get_default_guarded_variable(node.args) + if_true_defaulted = defaulted | {guarded} if guarded else defaulted + yield from cls._find_overrides(node.if_true, if_true_defaulted) + yield from cls._find_overrides(node.if_false, defaulted) + continue + + body = getattr(node, "body", None) + if body is not None: + yield from cls._find_overrides(body, defaulted) + continue + + if isinstance(node, (Set, Command)): + variable = cls._get_overridden_variable(node) + if variable is not None and variable not in defaulted: + yield node.line, variable + + def check(self): + ignores = get_ignore_matcher(self.repo_info) + cmake_files = get_cmake_files(self.repo_path, ignores=ignores) + trees = {} + for rel_path in cmake_files: + tree = self._parse(rel_path) + if tree is not None: + trees[rel_path] = tree + toolchains = self._get_toolchain_files(cmake_files, trees) + + all_passed = True + for rel_path, tree in trees.items(): + if rel_path in toolchains: + continue + for line, variable in self._find_overrides(tree): + self.log( + f"{rel_path}:{line}: CMake must not set {variable}; " + "this overrides user compilation flags. " + "Please update CMake files according to the Beman Standard. " + "See https://github.com/bemanproject/beman/blob/main/docs/beman_standard.md#cmakepassive_projects " + "for more information." + ) + all_passed = False + + return all_passed + + def fix(self): + self.log( + "Please don't set CMAKE_CXX_FLAGS*, CMAKE_CXX_STANDARD, " + "CMAKE_CXX_STANDARD_REQUIRED or CMAKE_CXX_EXTENSIONS in CMake files; " + "provide CMake presets or toolchain files instead. " + "See https://github.com/bemanproject/beman/blob/main/docs/beman_standard.md#cmakepassive_projects " + "for more information." + ) + return False + + @register_beman_standard_check("cmake.library_name") class CMakeLibraryNameCheck(CMakeBaseCheck): def __init__(self, repo_info, beman_standard_check_config): @@ -373,141 +609,6 @@ def fix(self): return False -@register_beman_standard_check("cmake.passive_projects") -class CMakePassiveProjectsCheck(BaseCheck): - """ - [cmake.passive_projects] - Requirement: CMake projects must not adjust user-specified compilation flags. - - Flags set() in toolchain files (and in the files they include) are user - settings, so they are not reported. Neither is a default set only when the - user did not provide one, i.e. inside if(NOT DEFINED ). - """ - - _FORBIDDEN_VARIABLES = ( - "CMAKE_CXX_FLAGS", - "CMAKE_CXX_STANDARD", - "CMAKE_CXX_STANDARD_REQUIRED", - ) - _TOOLCHAIN_NAME_RE = re.compile(r"toolchain", re.IGNORECASE) - _CURRENT_LIST_DIR_RE = re.compile(r"\$\{CMAKE_CURRENT_LIST_DIR\}/?") - - def _get_cmake_files(self): - ignores = get_ignore_matcher(self.repo_info) - return get_cmake_files(self.repo_path, ignores=ignores) - - def _parse(self, rel_path): - """ - Returns the parse tree of a CMake file, or None if it cannot be read or parsed. - """ - try: - content = (self.repo_path / rel_path).read_text( - encoding="utf-8", errors="ignore" - ) - return list(cmake_parser.parser.parse_tree(content, skip_comments=True)) - except Exception as e: - self.log(f"{rel_path}: cannot parse CMake file, skipping it ({e}).") - return None - - @classmethod - def _walk(cls, nodes): - for node in nodes or []: - yield node - if isinstance(node, If): - yield from cls._walk(node.if_true) - yield from cls._walk(node.if_false) - else: - yield from cls._walk(getattr(node, "body", None)) - - def _get_toolchain_files(self, cmake_files, trees): - """ - Returns the toolchain files: files named like a toolchain and the CMake - files they include, transitively. - """ - known = set(cmake_files) - toolchains = {p for p in cmake_files if self._TOOLCHAIN_NAME_RE.search(p.name)} - pending = list(toolchains) - while pending: - current = pending.pop() - for node in self._walk(trees.get(current)): - if not isinstance(node, Include) or not node.args: - continue - target = self._CURRENT_LIST_DIR_RE.sub("", node.args[0].value) - if "${" in target: - continue - included = Path(os.path.normpath(current.parent / target)) - if included in known and included not in toolchains: - toolchains.add(included) - pending.append(included) - return toolchains - - @staticmethod - def _is_default_guard(if_args, variable): - """ - True for if(NOT DEFINED ), which only sets a default. - """ - values = [arg.value.upper() for arg in if_args or []] - return values == ["NOT", "DEFINED", variable] - - @classmethod - def _find_forbidden_sets(cls, nodes, defaulted=frozenset()): - """ - Yields (line, variable) for each set() of a forbidden variable that - overrides the user's value. - """ - for node in nodes or []: - is_set = isinstance(node, Set) or ( - isinstance(node, Command) and node.identifier.lower() == "set" - ) - if is_set: - if node.args: - variable = node.args[0].value - if variable in cls._FORBIDDEN_VARIABLES and variable not in defaulted: - yield node.line, variable - elif isinstance(node, If): - guarded = { - v for v in cls._FORBIDDEN_VARIABLES if cls._is_default_guard(node.args, v) - } - yield from cls._find_forbidden_sets(node.if_true, defaulted | guarded) - yield from cls._find_forbidden_sets(node.if_false, defaulted) - else: - yield from cls._find_forbidden_sets(getattr(node, "body", None), defaulted) - - def check(self): - cmake_files = self._get_cmake_files() - trees = {} - for rel_path in cmake_files: - tree = self._parse(rel_path) - if tree is not None: - trees[rel_path] = tree - toolchains = self._get_toolchain_files(cmake_files, trees) - - all_passed = True - for rel_path, tree in trees.items(): - if rel_path in toolchains: - continue - for line, variable in self._find_forbidden_sets(tree): - self.log( - f"{rel_path}:{line}: CMake must not set {variable}; " - "this overrides user compilation flags. " - "Please update CMake files according to the Beman Standard. " - "See https://github.com/bemanproject/beman/blob/main/docs/beman_standard.md#cmakepassive_projects " - "for more information." - ) - all_passed = False - - return all_passed - - def fix(self): - self.log( - "Please remove set(CMAKE_CXX_FLAGS), set(CMAKE_CXX_STANDARD), and " - "set(CMAKE_CXX_STANDARD_REQUIRED) from CMake files. " - "See https://github.com/bemanproject/beman/blob/main/docs/beman_standard.md#cmakepassive_projects " - "for more information." - ) - return False - - # TODO cmake.passive_targets diff --git a/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v10/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v10/CMakeLists.txt new file mode 100644 index 00000000..c7e61971 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v10/CMakeLists.txt @@ -0,0 +1,13 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +function(beman_exemplar_setup) + set(CMAKE_CXX_STANDARD 20 PARENT_SCOPE) +endfunction() + +beman_exemplar_setup() + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v11/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v11/CMakeLists.txt new file mode 100644 index 00000000..d43ae811 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v11/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +set(CMAKE_CXX_FLAGS "-Wall" CACHE STRING "C++ flags" FORCE) + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v12/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v12/CMakeLists.txt new file mode 100644 index 00000000..e0908798 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v12/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +list(APPEND CMAKE_CXX_FLAGS -Wall) + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v7/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v7/CMakeLists.txt new file mode 100644 index 00000000..011a5c41 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v7/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +string(APPEND CMAKE_CXX_FLAGS " -Wall") + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v8/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v8/CMakeLists.txt new file mode 100644 index 00000000..4ae096c5 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v8/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +set(CMAKE_CXX_FLAGS_RELEASE "-O3") + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v9/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v9/CMakeLists.txt new file mode 100644 index 00000000..ce074a4a --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/invalid/invalid-passive_projects-v9/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +set(CMAKE_CXX_EXTENSIONS OFF) + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/CMakeLists.txt new file mode 100644 index 00000000..be211cc7 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/CMakePresets.json b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/CMakePresets.json new file mode 100644 index 00000000..97451969 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/CMakePresets.json @@ -0,0 +1,10 @@ +{ + "version": 6, + "configurePresets": [ + { + "name": "ci", + "binaryDir": "${sourceDir}/build", + "toolchainFile": "${sourceDir}/cmake/ci.cmake" + } + ] +} diff --git a/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/cmake/ci.cmake b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/cmake/ci.cmake new file mode 100644 index 00000000..a0609298 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/cmake/ci.cmake @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +# Used as toolchainFile by CMakePresets.json. +set(CMAKE_CXX_STANDARD 20) + +# Relative to the top-level source directory. +include(cmake/warnings.cmake) diff --git a/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/cmake/warnings.cmake b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/cmake/warnings.cmake new file mode 100644 index 00000000..d247af2d --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v6/cmake/warnings.cmake @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +# Only included from the preset's toolchain file. +string(APPEND CMAKE_CXX_FLAGS " -Wall -Wextra") diff --git a/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v7/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v7/CMakeLists.txt new file mode 100644 index 00000000..9f6ae90c --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v7/CMakeLists.txt @@ -0,0 +1,13 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +# Only defaults: the user's values win. +if(NOT CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 20) +endif() +set(CMAKE_CXX_STANDARD_REQUIRED ON CACHE BOOL "Require the C++ standard") + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v8/CMakeLists.txt b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v8/CMakeLists.txt new file mode 100644 index 00000000..be211cc7 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v8/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required(VERSION 3.30...4.3) + +project(beman.exemplar LANGUAGES CXX) + +add_library(beman.exemplar INTERFACE) diff --git a/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v8/cmake/broken.cmake b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v8/cmake/broken.cmake new file mode 100644 index 00000000..30e331e8 --- /dev/null +++ b/tests/lib/checks/beman_standard/cmake/data/valid/passive_projects-v8/cmake/broken.cmake @@ -0,0 +1,5 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +# Missing endif(): cannot be parsed, so it is skipped. +if(BEMAN_EXEMPLAR_SOMETHING) + message(STATUS "something") diff --git a/tests/lib/checks/beman_standard/cmake/test_cmake.py b/tests/lib/checks/beman_standard/cmake/test_cmake.py index 988e4cd6..270f7a3f 100644 --- a/tests/lib/checks/beman_standard/cmake/test_cmake.py +++ b/tests/lib/checks/beman_standard/cmake/test_cmake.py @@ -381,6 +381,13 @@ def test__cmake_passive_projects__valid(repo_info, beman_standard_check_config): Path(f"{valid_prefix}/passive_projects-v4"), # CMAKE_CXX_STANDARD set only as a default, inside if(NOT DEFINED ...). Path(f"{valid_prefix}/passive_projects-v5"), + # Toolchain file named in CMakePresets.json, and a file it includes + # relative to the top-level source directory. + Path(f"{valid_prefix}/passive_projects-v6"), + # Defaults only: if(NOT ) and a CACHE entry without FORCE. + Path(f"{valid_prefix}/passive_projects-v7"), + # A CMake file that cannot be parsed is skipped, not a crash. + Path(f"{valid_prefix}/passive_projects-v8"), ] run_check_for_each_path( @@ -410,6 +417,18 @@ def test__cmake_passive_projects__invalid(repo_info, beman_standard_check_config Path(f"{invalid_prefix}/invalid-passive_projects-v5"), # Unconditional set() in the else() branch of if(NOT DEFINED ...). Path(f"{invalid_prefix}/invalid-passive_projects-v6"), + # string(APPEND CMAKE_CXX_FLAGS ...) + Path(f"{invalid_prefix}/invalid-passive_projects-v7"), + # set(CMAKE_CXX_FLAGS_RELEASE ...) + Path(f"{invalid_prefix}/invalid-passive_projects-v8"), + # set(CMAKE_CXX_EXTENSIONS OFF) + Path(f"{invalid_prefix}/invalid-passive_projects-v9"), + # set(CMAKE_CXX_STANDARD ... PARENT_SCOPE) inside a function(). + Path(f"{invalid_prefix}/invalid-passive_projects-v10"), + # CACHE entry with FORCE replaces the user's value. + Path(f"{invalid_prefix}/invalid-passive_projects-v11"), + # list(APPEND CMAKE_CXX_FLAGS ...) + Path(f"{invalid_prefix}/invalid-passive_projects-v12"), ] run_check_for_each_path(