From 1ee3cd0f3cc07d09fb67b1c9e5a13f805497e794 Mon Sep 17 00:00:00 2001 From: leftibot Date: Mon, 23 Nov 2026 13:42:21 -0700 Subject: [PATCH 1/3] Move Meson's choices helpers to facts.conditions, for Make to share `Choices`, `assigned` and `combined` (a variable's values set in branches, each in the builds it takes it in) were written for Meson's values, but nothing in them is Meson's. They move to `facts.conditions`, generic over the value, so that Make's evaluator can keep its variables the same way. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ByTXNqDWdM7HzezrFtEvQt --- .../build_systems/meson/evaluation.py | 4 +-- .../build_systems/meson/values.py | 27 +++---------------- project_validator/facts/conditions.py | 26 ++++++++++++++++++ 3 files changed, 30 insertions(+), 27 deletions(-) diff --git a/project_validator/build_systems/meson/evaluation.py b/project_validator/build_systems/meson/evaluation.py index 1aefd9d6..a836d86e 100644 --- a/project_validator/build_systems/meson/evaluation.py +++ b/project_validator/build_systems/meson/evaluation.py @@ -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 diff --git a/project_validator/build_systems/meson/values.py b/project_validator/build_systems/meson/values.py index 10c1709e..e300f8fb 100644 --- a/project_validator/build_systems/meson/values.py +++ b/project_validator/build_systems/meson/values.py @@ -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) @@ -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) @@ -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.""" @@ -128,7 +110,6 @@ def array(values: Iterable[tuple[Value, Condition]]) -> Array: __all__ = [ "FALSE", - "MOST_CHOICES", "TRUE", "Array", "Choices", @@ -140,8 +121,6 @@ def array(values: Iterable[tuple[Value, Condition]]) -> Array: "Unknown", "Value", "array", - "assigned", - "combined", "elements", "holds", "single", diff --git a/project_validator/facts/conditions.py b/project_validator/facts/conditions.py index bd6b4177..4adb6a98 100644 --- a/project_validator/facts/conditions.py +++ b/project_validator/facts/conditions.py @@ -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) @@ -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", From a5dc3698f03f0cd806c4e14fb813b250bc8a01ba Mon Sep 17 00:00:00 2001 From: leftibot Date: Mon, 23 Nov 2026 14:06:29 -0700 Subject: [PATCH 2/3] Read makefile lines indented with spaces, as make does Makefiles indent what a conditional holds (neovim's ` CMAKE := cmake` under `ifeq ($(UNIX_LIKE),FALSE)`). Only a tab starts a recipe line; make reads any other line as if it were not indented. The parser matched assignments, includes and rules from the line's first column, so an indented one was read as a directive and never set: neovim's CMAKE was unknown in every recipe. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ByTXNqDWdM7HzezrFtEvQt --- .../build_systems/make_syntax.py | 4 ++- tests/test_make_syntax.py | 25 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/project_validator/build_systems/make_syntax.py b/project_validator/build_systems/make_syntax.py index 1a5d0e20..1e04d3fb 100644 --- a/project_validator/build_systems/make_syntax.py +++ b/project_validator/build_systems/make_syntax.py @@ -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): diff --git a/tests/test_make_syntax.py b/tests/test_make_syntax.py index 44cbe8a4..fc0b4e16 100644 --- a/tests/test_make_syntax.py +++ b/tests/test_make_syntax.py @@ -95,6 +95,31 @@ def test_conditionals_nest_with_their_branches(self) -> None: ], ) + def test_lines_indented_with_spaces_are_read_as_written_unindented(self) -> None: + """Makefiles indent what a conditional holds (neovim's ` CMAKE := cmake`); only a tab starts a recipe line.""" + text = "ifdef WIN\n CC := cl\n include win.mk\n all: app\n\tlink app\nendif\n" + self.assertEqual( + _tree(text), + [ + ( + "if", + ( + ( + "ifdef", + "WIN", + ( + ("=", "CC", ":=", "cl"), + ("include", "win.mk", False), + ("rule", ("all",), ("app",), ""), + ("recipe", "link app"), + ), + ), + ), + None, + ) + ], + ) + def test_a_recipe_line_inside_a_conditional_is_a_node_of_its_own(self) -> None: """Which rule it belongs to is the evaluation's to say: the rule written before the conditional.""" text = "all:\nifeq ($(V),1)\n\techo verbose\nelse\n\t@echo quiet\nendif\n" From 3004954065697f29f762d8db4290110db64069d7 Mon Sep 17 00:00:00 2001 From: leftibot Date: Mon, 23 Nov 2026 14:33:54 -0700 Subject: [PATCH 3/3] Read Make conditionals as Conditions: each branch in the builds it holds in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Make read a conditional it could not decide by reading every branch, one after another. A variable set in two branches kept only the last value, and every recipe line ran on every runner: a Linux job "ran" the Windows branch's `build.bat`, and `$(RM)` was `rm -f` on Windows too. The evaluator now reads each line in the builds it holds in, a `Condition`, as Meson's and CMake's do: - A conditional's test is a `Condition`. A test the makefile and the command line decide takes its branch, as before. One on the platform (`$(OS)` is Windows_NT, or empty; what `$(shell uname -s)` prints, also through `UNAME_S := $(shell uname -s)`) holds on those platforms. Anything else the environment could decide (`ifdef DEBUG`, `ifeq ($(CC),clang)`) holds behind that requirement, so both branches may still run. - A variable holds each value in the builds its assignment was read in (`=`, `?=`, `+=` alike), and a recipe line expands to each text its variables give it, in the builds it takes it in. Prerequisites carry their builds too. - A recipe line that holds in only some builds is an `expansion.Only`. A CI job follows it only where it may hold on the job's runner; on a runner of unknown OS, everywhere. An unknown recipe in a branch that cannot hold there is not reported, and one whose program is unknown is reported once, whatever values its arguments take. Expansion is now recursive, which fixes how a variable that refers to itself was read: argo-cd's `BUILD_DATE := $(if $(BUILD_DATE),$(BUILD_DATE),…)` was substituted ten times over, doubling each time, into a 375 kB argument. A reference inside its own variable's value now stays as written (make rejects a variable that refers to itself). A reference whose name is computed (erlang.mk's `$(gen_verbose_$(V))`) is still expanded once its name is. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ByTXNqDWdM7HzezrFtEvQt --- project_validator/build_systems/make.py | 354 ++++++++++++++++++------ project_validator/facts/expansion.py | 73 +++-- tests/test_expansion.py | 172 ++++++++++-- 3 files changed, 471 insertions(+), 128 deletions(-) diff --git a/project_validator/build_systems/make.py b/project_validator/build_systems/make.py index 9055cde5..d3a9fef0 100644 --- a/project_validator/build_systems/make.py +++ b/project_validator/build_systems/make.py @@ -5,28 +5,45 @@ makefiles are followed and pattern rules (`%:`, `lint-%:`) matched to the goals they cover; a goal no rule defines is unknown. Where make runs in a directory CMake configured in place (`cmake .`), it builds that directory's CMake targets. -The makefile is parsed to a tree (`project_validator.build_systems.make_syntax`) and evaluated here, in order: a -conditional the makefile's variables and the command line decide takes its branch; one that depends on what only the -environment or the system can say (`ifeq ($(OS),Windows_NT)`, `$(shell uname)`) has every branch read, so what CI may -run is not narrowed by a guess. +The makefile is parsed to a tree (`project_validator.build_systems.make_syntax`) and evaluated here, in order, each +line in the builds it is read in (a `Condition`). A conditional the makefile's variables and the command line decide +takes its branch. One on the platform (`ifeq ($(OS),Windows_NT)`, `$(shell uname -s)`) has each branch read on the +platforms it holds on, and one on what else only the environment can say (`ifdef DEBUG`, `ifeq ($(CC),clang)`) has +each read behind that requirement, so what CI may run is not narrowed by a guess. A variable set in branches takes +each value in the builds its branch holds in, and so does a recipe line: a job follows those that may hold on its +runner (see `project_validator.facts.expansion.Only`). """ from __future__ import annotations import posixpath import re -from collections.abc import Iterator, Mapping, Sequence +from collections.abc import Callable, Iterator, Mapping, Sequence from dataclasses import dataclass, field from project_validator.build_systems import make_syntax from project_validator.core import Context from project_validator.facts import Command, Origin, Unknown from project_validator.facts.arguments import positional +from project_validator.facts.conditions import ( + ALWAYS, + MOST_CHOICES, + NEVER, + Choices, + Condition, + assigned, + both, + combined, + either, + negated, + only, + requiring, +) from project_validator.facts.exit_status import POSIX -from project_validator.facts.expansion import CommandExpander, Expansion, Script, found_at, inside, joined +from project_validator.facts.expansion import CommandExpander, Expansion, Only, Script, found_at, inside, joined from project_validator.includes import Chain, Refused, follow from project_validator.limits import MAKE_INCLUDES -from project_validator.templates import Syntax, known +from project_validator.templates import Reference, Syntax MAKEFILES = ("GNUmakefile", "makefile", "Makefile") _PROGRAMS = frozenset({"make", "gmake", "mingw32-make"}) @@ -37,14 +54,38 @@ VARIABLE = re.compile(r"\$(?:\([^()]*\)|\{[^{}]*\}|[^({$\s])") +@dataclass(frozen=True, slots=True) +class Step: + """A line of a recipe: where it is written, its text, and the builds it is read in.""" + + line: int + text: str + when: Condition = ALWAYS + + @dataclass(slots=True) class Rule: - prerequisites: list[str] = field(default_factory=list) - recipe: list[tuple[int, str]] = field(default_factory=list) + """A target's prerequisites and recipe, each in the builds it is written in.""" + + prerequisites: Choices[str] = field(default_factory=list) + recipe: list[Step] = field(default_factory=list) + + +@dataclass(frozen=True, slots=True) +class Setting: + """A value a variable is set to, and whether it is `settled`: the environment cannot change it (the command + line's, or one the makefile sets outright); make's own defaults (CC is cc), `?=` and `+=` onto a variable not yet + set give way to the environment.""" + + text: str + settled: bool = True + + +type Variables = dict[str, Choices[Setting]] # The variables make itself defines, which a makefile may use without setting. -_BUILT_IN = { +_DEFAULTS = { "CC": "cc", "CXX": "g++", "CPP": "$(CC) -E", @@ -56,11 +97,15 @@ class Rule: } +def _built_in() -> Variables: + return {name: [(Setting(value, settled=False), ALWAYS)] for name, value in _DEFAULTS.items()} + + @dataclass(slots=True) class Makefile: rules: dict[str, Rule] = field(default_factory=dict) default: str | None = None - variables: dict[str, str] = field(default_factory=lambda: dict(_BUILT_IN)) + variables: Variables = field(default_factory=_built_in) includes: list[str] = field(default_factory=list) # Why an include was not followed (a cycle, the chain too deep), each reported as unknown where make runs. problems: list[str] = field(default_factory=list) @@ -70,10 +115,64 @@ class Makefile: _REFERENCE = Syntax(re.compile(r"\$(?:\((?P[A-Za-z_][\w.-]*)\)|\{(?P[A-Za-z_][\w.-]*)\})")) -def expand_variables(line: str, variables: dict[str, str]) -> str: - """`line` with the references to `variables` replaced by their values, which may refer to others in turn; a - reference to a variable without a value stays as written.""" - return _REFERENCE.substituted(line, known(variables), rounds=10) +type _Lookup = Callable[[Reference], Choices[str] | None] + + +def _lookup(variables: Variables, *, settled: bool = False) -> _Lookup: + """The values of `variables`, each in its builds (only the `settled` ones, when asked); in the builds a variable + has no such value, a reference to it stays as written.""" + + def values(reference: Reference) -> Choices[str] | None: + found = [ + (setting.text, when) + for setting, when in variables.get(reference.name, ()) + if setting.settled or not settled + ] + if not found: + return None + rest = negated(either(*(when for _, when in found))) + return [*found, *([(reference.written, rest)] if rest else [])] + + return values + + +def _expanded(text: str, lookup: _Lookup, inside: frozenset[str] = frozenset()) -> Choices[str]: + """The texts `text` takes, its references replaced by each of their values, expanded in turn, in the builds it + takes each; a reference whose name is computed (`$(verbose_$(V))`) is expanded once its name is. A reference + inside the value of the variable it names (or of one that value refers to) stays as written: make rejects a + variable that refers to itself, and substituting it again would double it each time.""" + parts: list[Choices[str]] = [] + names = set(inside) + for part in _REFERENCE.parse(text).parts: + if isinstance(part, str): + parts.append([(part, ALWAYS)]) + elif part.name in inside or (values := lookup(part)) is None: + parts.append([(part.written, ALWAYS)]) + else: + names.add(part.name) + parts.append(_within(values, lookup, inside | {part.name})) + joined = [("".join(chosen), when) for chosen, when in combined(*parts)] + # Each pass that substitutes guards more names, so expanding again ends. + return joined if names == inside else _within(joined, lookup, frozenset(names)) + + +def _within(values: Choices[str], lookup: _Lookup, inside: frozenset[str]) -> Choices[str]: + """Each of `values` expanded (see `_expanded`), in the builds both it and its expansion are in.""" + expanded = ( + (new, held) + for value, when in values + for new, other in _expanded(value, lookup, inside) + if (held := both(when, other)) + ) + return list(expanded)[:MOST_CHOICES] + + +def _choices(text: str, lookup: _Lookup) -> Choices[str]: + """`text` expanded in each build (see `_expanded`); the builds that give the same text are one choice.""" + merged: dict[str, Condition] = {} + for value, when in _expanded(text, lookup): + merged[value] = either(merged.get(value, NEVER), when) + return list(merged.items()) # Why a recipe line written after `-` cannot fail make. @@ -86,18 +185,17 @@ def _recipe_line(line: str) -> str: class _Evaluation: - """A walk over a makefile's tree, in order, as make reads it: variables are set as they are assigned (the command - line's `overrides` win over the makefile's, unless it says `override`), recipe lines go to the rules written - before them, and each conditional is decided where it can be (see `_holds`).""" + """A walk over a makefile's tree, in order, as make reads it, each line in the builds `when` names: variables are + set as they are assigned (the command line's `overrides` win over the makefile's, unless it says `override`), + recipe lines go to the rules written before them, and each branch of a conditional is read where it holds (see + `_Test`).""" def __init__(self, overrides: Mapping[str, str]) -> None: self.makefile = Makefile() - self.makefile.variables.update(overrides) + self.makefile.variables.update({name: [(Setting(value), ALWAYS)] for name, value in overrides.items()}) self.overrides = frozenset(overrides) - # The variables whose value the environment cannot change: the command line's, and those the makefile sets - # outright. make's own defaults (CC is cc), `?=` and `+=` onto a variable not yet set give way to it. - self.settled = set(overrides) self.current: list[Rule] = [] + self.when = ALWAYS def nodes(self, nodes: Sequence[make_syntax.Node]) -> None: for node in nodes: @@ -106,11 +204,12 @@ def nodes(self, nodes: Sequence[make_syntax.Node]) -> None: def node(self, node: make_syntax.Node) -> None: if isinstance(node, make_syntax.RecipeLine): for rule in self.current: - rule.recipe.append((node.span.line, _recipe_line(node.text))) + rule.recipe.append(Step(node.span.line, _recipe_line(node.text), self.when)) elif isinstance(node, make_syntax.Assignment): self.assign(node) elif isinstance(node, make_syntax.Include): - self.makefile.includes += expand_variables(node.files, self.makefile.variables).split() + lookup = _lookup(self.makefile.variables) + self.makefile.includes += [name for files, _ in _choices(node.files, lookup) for name in files.split()] elif isinstance(node, make_syntax.Rule): self.rule(node) elif isinstance(node, make_syntax.Conditional): @@ -119,66 +218,115 @@ def node(self, node: make_syntax.Node) -> None: self.current = [] # any other line ends the recipe before it def assign(self, node: make_syntax.Assignment) -> None: - """Set the variable; `!=` (a shell command's output) has no value to read.""" + """Set the variable in the builds the assignment is read in; `!=` (a shell command's output) has no value to + read.""" variables = self.makefile.variables if node.how == "!=" or (node.name in self.overrides and not node.override): return + old = variables.get(node.name, []) + unset = both(self.when, negated(either(*(when for _, when in old)))) if node.how == "?=": - variables.setdefault(node.name, node.value) + variables[node.name] = [*old, *([(Setting(node.value, settled=False), unset)] if unset else [])] elif node.how == "+=": - variables[node.name] = f"{variables[node.name]} {node.value}" if node.name in variables else node.value + appended = [(Setting(f"{setting.text} {node.value}", setting.settled), when) for setting, when in old] + variables[node.name] = assigned(old, appended, self.when) + if unset: + variables[node.name].append((Setting(node.value, settled=False), unset)) else: - variables[node.name] = node.value - self.settled.add(node.name) + variables[node.name] = assigned(old, [(Setting(node.value), ALWAYS)], self.when) def rule(self, node: make_syntax.Rule) -> None: makefile = self.makefile self.current = [makefile.rules.setdefault(target, Rule()) for target in node.targets] for rule in self.current: - rule.prerequisites += node.prerequisites + rule.prerequisites += [(prerequisite, self.when) for prerequisite in node.prerequisites] if node.recipe: - rule.recipe.append((node.span.line, _recipe_line(node.recipe))) + rule.recipe.append(Step(node.span.line, _recipe_line(node.recipe), self.when)) if makefile.default is None: makefile.default = next((target for target in node.targets if not target.startswith(".")), None) def conditional(self, node: make_syntax.Conditional) -> None: - """The first branch that holds; where one cannot be decided, it and every later branch are read.""" - settled = {name: self.makefile.variables[name] for name in self.settled} - for index, branch in enumerate(node.branches): - holds = _holds(branch, settled) - if holds is None: - for undecided in node.branches[index:]: - self.nodes(undecided.body) - self.nodes(node.otherwise or ()) - return - if holds: - self.nodes(branch.body) - return - self.nodes(node.otherwise or ()) - - -def _holds(branch: make_syntax.Branch, variables: Mapping[str, str]) -> bool | None: - """Whether the branch's test holds, from the settled `variables`; None when the makefile and the command line - cannot say: a variable they do not settle (the environment may set it), or a reference left unexpanded (`$(shell - uname)`, a function).""" - if branch.test in ("ifdef", "ifndef"): - name = _known(branch.arguments.strip(), variables) - if name is None or name not in variables: - return None - return bool(variables[name].strip()) == (branch.test == "ifdef") - compared = _compared(branch.arguments) - if compared is None: - return None - left, right = (_known(side, variables) for side in compared) - if left is None or right is None: - return None - return (left.strip() == right.strip()) == (branch.test == "ifeq") - - -def _known(text: str, variables: Mapping[str, str]) -> str | None: - """`text` with its references expanded, or None when one is left that the variables cannot expand.""" - expanded = expand_variables(text.replace("$$", _ESCAPED_DOLLAR), dict(variables)) - return None if VARIABLE.search(expanded) else expanded.replace(_ESCAPED_DOLLAR, "$") + """Each branch, read in the builds where it holds and no branch before it does; what none holds in, after.""" + remaining = self.when + for branch in node.branches: + holds = _Test(self.makefile.variables).holds(branch) + self.within(both(remaining, holds), branch.body) + remaining = both(remaining, negated(holds)) + self.within(remaining, node.otherwise or ()) + + def within(self, when: Condition, nodes: Sequence[make_syntax.Node]) -> None: + if not when: + return # a branch that holds in no build is not read + outer, self.when = self.when, when + self.nodes(nodes) + self.when = outer + + +class _Test: + """Where a conditional's test holds, from the settled values of `variables`. What the makefile and the command + line cannot say (a variable they do not settle, a reference left unexpanded, `$(shell uname)`) holds behind a + requirement, or, where it names the platform, on the platforms it holds on (see `_platform`).""" + + def __init__(self, variables: Variables) -> None: + self.variables = variables + self.lookup = _lookup(variables, settled=True) + + def holds(self, branch: make_syntax.Branch) -> Condition: + positive = branch.test in ("ifdef", "ifeq") + held = self.defined(branch.arguments.strip()) if branch.test in ("ifdef", "ifndef") else self.equal(branch) + return held if positive else negated(held) + + def defined(self, written: str) -> Condition: + """Where the variable `written` names has a value that is not empty (make does not expand it to say).""" + found: list[Condition] = [] + for name, when in self.expanded(written): + settled = [(setting, held) for setting, held in self.variables.get(name, ()) if setting.settled] + decided = either(*(held for _, held in settled)) + nonempty = either(*(held for setting, held in settled if setting.text.strip())) + unknown = both(negated(decided), requiring(f"defined {name}")) + found.append(both(when, either(nonempty, unknown))) + return either(*found) + + def equal(self, branch: make_syntax.Branch) -> Condition: + compared = _compared(branch.arguments) + if compared is None: + return requiring(branch.arguments.strip()) + left, right = (self.expanded(side) for side in compared) + return either(*(both(when, _equal(*sides)) for sides, when in combined(left, right))) + + def expanded(self, text: str) -> Choices[str]: + """`text` expanded in each build, its `$$` kept apart (see `_ESCAPED_DOLLAR`), and stripped.""" + return [(value.strip(), when) for value, when in _choices(text.replace("$$", _ESCAPED_DOLLAR), self.lookup)] + + +def _equal(left: str, right: str) -> Condition: + """Where two expanded texts are equal: in every build or none, when neither holds a reference left unexpanded.""" + if not VARIABLE.search(left) and not VARIABLE.search(right): + return ALWAYS if left == right else NEVER + platform = _platform(left, right) + return platform if platform is not None else requiring(f"{left} == {right}") + + +# What `uname -s` prints on each platform: Windows's are MSYS2's, Cygwin's and MinGW's. +_UNAME = re.compile(r"\$[({]shell\s+uname(?:\s+-s)?\s*[)}]") +_UNAME_PLATFORMS = {"Linux": "linux", "Darwin": "macos"} +_WINDOWS_UNAME = ("MINGW", "MSYS", "CYGWIN") + + +def _platform(left: str, right: str) -> Condition | None: + """Where one side names the platform and the other is plain text: `$(OS)`, which Windows sets to Windows_NT (and + others leave empty), or what `$(shell uname -s)` prints. None for any other comparison.""" + for probe, text in ((left, right), (right, left)): + if VARIABLE.search(text): + continue + if probe in ("$(OS)", "${OS}") and text in ("Windows_NT", ""): + windows = only("platforms", ["windows"]) + return windows if text else negated(windows) + if _UNAME.fullmatch(probe): + if text.startswith(_WINDOWS_UNAME): + return only("platforms", ["windows"]) + return only("platforms", [_UNAME_PLATFORMS[text]]) if text in _UNAME_PLATFORMS else None + return None _QUOTED_PAIR = re.compile(r"""^(?P["'])(?P.*?)(?P=q1)\s+(?P["'])(?P.*?)(?P=q2)$""") @@ -220,33 +368,61 @@ def _rule(makefile: Makefile, target: str) -> tuple[Rule, str] | None: return None -def _recipes(makefile: Makefile, path: str, target: str, visited: set[str]) -> Iterator[Script | Unknown]: +def _recipes( + makefile: Makefile, path: str, target: str, visited: set[str], when: Condition = ALWAYS +) -> Iterator[Expansion]: + """The recipe lines `target` runs in the builds `when` names, after its prerequisites', each line once in each + of the texts its variables give it, in the builds it takes it in.""" if target in visited or (found := _rule(makefile, target)) is None: return visited.add(target) rule, stem = found - for prerequisite in rule.prerequisites: - yield from _recipes(makefile, path, prerequisite.replace("%", stem), visited) - automatic = {**makefile.variables, "@": target, "*": stem} - for number, line in rule.recipe: - origin = Origin(path=path, at=(target, number)) + for prerequisite, written in rule.prerequisites: + if held := both(when, written): + yield from _recipes(makefile, path, prerequisite.replace("%", stem), visited, held) + lookup = _lookup(makefile.variables) + for step in rule.recipe: + origin = Origin(path=path, at=(target, step.line)) # A variable may hold the recipe's prefixes (`Q = @`, then `$(Q)$(CC) …`). # `$$` is a `$` the shell sees, never a reference (Documenter's `$$(biome_jll.biome())`). - line = line.replace("$$", _ESCAPED_DOLLAR).replace("$@", target).replace("$*", stem) - expanded = expand_variables(line, automatic) - unprefixed = expanded.lstrip("@-+ ") - text = unprefixed.replace(_ESCAPED_DOLLAR, "$") - ignored = _IGNORED if "-" in expanded[: len(expanded) - len(unprefixed)] else "" - if (program := _REFERENCE.parse(text).leading) is not None: - name = program.name - yield Unknown( - origin=origin, - subject=f"the recipe {text!r}", - reason=f"its program is the variable {name}, which neither the makefile nor the command line sets", - ) - continue - # Each recipe line is a shell script of its own, run by `sh -c`. - yield Script(text=text, origin=origin, opaque=VARIABLE, shell=POSIX, advisory=ignored) + line = step.text.replace("$$", _ESCAPED_DOLLAR).replace("$@", target).replace("$*", stem) + yield from _step(_choices(line, lookup), origin, both(when, step.when)) + + +def _step(texts: Choices[str], origin: Origin, when: Condition) -> Iterator[Expansion]: + """A recipe line, in the builds `when` names, in each of the `texts` it takes: a shell script in each, but, where + its program is still a variable, one unknown, in every build any of those texts is in.""" + unknown: Unknown | None = None + unknown_in = NEVER + for expanded, chosen in texts: + if held := both(when, chosen): + recipe = _recipe(expanded, origin) + if isinstance(recipe, Script): + yield _only(recipe, held) + continue + unknown, unknown_in = unknown or recipe, either(unknown_in, held) + if unknown is not None: + yield _only(unknown, unknown_in) + + +def _only(expansion: Script | Unknown, when: Condition) -> Expansion: + return expansion if when == ALWAYS else Only(expansion, when) + + +def _recipe(expanded: str, origin: Origin) -> Script | Unknown: + """A recipe line, expanded: the shell script it runs, or, when its program is still a variable, that what it runs + is unknown.""" + unprefixed = expanded.lstrip("@-+ ") + text = unprefixed.replace(_ESCAPED_DOLLAR, "$") + ignored = _IGNORED if "-" in expanded[: len(expanded) - len(unprefixed)] else "" + if (program := _REFERENCE.parse(text).leading) is not None: + return Unknown( + origin=origin, + subject=f"the recipe {text!r}", + reason=f"its program is the variable {program.name}, which neither the makefile nor the command line sets", + ) + # Each recipe line is a shell script of its own, run by `sh -c`. + return Script(text=text, origin=origin, opaque=VARIABLE, shell=POSIX, advisory=ignored) _OPTIONS = frozenset({"-C", "--directory", "-f", "--file", "-j", "--jobs"}) diff --git a/project_validator/facts/expansion.py b/project_validator/facts/expansion.py index c281c7c9..b2738e44 100644 --- a/project_validator/facts/expansion.py +++ b/project_validator/facts/expansion.py @@ -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 @@ -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 @@ -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] @@ -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 @@ -331,13 +342,14 @@ 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 ()) @@ -345,34 +357,54 @@ def expand_command(command: Command, context: Context, expanders: Iterable[Comma 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: @@ -453,6 +485,7 @@ def joined(directory: str | None, path: str) -> str: "Expansion", "Invocation", "Launched", + "Only", "Script", "action_commands", "advised", diff --git a/tests/test_expansion.py b/tests/test_expansion.py index 20f0640e..a2842976 100644 --- a/tests/test_expansion.py +++ b/tests/test_expansion.py @@ -6,10 +6,11 @@ import unittest from typing import ClassVar -from project_validator.build_systems.make import parse_makefile +from project_validator.build_systems.make import Makefile, parse_makefile from project_validator.ecosystems.python.tox import braces from project_validator.facts import Command, Facts, Origin, Unknown, as_dict, resolved from project_validator.facts.arguments import positional +from project_validator.facts.conditions import ALWAYS from project_validator.facts.expansion import CommandExpander, known_expanders from project_validator.facts.tools import ToolRun from tests.support import GITHUB_WORKFLOW, github_job, github_steps, make_context, temp_project @@ -24,6 +25,18 @@ def _expanded(facts: Facts) -> list[tuple[str, ...]]: return [command.argv for command in facts.of(Command) if command.via] +def _recipe(makefile: Makefile, target: str) -> list[tuple[int, str]]: + return [(step.line, step.text) for step in makefile.rules[target].recipe] + + +def _value(makefile: Makefile, name: str) -> str: + """The value of a variable set once, in every build.""" + ((setting, when),) = makefile.variables[name] + if when != ALWAYS: + raise AssertionError(f"{name} is set in only some builds") + return setting.text + + class EngineTests(unittest.TestCase): def test_expanders_are_found_in_profiles_and_shared_modules(self) -> None: names = {expander.name for expander in known_expanders()} @@ -140,8 +153,8 @@ def test_rules_their_prerequisites_and_the_default_goal(self) -> None: makefile = parse_makefile(self.MAKEFILE) self.assertEqual(makefile.default, "all") self.assertEqual(list(makefile.rules), [".PHONY", "all", "build", "check", "lint"]) - self.assertEqual(makefile.rules["check"].recipe, [(7, "./app --selftest"), (8, "-make -C docs lint")]) - self.assertEqual(makefile.rules["lint"].recipe[0][0], 10) + self.assertEqual(_recipe(makefile, "check"), [(7, "./app --selftest"), (8, "-make -C docs lint")]) + self.assertEqual(_recipe(makefile, "lint")[0][0], 10) def test_make_runs_the_named_targets_after_their_prerequisites(self) -> None: files = {"Makefile": self.MAKEFILE, **github_job("ubuntu-latest", "make check")} @@ -162,25 +175,21 @@ def test_the_makefile_is_found_where_make_runs(self) -> None: def test_comments_and_blank_lines_keep_a_recipe_open_and_other_lines_close_it(self) -> None: makefile = parse_makefile("a:\n\techo 1\n# note\n\n\techo 2\nvpath %.c src\n\techo 3\n") - self.assertEqual(makefile.rules["a"].recipe, [(2, "echo 1"), (5, "echo 2")]) + self.assertEqual(_recipe(makefile, "a"), [(2, "echo 1"), (5, "echo 2")]) def test_assignments_append_default_and_drop_comments(self) -> None: makefile = parse_makefile("A = x\nA += y\nB ?= 1\nB ?= 2\nC += z\nD = a b # note # more\nE := e\n") - variables = makefile.variables - self.assertEqual( - (variables["A"], variables["B"], variables["C"], variables["D"], variables["E"]), - ("x y", "1", "z", "a b", "e"), - ) + self.assertEqual([_value(makefile, name) for name in "ABCDE"], ["x y", "1", "z", "a b", "e"]) def test_includes_and_prerequisites_accumulate(self) -> None: makefile = parse_makefile("include a.mk\ninclude b.mk c.mk\nx: a\nx: b c\n") self.assertEqual(makefile.includes, ["a.mk", "b.mk", "c.mk"]) - self.assertEqual(makefile.rules["x"].prerequisites, ["a", "b", "c"]) + self.assertEqual(makefile.rules["x"].prerequisites, [("a", ALWAYS), ("b", ALWAYS), ("c", ALWAYS)]) def test_continued_lines_are_numbered_by_their_first_line(self) -> None: makefile = parse_makefile("a: \\\n b \\\n c\n\techo \\\n\t done\n") - self.assertEqual(makefile.rules["a"].prerequisites, ["b", "c"]) - self.assertEqual([number for number, _ in makefile.rules["a"].recipe], [4]) + self.assertEqual(makefile.rules["a"].prerequisites, [("b", ALWAYS), ("c", ALWAYS)]) + self.assertEqual([number for number, _ in _recipe(makefile, "a")], [4]) def test_recipe_prefixes_are_not_part_of_the_command(self) -> None: files = {"Makefile": "all:\n\t@echo a\n\t-echo b\n\t+echo c\n\t@-echo d\n", **github_job("x", "make")} @@ -202,12 +211,137 @@ def test_the_command_line_decides_a_conditional(self) -> None: files = {"Makefile": makefile, **github_job("x", "make DEBUG=1")} self.assertEqual(_expanded(_facts(files)), [("cc", "-g", "a.c")]) - def test_a_conditional_on_the_environment_reads_every_branch(self) -> None: - """Where the makefile cannot say (the OS make runs on, a variable only the environment may set), every branch - is read, as when conditionals were not followed: what CI may run is not narrowed by a guess.""" - makefile = "all:\nifeq ($(OS),Windows_NT)\n\tbuild.bat\nelse\n\t./build.sh\nendif\n" - files = {"Makefile": makefile, **github_job("x", "make")} - self.assertEqual(_expanded(_facts(files)), [("build.bat",), ("./build.sh",)]) + def test_a_conditional_on_the_os_is_read_for_the_os_the_job_runs_on(self) -> None: + """Windows sets `OS` to Windows_NT, and `uname -s` names the others: each branch holds on its own OS, so a + job runs the branches that hold on its runner. On a runner of unknown OS every branch is read: what CI may run + is not narrowed by a guess.""" + windows = "all:\nifeq ($(OS),Windows_NT)\n\tbuild.bat\nelse\n\t./build.sh\nendif\n" + uname = ( + "UNAME_S := $(shell uname -s)\n" + "all:\nifeq ($(UNAME_S),Darwin)\n\tbrew bundle\nelse\n\tapt-get check\nendif\n" + ) + for makefile, runner, expected in ( + (windows, "ubuntu-latest", [("./build.sh",)]), + (windows, "windows-latest", [("build.bat",)]), + (windows, "self-hosted", [("build.bat",), ("./build.sh",)]), + (uname, "macos-latest", [("brew", "bundle")]), + (uname, "ubuntu-latest", [("apt-get", "check")]), + ): + with self.subTest(makefile=makefile.splitlines()[0], runner=runner): + files = {"Makefile": makefile, **github_job(runner, "make")} + self.assertEqual(_expanded(_facts(files)), expected) + + def test_a_variable_set_in_branches_takes_each_value_where_its_branch_holds(self) -> None: + makefile = "ifeq ($(OS),Windows_NT)\nRM = del /q\nelse\nRM = rm -f\nendif\nclean:\n\t$(RM) out\n" + for runner, expected in ( + ("ubuntu-latest", [("rm", "-f", "out")]), + ("windows-latest", [("del", "/q", "out")]), + ("self-hosted", [("del", "/q", "out"), ("rm", "-f", "out")]), + ): + with self.subTest(runner=runner): + files = {"Makefile": makefile, **github_job(runner, "make clean")} + self.assertEqual(sorted(_expanded(_facts(files))), expected) + + def test_a_conditional_on_a_variable_set_in_branches_holds_where_its_values_do(self) -> None: + makefile = ( + "ifeq ($(OS),Windows_NT)\nEXE = .exe\nelse\nEXE =\nendif\n" + "all:\nifeq ($(EXE),.exe)\n\twin-test\nelse\n\tposix-test\nendif\n" + ) + for runner, expected in (("ubuntu-latest", [("posix-test",)]), ("windows-latest", [("win-test",)])): + with self.subTest(runner=runner): + files = {"Makefile": makefile, **github_job(runner, "make")} + self.assertEqual(_expanded(_facts(files)), expected) + + def test_appending_or_defaulting_in_a_branch_changes_only_its_builds(self) -> None: + makefile = ( + "FLAGS = -O2\nifeq ($(OS),Windows_NT)\nFLAGS += /W4\nNAME ?= app.exe\nendif\nNAME ?= app\n" + "all:\n\tcc $(FLAGS) -o $(NAME)\n" + ) + for runner, expected in ( + ("ubuntu-latest", [("cc", "-O2", "-o", "app")]), + ("windows-latest", [("cc", "-O2", "/W4", "-o", "app.exe")]), + ): + with self.subTest(runner=runner): + files = {"Makefile": makefile, **github_job(runner, "make")} + self.assertEqual(_expanded(_facts(files)), expected) + + def test_ifdef_on_a_variable_set_in_some_builds_is_decided_only_there(self) -> None: + """Where the makefile leaves DEBUG unset, the environment may set it: both branches may run.""" + makefile = "ifeq ($(OS),Windows_NT)\nDEBUG = 1\nendif\nall:\nifdef DEBUG\n\tcc -g\nelse\n\tcc -O2\nendif\n" + for runner, expected in ( + ("windows-latest", [("cc", "-g")]), + ("ubuntu-latest", [("cc", "-g"), ("cc", "-O2")]), + ): + with self.subTest(runner=runner): + files = {"Makefile": makefile, **github_job(runner, "make")} + self.assertEqual(_expanded(_facts(files)), expected) + + def test_other_ways_of_naming_the_platform(self) -> None: + """`$(OS)` is empty off Windows; MSYS2's, MinGW's and Cygwin's `uname -s` name Windows.""" + makefile = "all:\nifeq ($(OS),)\n\tposix\nendif\nifeq ($(shell uname),MINGW64_NT-10.0)\n\tmingw\nendif\n" + for runner, expected in (("ubuntu-latest", [("posix",)]), ("windows-latest", [("mingw",)])): + with self.subTest(runner=runner): + files = {"Makefile": makefile, **github_job(runner, "make")} + self.assertEqual(_expanded(_facts(files)), expected) + + def test_a_recipe_unknown_only_in_a_branch_that_does_not_hold_is_not_unknown(self) -> None: + makefile = "all:\nifeq ($(OS),Windows_NT)\n\t$(MSBUILD) app.sln\nelse\n\tninja\nendif\n" + for runner, unknown in (("ubuntu-latest", []), ("windows-latest", ["the recipe '$(MSBUILD) app.sln'"])): + with self.subTest(runner=runner): + facts = _facts({"Makefile": makefile, **github_job(runner, "make")}) + self.assertEqual( + [fact.subject for fact in facts.of(Unknown) if fact.subject.startswith("the recipe")], unknown + ) + + def test_a_value_or_prerequisite_from_the_other_branch_is_not_followed_inside_this_one(self) -> None: + """Inside the Windows branch, `$(X)` is only Windows's value, and a prerequisite written for the others is no + prerequisite.""" + makefile = ( + "ifeq ($(OS),Windows_NT)\nX = a\nall: tool\nelse\nX = b\ntool: gen\nendif\n" + "tool:\nifeq ($(OS),Windows_NT)\n\techo $(X)\nendif\ngen:\n\tgenerate\n" + ) + files = {"Makefile": makefile, **github_job("windows-latest", "make")} + self.assertEqual(_expanded(_facts(files)), [("echo", "a")]) + + def test_conditionals_written_other_ways(self) -> None: + """`ifeq "a" "b"` compares as `ifeq (a,b)` does; one that cannot be read holds behind a requirement, so both + branches may run.""" + quoted = 'all:\nifeq "$(OS)" "Windows_NT"\n\tbuild.bat\nelse\n\t./build.sh\nendif\n' + unread = "all:\nifeq $(OS)\n\tbuild.bat\nelse\n\t./build.sh\nendif\n" + one_side = "all:\nifeq ($(OS))\n\tbuild.bat\nelse\n\t./build.sh\nendif\n" + both_branches = [("build.bat",), ("./build.sh",)] + for makefile, expected in ((quoted, [("./build.sh",)]), (unread, both_branches), (one_side, both_branches)): + with self.subTest(makefile=makefile.splitlines()[1]): + files = {"Makefile": makefile, **github_job("ubuntu-latest", "make")} + self.assertEqual(_expanded(_facts(files)), expected) + + def test_a_reference_whose_name_is_computed_is_expanded_once_its_name_is(self) -> None: + """erlang.mk's `gen_verbose = $(gen_verbose_$(V))`, with `V ?= 0`, is `gen_verbose_0`'s value.""" + makefile = "V ?= 0\nq_0 = @\nQ = $(q_$(V))\nall:\n\t$(Q)echo hi\n" + files = {"Makefile": makefile, **github_job("ubuntu-latest", "make")} + self.assertEqual(_expanded(_facts(files)), [("echo", "hi")]) + + def test_a_reference_to_a_variable_inside_its_own_value_stays_as_written(self) -> None: + """make rejects a variable that refers to itself; argo-cd's `BUILD_DATE := $(if $(BUILD_DATE),$(BUILD_DATE),…)` + refers to what the environment sets. Substituted again and again, its value would double each time.""" + makefile = "A = $(A) x\nD := $(if $(D),$(D),now)\nall:\n\techo $(A)\n\techo $(D)\n" + files = {"Makefile": makefile, **github_job("ubuntu-latest", "make")} + expanded = _expanded(_facts(files)) + self.assertIn(("echo", "$(A)", "x"), expanded) + self.assertIn(("echo", "$(if $(D),$(D),now)"), expanded) + + def test_a_recipe_whose_program_is_unknown_is_reported_once_whatever_its_arguments(self) -> None: + makefile = "ifdef DEBUG\nFLAGS = -g\nelse\nFLAGS = -O2\nendif\nall:\n\t$(TOOL) $(FLAGS)\n" + facts = _facts({"Makefile": makefile, **github_job("ubuntu-latest", "make")}) + recipes = [fact.subject for fact in facts.of(Unknown) if fact.subject.startswith("the recipe")] + self.assertEqual(recipes, ["the recipe '$(TOOL) -g'"]) + + def test_a_rule_written_in_a_branch_runs_only_where_it_holds(self) -> None: + makefile = "all: test\nifeq ($(OS),Windows_NT)\nall: package\nendif\ntest:\n\tctest\npackage:\n\tcpack\n" + for runner, expected in (("ubuntu-latest", [("ctest",)]), ("windows-latest", [("ctest",), ("cpack",)])): + with self.subTest(runner=runner): + files = {"Makefile": makefile, **github_job(runner, "make")} + self.assertEqual(_expanded(_facts(files)), expected) def test_what_the_environment_may_override_decides_no_conditional(self) -> None: """make's own defaults (CC is cc) and `?=` give way to the environment, which CI often sets (CC=clang): a @@ -229,7 +363,7 @@ def test_a_branch_not_taken_defines_nothing(self) -> None: def test_a_define_body_is_no_rule(self) -> None: makefile = parse_makefile("define HELP\nusage: make all\nendef\nall:\n\techo ok\n") self.assertEqual((makefile.default, list(makefile.rules)), ("all", ["all"])) - self.assertEqual(makefile.variables["HELP"], "usage: make all") + self.assertEqual(_value(makefile, "HELP"), "usage: make all") def test_includes_of_included_makefiles_are_followed(self) -> None: files = {