Merge pull request #1289 from maximilliangrand/fix/array-methods-noop-structural-sharing
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Mark Erikson · committed by GitHub · parents d2c158f, 9491138 · Browse files · 4 files·+201 added−39 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- fix: preserve structural sharing for no-op array-methods calls
Diff stats
4 files+201 added−39 removed
- tests:+103 added−7 removed
- other:+98 added−32 removed
Provenance
- Commit
907395a- Tree
773c8b4- Author
Mark Erikson <mark@isquaredsoftware.com>- Committer
GitHub <noreply@github.com>- Parent 1
d2c158f- Parent 2
9491138
4 files changed+201 added−39 removed
modified:__tests__/base.js+80 added-5 removed
58 unmodified lines59 useStrictShallowCopy,60 useListener,61 useArrayMethods = false62 ) {63- const listener = useListener ? function () {} : undefined63+ const listener = useListener ? function() {} : undefined64 65 const {produce, produceWithPatches} = createPatchedImmer({66 autoFreeze,67 useStrictShallowCopy4 unmodified lines72 function createPatchedImmer(options) {73 const immer = new Immer(options)74 75 const {produce} = immer76- immer.produce = function (...args) {76+ immer.produce = function(...args) {77 return typeof args[1] === "function" && args.length < 378 ? produce(...args, listener)79 : produce(...args)80 }210 unmodified lines291 expect(nextState.anArray.length).toBe(baseLength + 1)292 })293 294 describe("mutating array methods", () => {295+ describe("no-op calls preserve structural sharing", () => {296+ it("push() with no arguments returns the base", () => {297+ const base = {list: [1, 2, 3], keep: {x: 1}}298+ const [next, patches] = produceWithPatches(base, d => {299+ d.list.push(...[])300+ })301+ expect(next).toBe(base)302+ expect(next.keep).toBe(base.keep)303+ expect(patches).toHaveLength(0)304+ })305+306+ it("unshift() with no arguments returns the base", () => {307+ const base = {list: [1, 2, 3]}308+ const next = produce(base, d => {309+ d.list.unshift()310+ })311+ expect(next).toBe(base)312+ })313+314+ it("splice() that removes and inserts nothing returns the base", () => {315+ const base = {list: [1, 2, 3]}316+ const [next, patches] = produceWithPatches(base, d => {317+ d.list.splice(1, 0)318+ })319+ expect(next).toBe(base)320+ expect(patches).toHaveLength(0)321+ })322+323+ it("pop()/shift() on an empty array return the base", () => {324+ const base = {popped: [], shifted: []}325+ const next = produce(base, d => {326+ d.popped.pop()327+ d.shifted.shift()328+ })329+ expect(next).toBe(base)330+ })331+332+ it("no-op push() on an array inside a Set preserves the array's identity", () => {333+ const arr = [1, 2, 3]334+ const base = new Set([arr, {x: 1}])335+ const next = produce(base, d => {336+ for (const v of d) {337+ if (Array.isArray(v)) v.push(...[])338+ else v.x = 2339+ }340+ })341+ expect(next).not.toBe(base)342+ expect([...next].find(Array.isArray)).toBe(arr)343+ })344+345+ it("sort()/reverse() on arrays with fewer than two elements return the base", () => {346+ const base = {empty: [], single: [1]}347+ const next = produce(base, d => {348+ d.empty.sort()349+ d.empty.reverse()350+ d.single.sort((a, b) => a - b)351+ d.single.reverse()352+ })353+ expect(next).toBe(base)354+ })355+356+ it("no-op splice() on an array inside a Set preserves the array's identity", () => {357+ const arr = [1, 2, 3]358+ const base = new Set([arr, {x: 1}])359+ const next = produce(base, d => {360+ for (const v of d) {361+ if (Array.isArray(v)) v.splice(1, 0)362+ else v.x = 2363+ }364+ })365+ expect(next).not.toBe(base)366+ expect([...next].find(Array.isArray)).toBe(arr)367+ })368+ })369+370 // Reported here: https://github.com/mweststrate/immer/issues/116371 it("can pop then push", () => {372 const nextState = produce([1, 2, 3], s => {373 s.pop()2929 unmodified lines3303 })3304 3305 it("'this' should not be bound anymore - 1", () => {3306 const base = {x: 3}3232- const next1 = produce(base, function () {3307+ const next1 = produce(base, function() {3308 expect(this).toBe(undefined)3309 })3310 })3311 3312 it("'this' should not be bound anymore - 2", () => {3238- const incrementor = produce(function () {3313+ const incrementor = produce(function() {3314 expect(this).toBe(undefined)3315 })3316 incrementor()3317 })3318 3319 it("should be possible to use dynamic bound this", () => {3320 const world = {3321 counter: {count: 1},3247- inc: produce(function (draft) {3322+ inc: produce(function(draft) {3323 expect(this).toBe(world)3324 draft.counter.count = this.counter.count + 13325 })3326 }978 unmodified linesmodified:__tests__/map-set.js+23 added-2 removed
21 unmodified lines22 runBaseTest("proxy (autofreeze)", true, true)23 runBaseTest("proxy (autofreeze)(patch listener)", true, true, true)24 25 function runBaseTest(name, autoFreeze, useListener) {26- const listener = useListener ? function () {} : undefined26+ const listener = useListener ? function() {} : undefined27 const {produce, produceWithPatches} = createPatchedImmer({28 autoFreeze29 })30 2 unmodified lines33 function createPatchedImmer(options) {34 const immer = new Immer(options)35 36 const {produce} = immer37- immer.produce = function (...args) {37+ immer.produce = function(...args) {38 return typeof args[1] === "function" && args.length < 339 ? produce(...args, listener)40 : produce(...args)41 }352 unmodified lines394 })395 396 expect(Array.from(newSet)).toEqual([objs[0], objs[1]])397 })398+399+ test("reading (but not modifying) a nested object inside a Set does not leak the copy", () => {400+ const untouched = {nested: {a: 1}}401+ const base = new Set([untouched, {x: 1}])402+ const next = produce(base, draft => {403+ for (const v of draft) {404+ if (v.nested) {405+ // Read only - creates a child draft (and a stray copy_406+ // on the parent) but modifies nothing407+ expect(v.nested.a).toBe(1)408+ } else {409+ v.x = 2410+ }411+ }412+ })413+ expect(next).not.toBe(base)414+ const finalUntouched = Array.from(next).find(v => v.nested)415+ expect(finalUntouched).toBe(untouched)416+ expect(finalUntouched.nested.a).toBe(1)417+ expect(isDraft(finalUntouched.nested)).toBe(false)418+ })419 })420 }421 422 // Bug reproduction: DraftSet leakage when placed in new object and set into Map113 unmodified linesmodified:src/plugins/arrayMethods.ts+87 added-25 removed
172 unmodified lines173 markLength = true174 ): T {175 prepareCopy(state)176 const result = operation()177+ markArrayChanged(state, markLength)178+ return result179+ }180+181+ /**182+ * Marks the array (and its ancestors) as modified after a mutating operation.183+ *184+ * Kept separate from `executeArrayMethod` so that operations which turn out to185+ * be no-ops (e.g. `push()` with no arguments, `splice(i, 0)`, `pop()`/`shift()`186+ * on an empty array) can prepare a copy but skip marking, preserving Immer's187+ * structural-sharing guarantee that a change-free producer returns the base.188+ */189+ function markArrayChanged(state: ProxyArrayState, markLength = true) {190 markChanged(state)191 if (markLength) state.assigned_!.set("length", true)179- return result192 }193 194 function markAllIndicesReassigned(state: ProxyArrayState) {195 state.allIndicesReassigned_ = true49 unmodified lines245 state: ProxyArrayState,246 method: string,247 args: any[]248 ) {237- return executeArrayMethod(state, () => {238- // For push/unshift, capture the length before the operation239- // so we can compute insertion indices for handleCrossReference240- const lengthBefore = state.copy_!.length249+ // Detect no-op calls before creating a copy so structural sharing is250+ // preserved: push/unshift with no arguments add nothing, and pop/shift251+ // on an empty array remove nothing. The check must happen before252+ // prepareCopy - a stray copy_ on an unmodified state would be picked253+ // up by finalization of a parent Set and break identity there.254+ const isInsert = method === "push" || method === "unshift"255+ if (isInsert ? args.length === 0 : latest(state).length === 0) {256+ // Match the native return values: push/unshift return the257+ // (unchanged) length, pop/shift on an empty array return undefined258+ return isInsert ? latest(state).length : undefined259+ }260 242- const result = (state.copy_! as any)[method](...args)261+ prepareCopy(state)262 244- // Handle index reassignment for shifting methods245- if (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {246- markAllIndicesReassigned(state)247- }263+ // For push/unshift, capture the length before the operation264+ // so we can compute insertion indices for handleCrossReference265+ const lengthBefore = state.copy_!.length266 249- // Handle cross-references for newly inserted values.250- // push appends at the end, unshift inserts at the beginning.251- if (method === "push" && args.length > 0) {252- handleInsertedValues(state, lengthBefore, args)253- } else if (method === "unshift" && args.length > 0) {254- handleInsertedValues(state, 0, args)255- }267+ const result = (state.copy_! as any)[method](...args)268 257- // Return appropriate value based on method258- return RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)259- ? result260- : state.draft_261- })269+ markArrayChanged(state)270+271+ // Handle index reassignment for shifting methods272+ if (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {273+ markAllIndicesReassigned(state)274+ }275+276+ // Handle cross-references for newly inserted values.277+ // push appends at the end, unshift inserts at the beginning.278+ if (method === "push") {279+ handleInsertedValues(state, lengthBefore, args)280+ } else if (method === "unshift") {281+ handleInsertedValues(state, 0, args)282+ }283+284+ // Return appropriate value based on method285+ return RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)286+ ? result287+ : state.draft_288 }289 290 /**291 * Handles reordering operations (reverse, sort) that change element order.8 unmodified lines300 state: ProxyArrayState,301 method: string,302 args: any[]303 ) {304+ // Reordering an array with fewer than two elements cannot change it,305+ // so preserve structural sharing and skip copying (see306+ // handleSimpleOperation for why this must run before prepareCopy).307+ if (latest(state).length <= 1) return state.draft_308+309 return executeArrayMethod(310 state,311 () => {312 ;(state.copy_! as any)[method](...args)41 unmodified lines354 return handleReorderingOperation(state, method, args)355 }356 357 if (method === "splice") {327- const res = executeArrayMethod(state, () =>328- state.copy_!.splice(...(args as [number, number, ...any[]]))358+ const insertCount = args.length > 2 ? args.length - 2 : 0359+360+ // Detect no-op calls before creating a copy so structural361+ // sharing is preserved (see handleSimpleOperation). A splice362+ // removes nothing when called with no arguments, when the363+ // normalized start is at/past the end, or when the delete364+ // count coerces to less than 1. splice(start) with a single365+ // argument removes everything from start onwards, so it must366+ // not match. Exotic arguments that slip through are caught367+ // by the post-copy check below.368+ if (insertCount === 0) {369+ const length = latest(state).length370+ if (371+ args.length === 0 ||372+ normalizeSliceIndex(args[0] ?? 0, length) === length ||373+ (args.length > 1 && !(args[1] >= 1))374+ ) {375+ return []376+ }377+ }378+379+ prepareCopy(state)380+ const res = state.copy_!.splice(381+ ...(args as [number, number, ...any[]])382 )383+384+ // Backstop for exotic arguments the pre-check above missed:385+ // if nothing was removed and nothing inserted, the array is386+ // unchanged and must not be marked as modified.387+ if (res.length === 0 && insertCount === 0) {388+ return res389+ }390+391+ markArrayChanged(state)392 markAllIndicesReassigned(state)393 // Handle cross-references for inserted values (args from index 2+)332- if (args.length > 2) {394+ if (insertCount > 0) {395 const startIndex = normalizeSliceIndex(396 args[0] ?? 0,397 state.copy_!.length398 )110 unmodified linesmodified:src/utils/common.ts+11 added-7 removed
103 unmodified lines104 const state: undefined | ImmerState = thing[DRAFT_STATE]105 return state106 ? state.type_107 : isArray(thing)108- ? ArchType.Array109- : isMap(thing)110- ? ArchType.Map111- : isSet(thing)112- ? ArchType.Set113- : ArchType.Object108+ ? ArchType.Array109+ : isMap(thing)110+ ? ArchType.Map111+ : isSet(thing)112+ ? ArchType.Set113+ : ArchType.Object114 }115 116 /*#__PURE__*/117 export let has = (67 unmodified lines185 export let latest = (state: ImmerState): any => state.copy_ || state.base_186 187 export let getValue = <T extends object>(value: T): T => {188 const proxyDraft = getProxyDraft(value)189- return proxyDraft ? (proxyDraft.copy_ ?? proxyDraft.base_) : value189+ // Use the copy only if the draft was actually modified. An unmodified190+ // draft can still have a copy_ (e.g. the get trap caches child drafts191+ // there), and using it would both break structural sharing and leak192+ // soon-to-be-revoked child drafts into the result.193+ return proxyDraft ? getFinalValue(proxyDraft) : value194 }195 196 export let getFinalValue = (state: ImmerState): any =>197 state.modified_ ? state.copy_ : state.base_93 unmodified lines