feat(spec): preserve referenced macros during removal - #334
Conversation
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
d8cf4b5 to
8457ab8
Compare
4a298a0 to
740f791
Compare
8457ab8 to
bbe0fcf
Compare
740f791 to
1771691
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved integration and macro-analysis correctness issues remain.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Adds structural RPM macro hoisting when sections or subpackages are removed, preserving referenced declarations and rejecting unsafe relocations.
Changes:
- Tracks transitive macro dependencies and preserves declaration order.
- Rejects ambiguous or unsafe hoists without modifying the spec.
- Adds focused tests and regression fixtures.
File summaries
| File | Summary |
|---|---|
internal/rpm/spec/tree_hoist.go |
Implements macro analysis, validation, and hoisting. |
internal/rpm/spec/tree_hoist_internal_test.go |
Adds focused hoisting and rejection tests. |
internal/rpm/spec/testdata/specs/subpackage-define-transitive.spec |
Covers transitive macro preservation. |
internal/rpm/spec/testdata/specs/subpackage-define-shadowed.spec |
Covers shadowed definitions. |
internal/rpm/spec/testdata/specs/subpackage-define-referenced.spec |
Covers direct macro references. |
internal/rpm/spec/testdata_test.go |
Adds fixture-based integration coverage. |
internal/rpm/spec/structural_tree_api.go |
Integrates hoisting with section removal. |
Review details
Suppressed comments (7)
internal/rpm/spec/structural_tree_api.go:188
- This changes the user-facing behavior of both
spec-remove-sectionandspec-remove-subpackage, butdocs/user/reference/config/overlays.mdstill only documents section deletion. Please document that referenced macro declarations may be hoisted and that conservativeErrUnsafeMacroHoistcases abort without changing the spec.
if err := t.hoistReferencedMacros(sections); err != nil {
return err
}
internal/rpm/spec/structural_tree_api.go:188
- An empty handle slice now reaches
hoistReferencedMacros, where no removed root ancestor exists andErrUnsafeMacroHoistis returned. Before this hook,validateSectionRemovalfollowed byremoveSectionsmadeRemoveSections(nil)a no-op; retain that behavior for callers that build a selection dynamically and can have no matches.
if err := t.hoistReferencedMacros(sections); err != nil {
return err
}
internal/rpm/spec/tree_hoist.go:466
- Dynamic invocations are only checked against removed declaration names here; this never resolves a dynamic target to a surviving lazy definition and traverses that definition's dependencies. For example, with surviving
%define suffix nameand%define rootname %{dep}, a removed%define dep value, andecho %{root%{suffix}}, the dynamic target isrootnamesodepis never selected and removal leaves a dangling%{dep}whenrootnameexpands. Resolve or conservatively reject matching surviving definitions at the invocation order.
for _, reference := range facts.references {
visit(effectiveMacroDefinition(facts.all[reference.name], reference.order), reference.order)
}
internal/rpm/spec/tree_hoist.go:616
- This treats macro-looking text in comments as a live reference. RPM does not expand a
#comment, so a removed parameterized or conditional declaration plus a surviving line such as# %{helper}will select that declaration and then fail withErrUnsafeMacroHoist, even though no surviving content needs it. Skip comment-only lines before collecting references.
if !removed {
addReferences(line, order)
}
internal/rpm/spec/tree_hoist.go:361
- A selected
%globalcan depend on a selected lazy%define, but this early return prevents validation from traversing that dependency. If%define base %{dep}is removed,%global root %{base}is later in the removed sections, and surviving%define dep newlies between the first removed section androot, the original eagerrootseesnewwhile the hoistedrootexpands before it and sees a different binding; this shape is currently accepted and silently changes the spec. Validate the complete eager dependency closure at both the original and insertion orders, or reject this case.
if definition == nil || definition.global {
return nil
internal/rpm/spec/tree_hoist.go:532
- This rejects every surviving dependency of a selected
%global, even when that dependency is already defined before the hoist insertion point. For example, a preamble%define dep /usr/libfollowed by a removed%global root %{dep}and a survivingecho %{root}is safe—the hoisted global still followsdep—but this returnsErrUnsafeMacroHoist. Compare the candidate's order withinsertionOrderinstead of treating all surviving candidates as unsafe.
if !candidate.removed || candidate.order >= definition.order {
return fmt.Errorf("cannot safely hoist eager '%%global' macro %#q before dependency %#q:\n%w",
definition.block.Name, dependency, ErrUnsafeMacroHoist)
}
internal/rpm/spec/tree_hoist.go:225
facts.undefinedrecords only whether a name was ever undefined, so any%undefinecauses a selected declaration to be rejected. A preamble%undefine foofollowed by a removed%define foo valueis safe: the hoisted definition remains after the preamble and still follows the undefine, but this returnsErrUnsafeMacroHoist. Track directive order/context and reject only when the relocation crosses a relevant%undefine.
if facts.undefined[definition.block.Name] {
return fmt.Errorf("cannot safely hoist macro %#q across '%%undefine':\n%w",
definition.block.Name, ErrUnsafeMacroHoist)
}
- Files reviewed: 7/7 changed files
- Comments generated: 1
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
bbe0fcf to
ebb8145
Compare
1771691 to
4a1f467
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical and moderate findings remain, including unsafe dependency handling and missing production-path integration.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (7)
internal/rpm/spec/structural_tree_api.go:188
RemoveSectionspreviously treated an empty handle list as a no-op, but this hook now callshoistReferencedMacros, which returnsErrUnsafeMacroHoistbecause there is no removed root ancestor. Any caller that computes an empty selection now fails instead of leaving the spec unchanged. Return early whenlen(sections) == 0before invoking the hoister.
if err := t.hoistReferencedMacros(sections); err != nil {
return err
}
internal/rpm/spec/structural_tree_api.go:188
- This hook only affects
EditorStructural; the production render/prepare path initializessourcePreparerImpl.specEditortoEditorLegacyand no caller passesWithSpecEditor(EditorStructural). Therefore the issue #203azldev comp render -p qemupath still uses the legacy removal and can droptestsdir, while these tests exercise direct structural opens. Wire the overlay path to the structural editor or implement the same preservation in the legacy editor before treating the issue as fixed.
if err := t.hoistReferencedMacros(sections); err != nil {
return err
}
internal/rpm/spec/tree_hoist.go:616
- Macro references in spec comments are treated as live references here. RPM ignores lines whose trimmed text starts with
#(the tree's own content check does the same atstructural_tree_api.go:556-560), so a surviving comment such as# %{helper}can hoist a removed%globaland change later expansion—or make an unsafe removal fail—even though no surviving content uses it. Skip comment lines before callingaddReferencesand cover this with a regression test.
if !removed {
addReferences(line, order)
}
internal/rpm/spec/tree_hoist.go:437
- Dynamic references inside a selected
%defineare recorded withdefinition.orderrather than each surviving invocation's order. Because%defineis lazy, a later removed binding can be the target at use time but is skipped by(definition.order <= dynamic.order || selected[definition]); for example,root %{dir%{suffix}}followed by removeddirnameand a surviving%{root}leavesdirnameundefined after hoisting. Propagate the actual use orders through closure/dynamic validation.
dynamics = append(dynamics, macroDynamicReference{pattern: pattern, order: definition.order})
internal/rpm/spec/tree_hoist.go:531
validateGlobalDependencytreats every surviving dependency definition as unsafe, even when it is beforeinsertionOrderand remains in the same relative position after the selected%globalis hoisted. A removed%global path %{base}/binafter a surviving preamble%global base /usr/libis safe to move, but this branch rejects it and prevents the promised preservation. Only surviving candidates that the move crosses (after the insertion point) should cause rejection; the single-binding “ambiguous” test should be adjusted accordingly.
if !candidate.removed || candidate.order >= definition.order {
return fmt.Errorf("cannot safely hoist eager '%%global' macro %#q before dependency %#q:\n%w",
definition.block.Name, dependency, ErrUnsafeMacroHoist)
internal/rpm/spec/tree_hoist.go:785
bracedMacroEnddecrements the outer macro depth for every raw}.%{expand:...}and%{lua:...}bodies legitimately contain shell/Lua braces, and the parser already treats those braces as opaque; here an inner}can terminate the scan before later%{dependency}references. A removed macro such as%define root %{expand: ... ${x} ... %{dep} ... }can therefore be hoisted withoutdep, leaving a dangling reference. Track the body syntax/raw-brace state, or reuse the parser’s macro scanner, when finding the outer close.
if content[index] == '}' {
depth--
if depth == 0 {
return index, true
internal/rpm/spec/tree_hoist.go:66
- This behavior is user-visible for both spec-removal overlays, but the checked-in overlay reference and agent guidance still only say that these overlays delete sections. Please document that referenced declarations may be hoisted in order and that conservative analysis can fail with
ErrUnsafeMacroHoist; otherwise users cannot predict the new output or failure mode.
// hoistReferencedMacros preserves only the exact declarations used by surviving
// references. RPM macro evaluation is contextual, so any ambiguous relocation
// is rejected rather than guessed.
- Files reviewed: 7/7 changed files
- Comments generated: 1
- Review effort level: Lite
| visit = func(definition *macroDefinition, useOrder int) error { | ||
| if definition == nil || definition.global { | ||
| return nil | ||
| } |
ebb8145 to
c523b5c
Compare
|
Closing this PR for now. Review surfaced unresolved ambiguity around eager |
Summary
Removing a section or subpackage can also remove
%defineor%globaldeclarations that happen to live inside it. When surviving content still references one of those macros, the rendered spec is left with a dangling reference and often fails much later during the build.This PR teaches the structural editor to preserve the complete declarations that surviving content still needs. It follows transitive dependencies and keeps declaration ordering intact. When a relocation is ambiguous or clearly unsafe, the removal fails without modifying the spec.
Motivation
Issue #203 documents this with QEMU:
%define testsdirlives in the tests subpackage, but%installcontinues to use it after that subpackage is removed. The macro declaration must survive even though the package sections do not.Changes
ErrUnsafeMacroHoistwithout modifying the spec, including:%globaldependencies or redefinitions;%globaldeclarations;spec-remove-subpackagedrops%definemacros inside the removed subpackage that are referenced elsewhere #203 coverage and focused rejection tests.Validation
mage buildmage unitThe completed structural editor also rendered the full Azure Linux evaluation corpus without parser or overlay errors, including automatic preservation of QEMU's
testsdirmacro.Known limitations
This is conservative structural and lexical analysis, not RPM macro evaluation. If azldev cannot establish a safe binding, it rejects the removal instead of guessing. Conditional same-name bindings that would require evaluating the condition remain best-effort.