Skip to content
Merged
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
10 changes: 5 additions & 5 deletions project_validator/build_systems/cmake/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,13 @@ def _evaluated(files: Mapping[str, str]) -> CMakeProject:
evaluation.evaluate()
problems = (
Unknown(
origin=Origin(path=path),
origin=Origin(path=path, span=problem.span),
subject=f"the CMake file {path}",
reason=reason,
reason=problem.reason,
hides="settings",
tools=("CMake",),
)
for path, reason in evaluation.problems.items()
for path, problem in evaluation.problems.items()
)
targets = {
name: tuple(
Expand Down Expand Up @@ -175,8 +175,8 @@ def _scripts_run(command: Command, context: Context) -> list[Expansion] | None:
evaluation = Evaluation(files=frozenset(files), read=files.__getitem__, observer=collector)
evaluation.script(path, defines)
problems: list[Expansion] = [
Unknown(origin=Origin(path=at), subject=f"the CMake script {at}", reason=reason, hides="commands")
for at, reason in evaluation.problems.items()
Unknown(origin=Origin(path=at, span=problem.span), subject=f"the CMake script {at}", reason=problem.reason)
for at, problem in evaluation.problems.items()
]
return [
*problems,
Expand Down
29 changes: 15 additions & 14 deletions project_validator/build_systems/cmake/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,13 @@ def invoked(self, frame: Frame, invocation: Invocation, words: list[Value]) -> N
if (handler := _COMMANDS.get(invocation.name)) is not None:
handler(self, frame, invocation, words)
elif invocation.name in _TEST_REGISTRATIONS:
self.ctest(frame, "registers", invocation.name)
self.ctest(frame, invocation, "registers", invocation.name)
registered = _registered_test([word.text for word in words])
if invocation.name == "add_test" and registered[:1] not in ((), ("",)):
self.ctest(frame, "test", registered)
self.ctest(frame, invocation, "test", registered)
elif invocation.name in _DEPENDENCY_MANAGERS:
self.facts.append(Declared(origin=Origin(path=frame.path), manager=_DEPENDENCY_MANAGERS[invocation.name]))
manager = _DEPENDENCY_MANAGERS[invocation.name]
self.facts.append(Declared(origin=frame.origin(invocation), manager=manager))

def finished(self, frame: Frame) -> None:
"""The CMake variables a directory set last, as settings; those that hold flags, as options too."""
Expand Down Expand Up @@ -147,11 +148,11 @@ def options(
builds = both(frame.condition, word.when, value.when)
self._add(word.origin or frame.origin(invocation), builds, options, kind, target)

def ctest(self, frame: Frame, key: str, value: object) -> None:
self.facts.append(Setting(origin=Origin(path=frame.path), tool="CTest", key=key, value=value))
def ctest(self, frame: Frame, invocation: Invocation, key: str, value: object) -> None:
self.facts.append(Setting(origin=frame.origin(invocation), tool="CTest", key=key, value=value))

def guard(self, frame: Frame, text: str) -> None:
self.facts.append(Setting(origin=Origin(path=frame.path), tool=BUILD_SYSTEM, key="guard", value=text))
def guard(self, frame: Frame, invocation: Invocation, text: str) -> None:
self.facts.append(Setting(origin=frame.origin(invocation), tool=BUILD_SYSTEM, key="guard", value=text))

def setting(
self,
Expand Down Expand Up @@ -302,15 +303,15 @@ def _option(collector: Collector, frame: Frame, invocation: Invocation, words: l
for value in arguments[2] if len(arguments) > 2 else [Value("OFF")]:
collector.setting(frame, invocation, words[0].text, value, None, default=True)
if invocation.name == "cmake_dependent_option" and len(arguments) >= 4:
collector.guard(frame, arguments[3][0].text)
collector.guard(frame, invocation, arguments[3][0].text)


def _guard(collector: Collector, frame: Frame, _invocation: Invocation, words: list[Value]) -> None:
def _guard(collector: Collector, frame: Frame, invocation: Invocation, words: list[Value]) -> None:
"""What an `if()` (or `elseif()`) tests, as written: the evaluator decides where it holds; the text says what the
project guards on (`PROJECT_IS_TOP_LEVEL`, a comparison of the source and binary directories). A variable a path
was resolved into reads as the path."""
texts = (collector.resolved.get(word.text.removeprefix("${").removesuffix("}"), word.text) for word in words)
collector.guard(frame, " ".join(texts))
collector.guard(frame, invocation, " ".join(texts))


def _resolve(collector: Collector, _frame: Frame, invocation: Invocation, _words: list[Value]) -> None:
Expand All @@ -328,7 +329,7 @@ def _string(collector: Collector, frame: Frame, invocation: Invocation, _words:
`if(a STREQUAL b)` would, so the comparison, as written, is a guard."""
raw = [argument.text for argument in invocation.arguments]
if raw[:2] == ["COMPARE", "EQUAL"] and len(raw) >= 5:
collector.guard(frame, f"{raw[2]} STREQUAL {raw[3]}")
collector.guard(frame, invocation, f"{raw[2]} STREQUAL {raw[3]}")


def _set(collector: Collector, frame: Frame, invocation: Invocation, words: list[Value]) -> None:
Expand All @@ -339,8 +340,8 @@ def _set(collector: Collector, frame: Frame, invocation: Invocation, words: list
collector.setting(frame, invocation, texts[0], Value(value, words[0].when), None, default=True)


def _enable_testing(collector: Collector, frame: Frame, _invocation: Invocation, _words: list[Value]) -> None:
collector.ctest(frame, "enables", True)
def _enable_testing(collector: Collector, frame: Frame, invocation: Invocation, _words: list[Value]) -> None:
collector.ctest(frame, invocation, "enables", True)


def _include(collector: Collector, frame: Frame, invocation: Invocation, words: list[Value]) -> None:
Expand All @@ -349,7 +350,7 @@ def _include(collector: Collector, frame: Frame, invocation: Invocation, words:
if words[0].text == "CTest":
_enable_testing(collector, frame, invocation, words)
elif words[0].text.endswith("CPM.cmake"):
collector.facts.append(Declared(origin=Origin(path=frame.path), manager="CPM"))
collector.facts.append(Declared(origin=frame.origin(invocation), manager="CPM"))


def _commands(
Expand Down
29 changes: 15 additions & 14 deletions project_validator/build_systems/cmake/evaluation.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
from project_validator.facts import Origin
from project_validator.facts.conditions import ALWAYS, Condition, both, either, negated, requiring
from project_validator.limits import CMAKE_NESTING
from project_validator.parsing import Problem

# How many items a loop runs for, and how many commands are evaluated in all (how deep calls and includes nest is
# `CMAKE_NESTING`).
Expand Down Expand Up @@ -107,7 +108,7 @@ class Frame:
stack: tuple[str, ...] = ()

def origin(self, invocation: Invocation) -> Origin:
return Origin(path=self.path, at=(invocation.name, invocation.line))
return Origin(path=self.path, at=(invocation.name,), span=invocation.span)


class Observer(Protocol):
Expand Down Expand Up @@ -147,7 +148,7 @@ class Evaluation:
configured: set[str] = field(default_factory=set)
descriptions: dict[str, str] = field(default_factory=dict)
reached: set[str] = field(default_factory=set)
problems: dict[str, str] = field(default_factory=dict)
problems: dict[str, Problem] = field(default_factory=dict)
_parsed: dict[str, list[Node] | None] = field(default_factory=dict)
_commands: int = 0

Expand All @@ -156,10 +157,10 @@ def parsed(self, path: str) -> list[Node] | None:
try:
self._parsed[path] = parse(self.read(path))
except CMakeSyntaxError as error:
self.problems[path] = str(error)
self.problems[path] = Problem(str(error), error.span)
self._parsed[path] = None
except RecursionError:
self.problems[path] = "nested too deeply to read"
self.problems[path] = Problem("nested too deeply to read")
self._parsed[path] = None
return self._parsed[path]

Expand All @@ -168,9 +169,9 @@ def evaluate(self) -> None:
try:
self._evaluate_all()
except _TooMuch:
self.problems["CMakeLists.txt"] = f"evaluation stopped after {MOST_COMMANDS} commands"
self.problems["CMakeLists.txt"] = Problem(f"evaluation stopped after {MOST_COMMANDS} commands")
except RecursionError:
self.problems["CMakeLists.txt"] = "nested too deeply to read"
self.problems["CMakeLists.txt"] = Problem("nested too deeply to read")

def script(self, path: str, defines: Mapping[str, str]) -> None:
"""Run `path` as `cmake -D name=value... -P path` does: on its own, with the variables the command defines."""
Expand All @@ -182,7 +183,7 @@ def script(self, path: str, defines: Mapping[str, str]) -> None:
try:
self._file(path, frame)
except _TooMuch:
self.problems[path] = f"evaluation stopped after {MOST_COMMANDS} commands"
self.problems[path] = Problem(f"evaluation stopped after {MOST_COMMANDS} commands")

def _evaluate_all(self) -> None:
lists = sorted((path for path in self.files if PurePosixPath(path).name == LISTS_FILE), key=_depth)
Expand Down Expand Up @@ -337,16 +338,16 @@ def _foreach(self, block: Block, frame: Frame) -> None:
def _invoke(self, invocation: Invocation, frame: Frame) -> None:
words = self.words(invocation.arguments, frame)
if (definition := self.functions.get(invocation.name)) is not None:
self._call(definition, words, frame)
self._call(definition, words, frame, invocation)
return
if (handler := _HANDLERS.get(invocation.name)) is not None:
handler(self, frame, words, invocation)
self.observer.invoked(frame, invocation, words)

def _call(self, definition: Definition, words: list[Value], frame: Frame) -> None:
def _call(self, definition: Definition, words: list[Value], frame: Frame, invocation: Invocation) -> None:
arguments = tuple(word.text for word in words)
if not CMAKE_NESTING.allows(len(frame.stack)):
self.problems.setdefault(frame.path, CMAKE_NESTING.reason)
self.problems.setdefault(frame.path, Problem(CMAKE_NESTING.reason, invocation.span))
if arguments in definition.seen or definition.name in frame.stack or not CMAKE_NESTING.allows(len(frame.stack)):
definition.calls = max(definition.calls, 1)
return
Expand Down Expand Up @@ -458,11 +459,11 @@ def parse_arguments(self, frame: Frame, words: list[Value], _: Invocation) -> No
elif len(texts) >= 4:
_parse_arguments(frame.scope, texts[:4], words[4:])

def include(self, frame: Frame, words: list[Value], _: Invocation) -> None:
def include(self, frame: Frame, words: list[Value], invocation: Invocation) -> None:
if not words or (path := self._module(frame, words[0].text)) is None or path in frame.stack:
return
if not CMAKE_NESTING.allows(len(frame.stack)):
self.problems.setdefault(frame.path, CMAKE_NESTING.reason)
self.problems.setdefault(frame.path, Problem(CMAKE_NESTING.reason, invocation.span))
return
if path in self.reached and self._guarded(path):
return
Expand All @@ -486,11 +487,11 @@ def _module(self, frame: Frame, name: str) -> str | None:
found = (_within(self.files, directory, f"{name}.cmake") for directory in directories)
return next((path for path in found if path is not None), None)

def add_subdirectory(self, frame: Frame, words: list[Value], _: Invocation) -> None:
def add_subdirectory(self, frame: Frame, words: list[Value], invocation: Invocation) -> None:
if not words:
return
if not CMAKE_NESTING.allows(len(frame.stack)):
self.problems.setdefault(frame.path, CMAKE_NESTING.reason)
self.problems.setdefault(frame.path, Problem(CMAKE_NESTING.reason, invocation.span))
return
path = _within(self.files, frame.directory, f"{words[0].text}/{LISTS_FILE}")
if path is not None and path not in frame.stack:
Expand Down
28 changes: 20 additions & 8 deletions project_validator/build_systems/cmake/syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from collections.abc import Iterator
from dataclasses import dataclass, field

from project_validator.parsing import ParseError
from project_validator.parsing import ParseError, Span


class Kind(enum.Enum):
Expand All @@ -26,11 +26,16 @@ class Argument:

@dataclass(frozen=True, slots=True)
class Invocation:
"""A command invocation: its name (in lower case, as CMake compares them), arguments and line."""
"""A command invocation: its name (in lower case, as CMake compares them), arguments, and where it is written,
from its name to past its closing parenthesis."""

name: str
arguments: tuple[Argument, ...]
line: int
span: Span

@property
def line(self) -> int:
return self.span.line


@dataclass(slots=True)
Expand Down Expand Up @@ -85,6 +90,11 @@ def __init__(self, text: str) -> None:
def of(self, offset: int) -> int:
return bisect.bisect_right(self.starts, offset)

def position(self, offset: int) -> tuple[int, int]:
"""The line and column of `offset`, both from 1."""
line = self.of(offset)
return line, offset - self.starts[line - 1] + 1


def _tokens(text: str) -> Iterator[tuple[str, str, int]]:
"""(kind, text, offset) of each token that is not blank or a comment."""
Expand All @@ -108,13 +118,14 @@ def _argument(kind: str, text: str) -> Argument:
return Argument(text, Kind.UNQUOTED)


def _arguments(tokens: Iterator[tuple[str, str, int]], lines: _Lines, line: int) -> tuple[Argument, ...]:
"""The arguments up to the closing parenthesis; nested parentheses are arguments of their own (`if((A))`)."""
def _arguments(tokens: Iterator[tuple[str, str, int]], line: int) -> tuple[tuple[Argument, ...], int]:
"""The arguments up to the closing parenthesis, and the offset after it; nested parentheses are arguments of their
own (`if((A))`)."""
found: list[Argument] = []
depth = 0
for kind, text, _ in tokens:
for kind, text, offset in tokens:
if kind == "close" and depth == 0:
return tuple(found)
return tuple(found), offset + 1
depth += {"open": 1, "close": -1}.get(kind, 0)
found.append(Argument(text, Kind.UNQUOTED) if kind in ("open", "close") else _argument(kind, text))
raise CMakeSyntaxError(line, "the command's arguments are never closed")
Expand All @@ -130,7 +141,8 @@ def invocations(text: str) -> Iterator[Invocation]:
raise CMakeSyntaxError(line, f"expected a command, found {name!r}")
if next(tokens, ("", "", 0))[0] != "open":
raise CMakeSyntaxError(line, f"expected ( after {name}")
yield Invocation(name.lower(), _arguments(tokens, lines, line), line)
arguments, end = _arguments(tokens, line)
yield Invocation(name.lower(), arguments, Span(*lines.position(offset), *lines.position(end)))


def _block(opening: Invocation, found: Iterator[Invocation]) -> Block:
Expand Down
Loading
Loading