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
244 changes: 242 additions & 2 deletions beman_tidy/lib/checks/beman_standard/cmake.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

import json
import os
import re
from abc import ABC
from collections.abc import Iterable
from pathlib import Path

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,
cmake_has_unguarded_subdirectory,
)

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.
Expand Down Expand Up @@ -247,7 +254,240 @@ def fix(self):
return False


# TODO cmake.passive_projects
@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 <variable>) or if(NOT <variable>).
"""

_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 <variable> for if(NOT DEFINED <variable>) and if(NOT <variable>),
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")
Expand Down
26 changes: 26 additions & 0 deletions beman_tidy/lib/utils/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,32 @@ def get_cpp_files(repo_path, ignores=None):
return get_matched_paths(repo_path, get_cpp_extensions(), ignores=ignores)


def get_cmake_files(repo_path, ignores=None):
"""
Get all CMake files (CMakeLists.txt and *.cmake) in the repository.
Ignores paths specified in 'ignores' (an IgnoreMatcher or patterns).
"""
repo_path = Path(repo_path)
matcher = _as_matcher(ignores, repo_path)

matched_files = []

for root, dirs, files in os.walk(repo_path):
rel_root = Path(root).relative_to(repo_path)

for d in list(dirs):
if matcher.is_ignored(rel_root / d, is_dir=True):
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 matcher.is_ignored(f_path, is_dir=False):
matched_files.append(f_path)

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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
@@ -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()
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
@@ -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")
Loading
Loading