Skip to content

fix: keep the content around a moved range in update - #385

Open
theRizwan wants to merge 1 commit into
Rich-Harris:masterfrom
theRizwan:fix-update-after-move
Open

theRizwan wants to merge 1 commit into
Rich-Harris:masterfrom
theRizwan:fix-update-after-move

Conversation

@theRizwan

Copy link
Copy Markdown
Contributor

Since 1.4.5, update() and overwrite() on a range that was moved delete unrelated text:

new MagicString('ab').move(1, 2, 0).update(1, 2, 'P').toString()
// 'P', expected 'Pa' (1.4.4 gives 'Pa')

new MagicString('abc').move(1, 2, 0).update(1, 2, 'P').toString()
// 'Pc', expected 'Pac'

new MagicString('ab').move(1, 2, 0).replace('b', 'P').toString()
// 'P', expected 'Pa': replace() overwrites the match, so it is affected too

No error is thrown, so the text is lost silently.

Cause

#371 rewrote the loop in update() that empties the rest of the range after first takes the replacement. It used to walk from first to last, a run the check above it had already proved contiguous. It now walks first.next in output order while chunk.start < end. After a move, the chunk that follows first in the output can be one from before start in the original. Its start is below end, so it is taken for part of the range and emptied. In the first example, 'a' ([0, 1)) follows the moved 'b' ([1, 2)), so it is wiped.

Fix

Walk the range itself, with the same condition as the check right above it (chunk.end < end, following next). That check has already thrown unless every chunk in the range is followed by the one starting at its end, so the walk stays inside the range.

Evidence

One test is added, covering a range moved to the front, a single character and two characters, with update and with replace. It fails on master and passes here. The suite is at 495 and passes, ESLint is clean, and typecheck reports no errors.

Since Rich-Harris#371, update() emptied every chunk after `first` in output order while its start was before `end`. Once `first` has been moved, the chunk after it in the output can come from before `start`, so updating a moved range dropped unrelated content: `new MagicString('ab').move(1, 2, 0).update(1, 2, 'P')` gave 'P' instead of 'Pa'. Walk the range itself, as the check before it does.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant