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
109 changes: 38 additions & 71 deletions project_validator/build_systems/cmake/generator_expressions.py
Original file line number Diff line number Diff line change
@@ -1,60 +1,17 @@
"""Generator expressions (see cmake-generator-expressions(7)), which CMake evaluates per build: `$<$<CONFIG:Debug>:-O0>`
is `-O0` in Debug builds and nothing in the others. Each value an argument takes is found with the builds it is in."""
is `-O0` in Debug builds and nothing in the others. Each value an argument takes is found with the builds it is in,
by walking its tree (`project_validator.build_systems.cmake.generator_syntax`)."""

from __future__ import annotations

import re
from collections.abc import Callable, Iterator, Mapping
from collections.abc import Callable, Mapping

from project_validator.build_systems.cmake.conditions import COMPILER, CONFIGURATION, LANGUAGE, PLATFORM, constant
from project_validator.build_systems.cmake.generator_syntax import START, Expression, Template, parse, split, written
from project_validator.build_systems.cmake.values import MOST_VALUES, Value, referenced
from project_validator.facts.conditions import ALWAYS, NEVER, Condition, both, either, negated, requiring

_START = "$<"


def _split(text: str, separator: str) -> list[str]:
"""`text` split on `separator` outside nested generator expressions."""
parts, depth, start = [], 0, 0
for position, character in enumerate(text):
if text.startswith(_START, position):
depth += 1
elif character == ">" and depth:
depth -= 1
elif character == separator and not depth:
parts.append(text[start:position])
start = position + 1
return [*parts, text[start:]]


def _head(content: str) -> tuple[str, str, str]:
"""An expression's name (or condition) and arguments, split at the first colon outside nested expressions."""
name, *rest = _split(content, ":")
return name, ":" if rest else "", ":".join(rest)


def _end(text: str, start: int) -> int:
"""The position of the `>` closing the expression whose content starts at `start`; -1 when it is not closed."""
depth = 1
for position in range(start, len(text)):
if text.startswith(_START, position):
depth += 1
elif text[position] == ">":
depth -= 1
if depth == 0:
return position
return -1


def _parts(text: str) -> Iterator[tuple[str, bool]]:
"""(text, whether it is an expression's content) for each part of `text`."""
position = 0
while (start := text.find(_START, position)) >= 0 and (end := _end(text, start + 2)) >= 0:
yield text[position:start], False
yield text[start + 2 : end], True
position = end + 1
yield text[position:], False


def _listed(evaluate: Callable[[list[str]], Condition]) -> Callable[[list[str]], Condition]:
return lambda arguments: evaluate([name for argument in arguments for name in argument.split(",") if name])
Expand All @@ -73,7 +30,7 @@ def _bool(arguments: list[str]) -> Condition:


def _streq(arguments: list[str]) -> Condition | None:
if len(arguments) != 2 or any("${" in argument or _START in argument for argument in arguments):
if len(arguments) != 2 or any("${" in argument or START in argument for argument in arguments):
return None
return ALWAYS if arguments[0] == arguments[1] else NEVER

Expand All @@ -93,62 +50,72 @@ def _streq(arguments: list[str]) -> Condition | None:

def test(text: str) -> Condition:
"""The builds in which `text`, a boolean expression or a constant, is 1."""
return _holds(parse(text))


def _holds(template: Template) -> Condition:
"""The builds in which a parsed boolean expression or constant is 1; one not understood is a requirement."""
text = written(template)
if (known := constant(text)) is not None:
return ALWAYS if known else NEVER
contents = [content for content, expression in _parts(text) if expression]
if len(contents) != 1 or not text.startswith(_START) or not text.endswith(">"):
if len(template) != 1 or not isinstance(expression := template[0], Expression):
return requiring(text)
name, _, rest = _head(contents[0])
arguments = _split(rest, ",")
found = _test(written(expression.name), expression.rest or ())
return requiring(text) if found is None else found


def _test(name: str, rest: Template) -> Condition | None:
found: Condition | None
arguments = [written(argument) for argument in split(rest, ",")]
if name == "NOT":
found = negated(test(rest))
found = negated(_holds(rest))
elif name in ("AND", "OR"):
found = (both if name == "AND" else either)(*(test(argument) for argument in arguments))
found = (both if name == "AND" else either)(*map(_holds, split(rest, ",")))
elif _COMPILER_ID.fullmatch(name):
found = _listed(COMPILER.listed)(arguments)
else:
found = _TESTS[name](arguments) if name in _TESTS else None
return requiring(text) if found is None else found
return found


_PASSED = frozenset({"BUILD_INTERFACE", "BUILD_LOCAL_INTERFACE", "HOST_LINK", "DEVICE_LINK", "LINK_ONLY"})
_CHARACTERS = {"SEMICOLON": ";", "COMMA": ",", "ANGLE-R": ">", "INSTALL_INTERFACE": ""}


def _in(when: Condition, value: str) -> list[Value]:
def _in(when: Condition, value: Template) -> list[Value]:
"""The values `value` takes in the builds `when` names."""
return [Value(part.text, held) for part in _generated(value) if (held := both(when, part.when))]


def _conditional(when: Condition, value: str) -> list[Value]:
def _conditional(when: Condition, value: Template) -> list[Value]:
"""`$<condition:value>`: the value where the condition holds, nothing elsewhere."""
found = _in(when, value)
return [*found, Value("", rest)] if (rest := negated(when)) else found


def _expression(content: str) -> list[Value]:
"""The values one expression (`content`, between `$<` and `>`) takes."""
name, separator, rest = _head(content)
if name in ("0", "1") or name.startswith(_START):
return _conditional(test(name), rest)
if name == "IF" and len(arguments := _split(rest, ",")) == 3:
when = test(arguments[0])
def _expression(expression: Expression) -> list[Value]:
"""The values one expression takes."""
name, rest = written(expression.name), expression.rest or ()
if name in ("0", "1") or (expression.name and isinstance(expression.name[0], Expression)):
return _conditional(_holds(expression.name), rest)
if name == "IF" and len(arguments := split(rest, ",")) == 3:
when = _holds(arguments[0])
return [*_in(when, arguments[1]), *_in(negated(when), arguments[2])]
if name in _PASSED:
return _generated(rest)
if name in _CHARACTERS:
return [Value(_CHARACTERS[name])]
if (separator and name in _TESTS) or name in ("NOT", "AND", "OR") or _COMPILER_ID.fullmatch(name):
when = test(f"$<{content}>")
tested = (expression.rest is not None and name in _TESTS) or name in ("NOT", "AND", "OR")
if tested or _COMPILER_ID.fullmatch(name):
when = _holds((expression,))
return [Value("1", when), Value("0", negated(when))]
return [Value(f"$<{content}>")]
return [Value(expression.written)]


def _generated(text: str) -> list[Value]:
def _generated(template: Template) -> list[Value]:
values = [Value("")]
for part, expression in _parts(text):
found = _expression(part) if expression else [Value(part)]
for part in template:
found = _expression(part) if isinstance(part, Expression) else [Value(part)]
values = [
Value(value.text + more.text, when)
for value in values
Expand All @@ -162,7 +129,7 @@ def generated(text: str) -> list[Value]:
"""The values `text` takes, with the builds it takes each in; expressions that are not understood (or are nested
too deeply) are kept."""
try:
return _generated(text)
return _generated(parse(text))
except RecursionError:
return [Value(text)]

Expand Down
95 changes: 95 additions & 0 deletions project_validator/build_systems/cmake/generator_syntax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
"""The syntax of generator expressions (see cmake-generator-expressions(7)): text to a `Template` of literal parts and
`Expression`s, without evaluating any (`project_validator.build_systems.cmake.generator_expressions` does).

An expression `$<name:rest>` has a name and, after its first colon outside nested expressions, the rest; both are
templates, since either may hold expressions of its own (`$<$<CONFIG:Debug>:-O0>`). The rest is not split: what a
comma means is the expression's (`$<IF:c,a,b>` takes three arguments, `$<1:a,b>` the value `a,b`), so its evaluation
splits it (`split`). A `$<` never closed is text, as CMake keeps it.
"""

from __future__ import annotations

from dataclasses import dataclass

# What opens an expression.
START = "$<"


@dataclass(frozen=True, slots=True)
class Expression:
"""`$<name:rest>` (`rest` None without a colon), as `written`, from `start` to `end` in the text parsed."""

name: Template
rest: Template | None
written: str
start: int
end: int


type Part = str | Expression
type Template = tuple[Part, ...]


def _end(text: str, start: int) -> int:
"""The position of the `>` closing the expression whose content starts at `start`; -1 when it is not closed."""
depth = 1
for position in range(start, len(text)):
if text.startswith(START, position):
depth += 1
elif text[position] == ">":
depth -= 1
if depth == 0:
return position
return -1


def _colon(content: str) -> int:
"""The position of the first colon outside nested expressions in an expression's content; -1 when there is none."""
depth = 0
for position, character in enumerate(content):
if content.startswith(START, position):
depth += 1
elif character == ">" and depth:
depth -= 1
elif character == ":" and not depth:
return position
return -1


def parse(text: str, offset: int = 0) -> Template:
"""The parts of `text`, its literal text and its expressions, each placed from `offset`."""
parts: list[Part] = []
position = 0
while (start := text.find(START, position)) >= 0 and (end := _end(text, start + 2)) >= 0:
if start > position:
parts.append(text[position:start])
content, at = text[start + 2 : end], offset + start + 2
colon = _colon(content)
name = parse(content if colon < 0 else content[:colon], at)
rest = None if colon < 0 else parse(content[colon + 1 :], at + colon + 1)
parts.append(Expression(name, rest, text[start : end + 1], offset + start, offset + end + 1))
position = end + 1
if position < len(text):
parts.append(text[position:])
return tuple(parts)


def written(template: Template) -> str:
"""The template's text, as written."""
return "".join(part if isinstance(part, str) else part.written for part in template)


def split(template: Template, separator: str) -> list[Template]:
"""The template split at `separator` in its literal text, outside the expressions it holds."""
found: list[list[Part]] = [[]]
for part in template:
if isinstance(part, Expression):
found[-1].append(part)
continue
first, *others = part.split(separator)
found[-1].append(first)
found += [[other] for other in others]
return [tuple(piece for piece in pieces if piece != "") for pieces in found]


__all__ = ["START", "Expression", "Part", "Template", "parse", "split", "written"]
56 changes: 56 additions & 0 deletions tests/test_cmake_generator_syntax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""The syntax of CMake generator expressions: text to literal parts and expressions, without evaluating any."""

from __future__ import annotations

import unittest

from project_validator.build_systems.cmake.generator_syntax import Expression, Template, parse, split, written


def _shape(template: Template) -> list[object]:
"""A template as nested lists: text as itself, an expression as (name, rest), rest None without a colon."""
return [
part if isinstance(part, str) else (_shape(part.name), None if part.rest is None else _shape(part.rest))
for part in template
]


class ParseTests(unittest.TestCase):
def test_text_and_expressions_with_their_name_and_rest(self) -> None:
self.assertEqual(
_shape(parse("-W$<$<CONFIG:Debug>:all,extra>x")),
["-W", ([(["CONFIG"], ["Debug"])], ["all,extra"]), "x"],
)

def test_an_expression_without_a_colon_has_no_rest(self) -> None:
self.assertEqual(_shape(parse("a$<SEMICOLON>b")), ["a", (["SEMICOLON"], None), "b"])

def test_the_name_ends_at_the_first_colon_outside_nested_expressions(self) -> None:
[expression] = parse("$<$<STREQUAL:a,b>:x:y>")
self.assertIsInstance(expression, Expression)
self.assertEqual(_shape(parse("$<$<STREQUAL:a,b>:x:y>")), [([(["STREQUAL"], ["a,b"])], ["x:y"])])

def test_an_expression_never_closed_is_text_to_the_end(self) -> None:
"""What it would hold is text too: the `>` that closes `$<c>` leaves `$<b` open."""
self.assertEqual(_shape(parse("a$<b$<c>")), ["a$<b$<c>"])
self.assertEqual(_shape(parse("$<unclosed")), ["$<unclosed"])

def test_each_expression_keeps_where_and_how_it_is_written(self) -> None:
[text, expression] = parse("-W$<IF:$<BOOL:x>,a,b>")
self.assertEqual(text, "-W")
self.assertIsInstance(expression, Expression)
if isinstance(expression, Expression):
self.assertEqual((expression.written, expression.start, expression.end), ("$<IF:$<BOOL:x>,a,b>", 2, 21))
self.assertEqual(written(parse("x$<A:$<B>,c>y")), "x$<A:$<B>,c>y")


class SplitTests(unittest.TestCase):
def test_a_template_splits_at_separators_outside_nested_expressions(self) -> None:
[expression] = parse("$<IF:$<AND:a,b>,x,y>")
rest = expression.rest if isinstance(expression, Expression) else None
self.assertEqual([written(part) for part in split(rest or (), ",")], ["$<AND:a,b>", "x", "y"])
self.assertEqual(split((), ","), [()])


if __name__ == "__main__":
unittest.main()
Loading