Skip to content

fix(issue#4358): parent selector list in selector - #4403

Closed
matthew-dean wants to merge 2 commits into
less:masterfrom
matthew-dean:pr-4369-rebased
Closed

matthew-dean wants to merge 2 commits into
less:masterfrom
matthew-dean:pr-4369-rebased

Conversation

@matthew-dean

@matthew-dean matthew-dean commented Mar 9, 2026 •

Copy link
Copy Markdown
Member

Rebased version of #4369 by @puckowski. Resolves conflicts with current master.

Original PR: #4369
Fixes: #4358

Credit: @puckowski

Summary by CodeRabbit

  • Improvements

    • Improved nested selector processing to better handle parent selector scenarios and complex selector combinations in Less
  • Tests

    • Expanded test coverage for pseudo-class selectors using :is() and :not() with various descendant and relative selector patterns

* Fix for issue less#4358 that correctly expands parent selectors in a list
  in a selector.
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Mar 9, 2026
@coderabbitai

coderabbitai Bot commented Mar 9, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@matthew-dean has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 2 minutes and 37 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2b307d6f-1621-41c3-8b56-429765fa08df

📥 Commits

Reviewing files that changed from the base of the PR and between 81dd8de and 5c99678.

📒 Files selected for processing (1)
  • packages/test-data/tests-unit/selectors/selectors.css
📝 Walkthrough

Walkthrough

This patch enhances the ruleset merging logic to properly handle parent selectors (\&) within nested pseudo-selectors like :is() and :not() containing multiple selectors. It introduces detection for future parent selectors and reconstructs selectors accordingly, with corresponding test cases validating the expected output.

Changes

Cohort / File(s) Summary
Ruleset Merging Logic
packages/less/src/less/tree/ruleset.js
Adds hasFutureParentSelector detection and new selector reconstruction logic for handling parent symbols in nested pseudo-selectors with multiple selectors. Introduces tracking of nestedPaths, replacements, and context reset mechanisms when parent selectors are detected.
Test Data
packages/test-data/tests-unit/selectors/selectors.less, packages/test-data/tests-unit/selectors/selectors.css
Adds four test cases using :is() and :not() pseudo-selectors with parent symbol references, providing expected Less input and compiled CSS output validation.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 Nested selectors dance with care,
Parent symbols now compile fair,
:is() and :not() sing in tune,
Beneath the hoppy moon,
Multiple paths found their groove—bugs skipped without a hitch!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly references the issue being fixed (#4358) and describes the main change: fixing parent selector expansion in selector lists.
Linked Issues check ✅ Passed The changes implement the required fix for issue #4358 by adding logic to handle parent selectors in nested pseudo-selectors with selector lists, and include test cases validating the expected behavior.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing issue #4358: the main logic fix in ruleset.js and corresponding test cases in the selectors test files.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/less/src/less/tree/ruleset.js`:
- Around line 799-824: The variable currentReplacedSelectors in ruleset.js is
never populated and its loop is dead code; remove the declaration of
currentReplacedSelectors and the inner loop that pushes its items into
replacedNewSelectors, then ensure logic around newSelectors/currentElements
remains consistent (the surrounding code uses replaceParentSelector,
nestedSelector, addAllReplacementsIntoPath and currentElements to build
replacedNewSelectors—so either remove the unused currentReplacedSelectors
references or if intended, add a clear TODO and implement population where
appropriate).
- Around line 745-788: The loop over selector.elements uses inSelectorIndex to
read inSelector.elements without bounds checking and increments it every
iteration, causing out-of-bounds or misaligned comparisons after splice; fix by
guarding the access and synchronizing increments: before referencing
inSelector.elements[inSelectorIndex] ensure inSelectorIndex <
inSelector.elements.length, and change the logic so inSelectorIndex is only
incremented when you consume/advance the corresponding inSelector element (i.e.,
when you do NOT splice selector.elements[k]); apply this change inside the loop
that splices selector.elements (referencing selector.elements, inSelector,
inSelectorIndex, splice, and the surrounding loop that builds
context/newSelectors) so comparisons and increments stay in sync and no read
from undefined occurs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 65833285-f66c-4f0d-9452-649b260ee91c

📥 Commits

Reviewing files that changed from the base of the PR and between 774f188 and 81dd8de.

📒 Files selected for processing (3)
  • packages/less/src/less/tree/ruleset.js
  • packages/test-data/tests-unit/selectors/selectors.css
  • packages/test-data/tests-unit/selectors/selectors.less

Comment on lines +745 to +788
let hasFutureParentSelector = false;
if (nestedSelector.elements && nestedSelector.elements.length > 0) {
if (nestedSelector.elements[0].value === '&' || (nestedSelector.elements[0].elements && nestedSelector.elements[0].elements[0].value === '&')) {
hasFutureParentSelector = true;
}
}
if (hadParentSelector || hasFutureParentSelector) {
context = [[]];
for (let index = 0; index < newSelectors.length; index++) {
for (let j = 0; j < newSelectors[index].length; j++) {
let selector = newSelectors[index][j];
if (selector && selector.elements) {
const eleCopy = [];
selector.elements.forEach(element => {
eleCopy.push(new Element(
element.combinator,
element.value,
element.isVariable,
element._index,
element._fileInfo
));
});
selector = new Selector(
eleCopy,
selector.extendList,
selector.condition,
selector.index,
selector.currentFileInfo,
selector.visibilityInfo && selector.visibilityInfo()
);
let inSelectorIndex = 0;
for (let k = 0; k < selector.elements.length; k++) {
if (/^[:[]/.test(selector.elements[k].value) || (inSelector.elements[inSelectorIndex].value !== '&' && hadParentSelector)) {
selector.elements.splice(k, 1);
k--;
}
inSelectorIndex++;
}
}

context[index][j] = selector;
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify the test failure output and check for similar patterns that might regress
echo "=== Checking the specific test case that fails ==="
rg -n "selector:not\(&:hover\)" packages/test-data/

echo ""
echo "=== Checking expected output for root-level :not(&) patterns ==="
rg -n -B2 -A2 "\.selector:not" packages/test-data/tests-unit/selectors/selectors.css

Repository: less/less.js

Length of output: 358


🏁 Script executed:

#!/bin/bash
# Get the full context of the ruleset.js file around the problematic section
echo "=== Full context of the problematic section (lines 740-800) ==="
sed -n '740,800p' packages/less/src/less/tree/ruleset.js | cat -n

echo ""
echo "=== Check if inSelector is defined and its scope ==="
sed -n '700,750p' packages/less/src/less/tree/ruleset.js | grep -n "inSelector" | head -20

Repository: less/less.js

Length of output: 4508


🏁 Script executed:

#!/bin/bash
# Check the test output to see if the regression is actually happening
echo "=== Looking for test failure output or related files ==="
fd -e "css" -e "txt" -e "json" packages/test-data | xargs grep -l "selector:not(:hover)" 2>/dev/null | head -5

echo ""
echo "=== Check what the actual compiled output is ==="
if [ -f packages/test-data/tests-unit/selectors/selectors.css ]; then
  sed -n '175,180p' packages/test-data/tests-unit/selectors/selectors.css | cat -n
fi

Repository: less/less.js

Length of output: 695


🏁 Script executed:

#!/bin/bash
# Understand the context of hadParentSelector and inSelector variables
echo "=== Search for hadParentSelector initialization ==="
rg -n "hadParentSelector\s*=" packages/less/src/less/tree/ruleset.js | head -10

echo ""
echo "=== Search for inSelector definition and usage ==="
rg -n "inSelector" packages/less/src/less/tree/ruleset.js | head -20

Repository: less/less.js

Length of output: 1952


🏁 Script executed:

#!/bin/bash
# Check if there's a test failure report or log
echo "=== Check for test failure output or related test results ==="
find packages/test-data -name "*.txt" -o -name "*.log" -o -name "*.json" 2>/dev/null | head -20

echo ""
echo "=== Look for any selectors test output or error files ==="
find packages/test-data -path "*selectors*" -type f | head -20

Repository: less/less.js

Length of output: 1755


🏁 Script executed:

#!/bin/bash
# Trace what happens when accessing inSelector.elements with out of bounds index
echo "=== Get more context about inSelector variable ==="
sed -n '695,735p' packages/less/src/less/tree/ruleset.js | cat -n

Repository: less/less.js

Length of output: 2100


🏁 Script executed:

#!/bin/bash
# Check if accessing undefined property causes error in the condition
echo "=== Check how the condition at line 777 would behave with undefined ==="
# Let's look at the full condition and see if undefined.value would be accessed
sed -n '775,785p' packages/less/src/less/tree/ruleset.js | cat -n

echo ""
echo "=== Check inSelector definition in function signature ==="
sed -n '694,710p' packages/less/src/less/tree/ruleset.js | cat -n

Repository: less/less.js

Length of output: 1967


🏁 Script executed:

#!/bin/bash
# Check if there are any test runners or CI configs that show failure
echo "=== Look for test configuration files ==="
find . -maxdepth 3 -name "*.json" -o -name "*.yml" -o -name "*.yaml" 2>/dev/null | grep -i test | head -10

Repository: less/less.js

Length of output: 174


🏁 Script executed:

#!/bin/bash
# Check if there are any error messages or test failures related to this code
echo "=== Look for runtime errors or test failures ==="
grep -r "Cannot read property" packages/test-data/ 2>/dev/null | head -5

echo ""
echo "=== Check git log or commit messages for context ==="
git log --oneline -20 2>/dev/null | head -20

Repository: less/less.js

Length of output: 427


🏁 Script executed:

#!/bin/bash
# Let's verify the test actually passes or fails
echo "=== Check if selectors test has expected vs actual output mismatch ==="
if [ -f packages/test-data/tests-unit/selectors/selectors.less ] && [ -f packages/test-data/tests-unit/selectors/selectors.css ]; then
  echo "Input (lines 185-195):"
  sed -n '185,195p' packages/test-data/tests-unit/selectors/selectors.less | cat -n
  echo ""
  echo "Output (lines 170-185):"
  sed -n '170,185p' packages/test-data/tests-unit/selectors/selectors.css | cat -n
fi

Repository: less/less.js

Length of output: 916


🏁 Script executed:

#!/bin/bash
# Check what selector.elements and inSelector.elements represent in a concrete case
echo "=== Understanding the array lengths issue ==="
sed -n '730,795p' packages/less/src/less/tree/ruleset.js | cat -n

Repository: less/less.js

Length of output: 4700


Critical: Bounds check missing on inSelectorIndex access.

The loop at line 776-781 increments inSelectorIndex for every iteration of the inner k loop over selector.elements, but then accesses inSelector.elements[inSelectorIndex] without bounds checking. When selector.elements is longer than inSelector.elements (which can occur after the splice operations at line 777), accessing inSelector.elements[inSelectorIndex].value will throw a TypeError on undefined.

Additionally, the logic appears problematic: inSelectorIndex should track a position in inSelector.elements, but it's being incremented for every element in selector.elements regardless of whether elements are spliced out. This can cause index misalignment and either skipped checks or out-of-bounds access.

A bounds check is required before line 777 to ensure inSelectorIndex < inSelector.elements.length, or the logic needs to be restructured to properly synchronize the two element arrays.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/src/less/tree/ruleset.js` around lines 745 - 788, The loop over
selector.elements uses inSelectorIndex to read inSelector.elements without
bounds checking and increments it every iteration, causing out-of-bounds or
misaligned comparisons after splice; fix by guarding the access and
synchronizing increments: before referencing
inSelector.elements[inSelectorIndex] ensure inSelectorIndex <
inSelector.elements.length, and change the logic so inSelectorIndex is only
incremented when you consume/advance the corresponding inSelector element (i.e.,
when you do NOT splice selector.elements[k]); apply this change inside the loop
that splices selector.elements (referencing selector.elements, inSelector,
inSelectorIndex, splice, and the surrounding loop that builds
context/newSelectors) so comparisons and increments stay in sync and no read
from undefined occurs.

Comment on lines +799 to 824
} else if (el instanceof Selector) {
const nestedSelector = el;

// merge the current list of non parent selector elements
// on to the current list of selectors to add
mergeElementsOnToSelectors(currentElements, newSelectors);

const nestedPaths = [];
let replaced;
let replacedNewSelectors = [];
let currentReplacedSelectors = [];
replaced = replaceParentSelector(nestedPaths, context, nestedSelector);
hadParentSelector = hadParentSelector || replaced;

for (k = 0; k < nestedPaths.length; k++) {
for (let selectorIndex = 0; selectorIndex < nestedPaths[k].length; ++selectorIndex) {
const replacementSelector = nestedPaths[k][selectorIndex];
addAllReplacementsIntoPath(newSelectors, [replacementSelector], el.elements[0], inSelector, replacedNewSelectors);
for (let current = 0; current < currentReplacedSelectors.length; ++current) {
replacedNewSelectors.push(currentReplacedSelectors[current]);
}
}
}

newSelectors = replacedNewSelectors;
currentElements = [];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if there are test cases that exercise this code path
echo "=== Looking for Selector-as-element patterns in test files ==="
rg -l "instanceof Selector" packages/less/src/less/tree/

Repository: less/less.js

Length of output: 157


🏁 Script executed:

# Read the relevant section of ruleset.js with surrounding context
cat -n packages/less/src/less/tree/ruleset.js | sed -n '780,850p'

Repository: less/less.js

Length of output: 4531


🏁 Script executed:

# Find the addAllReplacementsIntoPath function definition
rg -A 10 "function addAllReplacementsIntoPath|const addAllReplacementsIntoPath" packages/less/src/less/tree/ruleset.js

Repository: less/less.js

Length of output: 562


🏁 Script executed:

# Compare the two branches - ParentSelector branch and Selector branch
cat -n packages/less/src/less/tree/ruleset.js | sed -n '750,830p'

Repository: less/less.js

Length of output: 5506


🏁 Script executed:

# Search for test files related to Selector handling
find packages/less/test -type f -name "*.js" | head -20

Repository: less/less.js

Length of output: 1088


🏁 Script executed:

# Search for test files that test nested selector logic
rg -l "nested.*selector|Selector.*element" packages/less/test --type js | head -10

Repository: less/less.js

Length of output: 38


🏁 Script executed:

# Check git history of this specific section
git log --oneline -20 packages/less/src/less/tree/ruleset.js

Repository: less/less.js

Length of output: 114


🏁 Script executed:

# Check the commit that introduced this code
git show 81dd8de8 --stat

Repository: less/less.js

Length of output: 50368


🏁 Script executed:

# Show the actual diff for the ruleset.js file from the commit
git show 81dd8de8 -- packages/less/src/less/tree/ruleset.js | head -200

Repository: less/less.js

Length of output: 7365


🏁 Script executed:

# Get the diff focused on lines around 799-824
git show 81dd8de8 -- packages/less/src/less/tree/ruleset.js | grep -A 150 "else if (el instanceof Selector)" | head -100

Repository: less/less.js

Length of output: 5127


Remove or complete the unused currentReplacedSelectors logic.

The variable currentReplacedSelectors is initialized at line 809 but never populated. The loop at lines 817–819 that iterates over it will never execute, making this dead code. Either remove this loop and the variable, or add a TODO comment explaining the intended functionality for future completion.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/src/less/tree/ruleset.js` around lines 799 - 824, The variable
currentReplacedSelectors in ruleset.js is never populated and its loop is dead
code; remove the declaration of currentReplacedSelectors and the inner loop that
pushes its items into replacedNewSelectors, then ensure logic around
newSelectors/currentElements remains consistent (the surrounding code uses
replaceParentSelector, nestedSelector, addAllReplacementsIntoPath and
currentElements to build replacedNewSelectors—so either remove the unused
currentReplacedSelectors references or if intended, add a clear TODO and
implement population where appropriate).

The expected output for `.selector:not(&:hover)` was `:not(:hover)` but
& at global scope resolves to the selector itself, so the correct output
is `:not(.selector:hover)`. This was a pre-existing error in the test
expectation that was masked because the test was already failing before
the PR changes.
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Mar 9, 2026
@matthew-dean

Copy link
Copy Markdown
Member Author

Closing - replacing with a cleaner implementation that works within the existing abstractions instead of adding 80+ lines of manual element cloning and array splicing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Nested pseudo-selector with parent symbol

2 participants