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
354 changes: 265 additions & 89 deletions project_validator/build_systems/make.py

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion project_validator/build_systems/make_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,9 @@ def parse(self) -> Makefile:
return Makefile(tuple(self.top), tuple(self.errors))

def line(self, line: str, span: Span) -> None:
stripped = line.strip()
"""A line that is not a recipe line; what a conditional holds is often indented, which make ignores."""
line = line.lstrip()
stripped = line.rstrip()
if not stripped or stripped.startswith("#"):
return
if self.directive(stripped, span):
Expand Down
4 changes: 1 addition & 3 deletions project_validator/build_systems/meson/evaluation.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,13 @@
Unknown,
Value,
array,
assigned,
combined,
elements,
holds,
single,
strings,
)
from project_validator.facts import Origin
from project_validator.facts.conditions import ALWAYS, Condition, Dimension, both, either, negated
from project_validator.facts.conditions import ALWAYS, Condition, Dimension, assigned, both, combined, either, negated

BUILD_FILE = "meson.build"
MOST_ITERATIONS = 64
Expand Down
27 changes: 3 additions & 24 deletions project_validator/build_systems/meson/values.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,8 @@
from collections.abc import Iterable, Iterator
from dataclasses import dataclass

from project_validator.facts.conditions import ALWAYS, NEVER, Condition, Dimension, both, either, negated, requiring

# At most this many values of one expression are followed; the rest are left out.
MOST_CHOICES = 32
from project_validator.facts import conditions
from project_validator.facts.conditions import ALWAYS, NEVER, Condition, Dimension, both, either, requiring


@dataclass(frozen=True, slots=True)
Expand Down Expand Up @@ -69,7 +67,7 @@ class Object:


type Value = str | int | Truth | Symbol | Unknown | Array | Dictionary | Compiler | Object
type Choices = list[tuple[Value, Condition]]
type Choices = conditions.Choices[Value]

TRUE, FALSE = Truth(ALWAYS), Truth(NEVER)

Expand All @@ -92,22 +90,6 @@ def holds(choices: Choices) -> Condition:
return either(*(both(when, truth(value)) for value, when in choices))


def combined(*choices: Choices) -> Iterator[tuple[tuple[Value, ...], Condition]]:
"""Each combination of the values of several expressions, in the builds all of them take it in."""
found: list[tuple[tuple[Value, ...], Condition]] = [((), ALWAYS)]
for values in choices:
found = [
((*chosen, value), held) for chosen, when in found for value, other in values if (held := both(when, other))
][:MOST_CHOICES]
return iter(found)


def assigned(old: Choices | None, new: Choices, when: Condition) -> Choices:
"""A variable's values once it is set to `new` in the builds `when` names; other builds keep `old`."""
kept = [(value, held) for value, other in old or () if (held := both(other, negated(when)))]
return [*kept, *((value, held) for value, other in new if (held := both(other, when)))][:MOST_CHOICES]


def elements(choices: Choices) -> Iterator[tuple[Value, Condition]]:
"""The elements of an expression's values, flattened (Meson flattens nested arrays in arguments), each in its
builds."""
Expand All @@ -128,7 +110,6 @@ def array(values: Iterable[tuple[Value, Condition]]) -> Array:

__all__ = [
"FALSE",
"MOST_CHOICES",
"TRUE",
"Array",
"Choices",
Expand All @@ -140,8 +121,6 @@ def array(values: Iterable[tuple[Value, Condition]]) -> Array:
"Unknown",
"Value",
"array",
"assigned",
"combined",
"elements",
"holds",
"single",
Expand Down
26 changes: 26 additions & 0 deletions project_validator/facts/conditions.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,28 @@ def negated(condition: Condition) -> Condition:
return Condition(_DIAGRAM.negate(condition.node))


type Choices[T] = list[tuple[T, Condition]]
"""The values something takes (a variable set in branches), each with the builds it takes it in."""
# At most this many values of one thing are followed; the rest are left out.
MOST_CHOICES = 32


def assigned[T](old: Choices[T] | None, new: Choices[T], when: Condition) -> Choices[T]:
"""A variable's values once it is set to `new` in the builds `when` names; other builds keep `old`."""
kept = [(value, held) for value, other in old or () if (held := both(other, negated(when)))]
return [*kept, *((value, held) for value, other in new if (held := both(other, when)))][:MOST_CHOICES]


def combined[T](*choices: Choices[T]) -> Iterator[tuple[tuple[T, ...], Condition]]:
"""Each combination of the values of several things, in the builds all of them take it in."""
found: list[tuple[tuple[T, ...], Condition]] = [((), ALWAYS)]
for values in choices:
found = [
((*chosen, value), held) for chosen, when in found for value, other in values if (held := both(when, other))
][:MOST_CHOICES]
return iter(found)


def only(dimension: str, values: Iterable[str]) -> Condition:
"""The builds whose `dimension` takes one of `values`."""
allowed = frozenset(values)
Expand Down Expand Up @@ -274,13 +296,17 @@ def _values(found: str | tuple[str, ...]) -> tuple[str, ...]:
"CONFIGURATIONS",
"DIMENSIONS",
"LANGUAGES",
"MOST_CHOICES",
"NEVER",
"NOT",
"OTHER",
"PLATFORMS",
"Choices",
"Condition",
"Dimension",
"assigned",
"both",
"combined",
"either",
"extend",
"negated",
Expand Down
73 changes: 53 additions & 20 deletions project_validator/facts/expansion.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
A `CommandExpander` knows one way a command runs others (`npm test` runs the package's `test` script); an `Action`
knows the command a reusable CI step runs (`psf/black@stable` runs `black --check`). Expanded
commands are facts like those CI runs directly, in the same job, with `via` naming the commands that led to them.
Expansion repeats on what it finds, and stops where a definition would run itself again.
Expansion repeats on what it finds, and stops where a definition would run itself again. What holds in only some
builds (`Only`: a recipe in a makefile's `ifeq ($(OS),Windows_NT)`) is followed only in a job whose builds it may hold
in: one on a runner of that platform, or of a platform that is not known.
"""

from __future__ import annotations
Expand All @@ -18,8 +20,9 @@

from project_validator.components import known
from project_validator.evidence import DEVENV, DEVENV_HOOKS, PRE_COMMIT_CONFIGURATION
from project_validator.facts import NOTHING, ActionStep, Command, Fact, Origin, PartlyRead, Unknown, resolved
from project_validator.facts import NOTHING, ActionStep, CiJob, Command, Fact, Origin, PartlyRead, Unknown, resolved
from project_validator.facts.arguments import starts_with
from project_validator.facts.conditions import ALWAYS, DIMENSIONS, Condition, both, only
from project_validator.facts.exit_status import Shell, masked
from project_validator.facts.shell import ShellCommand, ShellSyntaxError, Unsplittable, split_script
from project_validator.templates import SHELL
Expand Down Expand Up @@ -64,7 +67,15 @@ class Launched:
env: Mapping[str, str] = NOTHING


type Expansion = Script | Invocation | Launched | Unknown
@dataclass(frozen=True, slots=True)
class Only:
"""An expansion that holds in only the builds `when` names (a recipe in a makefile's conditional)."""

expansion: Script | Unknown
when: Condition


type Expansion = Script | Invocation | Launched | Unknown | Only
type Expand = Callable[[Command, Context], Iterable[Expansion] | None]


Expand Down Expand Up @@ -284,7 +295,7 @@ def _changed(directory: str | None, argv: tuple[str, ...]) -> str | None:
OUTSIDE = "/"


def _children(command: Command, expansion: Expansion) -> Iterator[Fact]:
def _children(command: Command, expansion: Script | Invocation | Launched | Unknown) -> Iterator[Fact]:
via = (*command.via, command.origin)
if isinstance(expansion, Unknown):
yield expansion
Expand Down Expand Up @@ -331,48 +342,69 @@ def inside(context: Context, directory: str | None) -> bool:
return (context.project.root / directory).is_dir()


def expand_command(command: Command, context: Context, expanders: Iterable[CommandExpander]) -> Iterator[Fact]:
"""What `command` runs in turn, through every expander that recognises it, depth first. A command run outside the
project's own directories is not expanded."""
def expand_command(
command: Command, context: Context, expanders: Iterable[CommandExpander], where: Condition = ALWAYS
) -> Iterator[Fact]:
"""What `command`, run in the builds `where` names, runs in turn, through every expander that recognises it, depth
first. A command run outside the project's own directories is not expanded."""
if not inside(context, command.directory):
return
expanders = tuple(expanders)
chain = (*command.via, command.origin)
for expander in expanders:
try:
expansions = list(expander.expand(command, context) or ())
except ShellSyntaxError as error:
reason = f"what it runs does not split into words: {error}"
yield Unknown(origin=command.origin, subject=f"the command {command.line!r}", reason=reason)
continue
if any(isinstance(found, (Script, Invocation)) and found.origin in chain for found in expansions):
continue # a definition that runs itself, which is followed once
# A launcher runs a shorter command than its own, so launching ends.
expansions = [
found for found in expansions if not isinstance(found, Launched) or len(found.argv) < len(command.argv)
]
for expansion in expansions:
for expansion, held in _followed(command, expansions, where):
for child in _children(command, expansion):
yield child
if isinstance(child, Command):
yield from expand_command(child, context, expanders)
yield from expand_command(child, context, expanders, held)


def _followed(
command: Command, expansions: list[Expansion], where: Condition
) -> Iterator[tuple[Script | Invocation | Launched | Unknown, Condition]]:
"""The expansions to follow, each with the builds it is followed in: none, when one is a definition that runs
itself (which is followed once); and neither one that holds in none of the builds `where` names, nor a launcher's
command that is no shorter than its own (so launching ends)."""
held = [
(found.expansion, both(where, found.when)) if isinstance(found, Only) else (found, where)
for found in expansions
]
chain = (*command.via, command.origin)
if any(isinstance(found, (Script, Invocation)) and found.origin in chain for found, _ in held):
return
for found, when in held:
if when and (not isinstance(found, Launched) or len(found.argv) < len(command.argv)):
yield found, when


def _platform(job: CiJob) -> Condition:
"""The builds a job runs: those on its runner's platform, or any, when that is not known."""
return only("platforms", [job.os]) if job.os in DIMENSIONS["platforms"] else ALWAYS


def expanded(
facts: Iterable[Fact], context: Context, expanders: Iterable[CommandExpander], actions: Iterable[Action] = ()
) -> Iterator[Fact]:
"""`facts`, each command followed by what it runs in turn, and each action step by the commands it runs (and what
they run)."""
they run), in the builds of the job that runs it."""
expanders, actions = tuple(expanders), tuple(actions)
platforms: dict[str, Condition] = {}
for fact in facts:
yield fact
if isinstance(fact, Command):
yield from expand_command(fact, context, expanders)
if isinstance(fact, CiJob):
platforms[fact.id] = _platform(fact)
elif isinstance(fact, Command):
yield from expand_command(fact, context, expanders, platforms.get(fact.job, ALWAYS))
elif isinstance(fact, ActionStep):
for found in action_commands(fact, actions):
yield found
if isinstance(found, Command):
yield from expand_command(found, context, expanders)
yield from expand_command(found, context, expanders, platforms.get(fact.job, ALWAYS))


def from_hook(command: Command) -> bool:
Expand Down Expand Up @@ -453,6 +485,7 @@ def joined(directory: str | None, path: str) -> str:
"Expansion",
"Invocation",
"Launched",
"Only",
"Script",
"action_commands",
"advised",
Expand Down
Loading
Loading