From e24459988c3206cb0ec763d3e2ea48db8178686a Mon Sep 17 00:00:00 2001 From: tuchg Date: Thu, 27 Oct 2022 21:23:31 +0800 Subject: [PATCH 01/13] fix(reactivity-transform): ensure macro comply with the original semantic --- .../compileScriptPropsTransform.spec.ts.snap | 6 ++-- .../compileScriptRefTransform.spec.ts.snap | 10 +++--- .../compileScriptPropsTransform.spec.ts | 8 ++--- .../compileScriptRefTransform.spec.ts | 10 +++--- .../reactivityTransform.spec.ts.snap | 34 ++++++++++--------- .../__tests__/reactivityTransform.spec.ts | 23 +++++++------ .../src/reactivityTransform.ts | 20 +++++++++-- 7 files changed, 66 insertions(+), 45 deletions(-) diff --git a/packages/compiler-sfc/__tests__/__snapshots__/compileScriptPropsTransform.spec.ts.snap b/packages/compiler-sfc/__tests__/__snapshots__/compileScriptPropsTransform.spec.ts.snap index cfde6700dba..38762b2116f 100644 --- a/packages/compiler-sfc/__tests__/__snapshots__/compileScriptPropsTransform.spec.ts.snap +++ b/packages/compiler-sfc/__tests__/__snapshots__/compileScriptPropsTransform.spec.ts.snap @@ -10,9 +10,9 @@ const __props_bar = _toRef(__props, 'bar') const __props_foo = _toRef(__props, 'foo') - console.log((__props_foo)) - console.log((__props_bar)) - ({ foo: __props_foo, baz: __props_bar }) + console.log(__props_foo) + console.log(__props_bar) + console.log({ foo: __props_foo, baz: __props_bar }) return () => {} } diff --git a/packages/compiler-sfc/__tests__/__snapshots__/compileScriptRefTransform.spec.ts.snap b/packages/compiler-sfc/__tests__/__snapshots__/compileScriptRefTransform.spec.ts.snap index b7c81a08c86..442e170094b 100644 --- a/packages/compiler-sfc/__tests__/__snapshots__/compileScriptRefTransform.spec.ts.snap +++ b/packages/compiler-sfc/__tests__/__snapshots__/compileScriptRefTransform.spec.ts.snap @@ -7,11 +7,11 @@ export default { setup(__props, { expose }) { expose(); - let foo = (ref()) - let a = (ref(1)) - let b = (shallowRef({ + let foo = ref() + let a = ref(1) + let b = shallowRef({ count: 0 - })) + }) let c = () => {} let d @@ -65,7 +65,7 @@ exports[`sfc ref transform usage in normal `) expect(content).toMatch(`const __props_foo = _toRef(__props, 'foo')`) expect(content).toMatch(`const __props_bar = _toRef(__props, 'bar')`) - expect(content).toMatch(`console.log((__props_foo))`) - expect(content).toMatch(`console.log((__props_bar))`) - expect(content).toMatch(`({ foo: __props_foo, baz: __props_bar })`) + expect(content).toMatch(`console.log(__props_foo)`) + expect(content).toMatch(`console.log(__props_bar)`) + expect(content).toMatch(`{ foo: __props_foo, baz: __props_bar }`) assertCode(content) }) diff --git a/packages/compiler-sfc/__tests__/compileScriptRefTransform.spec.ts b/packages/compiler-sfc/__tests__/compileScriptRefTransform.spec.ts index 88d62f2b478..468c3f07b7e 100644 --- a/packages/compiler-sfc/__tests__/compileScriptRefTransform.spec.ts +++ b/packages/compiler-sfc/__tests__/compileScriptRefTransform.spec.ts @@ -22,12 +22,12 @@ describe('sfc ref transform', () => { expect(content).not.toMatch(`$(ref())`) expect(content).not.toMatch(`$(ref(1))`) expect(content).not.toMatch(`$(shallowRef({`) - expect(content).toMatch(`let foo = (ref())`) - expect(content).toMatch(`let a = (ref(1))`) + expect(content).toMatch(`let foo = ref()`) + expect(content).toMatch(`let a = ref(1)`) expect(content).toMatch(` - let b = (shallowRef({ + let b = shallowRef({ count: 0 - })) + }) `) // normal declarations left untouched expect(content).toMatch(`let c = () => {}`) @@ -95,7 +95,7 @@ describe('sfc ref transform', () => { expect(content).toMatch(`import { ref as _ref } from 'vue'`) expect(content).toMatch(`let count = _ref(0)`) expect(content).toMatch(`count.value++`) - expect(content).toMatch(`return ({ count })`) + expect(content).toMatch(`return { count }`) assertCode(content) }) diff --git a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap index 0251a2f5d17..41b3e7ffa13 100644 --- a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap +++ b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap @@ -3,14 +3,14 @@ exports[`$ unwrapping 1`] = ` " import { ref, shallowRef } from 'vue' - let foo = (ref()) - export let a = (ref(1)) - let b = (shallowRef({ + let foo = ref() + export let a = ref(1) + let b = shallowRef({ count: 0 - })) + }) let c = () => {} let d - label: var e = (ref()) + label: var e = ref() " `; @@ -18,9 +18,11 @@ exports[`$$ 1`] = ` "import { ref as _ref } from 'vue' let a = _ref(1) - const b = (a) - const c = ({ a }) - callExternal((a)) + let count = 0 + const b = a + const c = { a } + (count++,count) + callExternal(a) " `; @@ -59,7 +61,7 @@ exports[`accessing ref binding 1`] = ` exports[`array destructure 1`] = ` "import { ref as _ref, toRef as _toRef } from 'vue' - let n = _ref(1), __$temp_1 = (useFoo()), + let n = _ref(1), __$temp_1 = useFoo(), a = _toRef(__$temp_1, 0), b = _toRef(__$temp_1, 1, 1) console.log(n.value, a.value, b.value) @@ -88,7 +90,7 @@ exports[`macro import alias and removal 1`] = ` let a = _ref(1) - const __$temp_1 = (useMouse()), + const __$temp_1 = useMouse(), x = _toRef(__$temp_1, 'x'), y = _toRef(__$temp_1, 'y') " @@ -129,9 +131,9 @@ exports[`mutating ref binding 1`] = ` exports[`nested destructure 1`] = ` "import { toRef as _toRef } from 'vue' - let __$temp_1 = (useFoo()), + let __$temp_1 = useFoo(), b = _toRef(__$temp_1[0].a, 'b') - let __$temp_2 = (useBar()), + let __$temp_2 = useBar(), d = _toRef(__$temp_2.c, 0), e = _toRef(__$temp_2.c, 1) console.log(b.value, d.value, e.value) @@ -170,7 +172,7 @@ exports[`nested scopes 1`] = ` a.value++ // if block a } - return ({ a, b, c, d }) + return { a, b, c, d } } " `; @@ -178,13 +180,13 @@ exports[`nested scopes 1`] = ` exports[`object destructure 1`] = ` "import { ref as _ref, toRef as _toRef } from 'vue' - let n = _ref(1), __$temp_1 = (useFoo()), + let n = _ref(1), __$temp_1 = useFoo(), a = _toRef(__$temp_1, 'a'), c = _toRef(__$temp_1, 'b'), d = _toRef(__$temp_1, 'd', 1), f = _toRef(__$temp_1, 'e', 2), h = _toRef(__$temp_1, g) - let __$temp_2 = (useSomething(() => 1)), + let __$temp_2 = useSomething(() => 1), foo = _toRef(__$temp_2, 'foo'); console.log(n.value, a.value, c.value, d.value, f.value, h.value, foo.value) " @@ -193,7 +195,7 @@ exports[`object destructure 1`] = ` exports[`object destructure w/ mid-path default values 1`] = ` "import { toRef as _toRef } from 'vue' - const __$temp_1 = (useFoo()), + const __$temp_1 = useFoo(), b = _toRef((__$temp_1.a || { b: 123 }), 'b') console.log(b.value) " diff --git a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts index 7471615cae2..b3f44c2c1f4 100644 --- a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts +++ b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts @@ -30,17 +30,17 @@ test('$ unwrapping', () => { expect(code).not.toMatch(`$(ref())`) expect(code).not.toMatch(`$(ref(1))`) expect(code).not.toMatch(`$(shallowRef({`) - expect(code).toMatch(`let foo = (ref())`) - expect(code).toMatch(`export let a = (ref(1))`) + expect(code).toMatch(`let foo = ref()`) + expect(code).toMatch(`export let a = ref(1)`) expect(code).toMatch(` - let b = (shallowRef({ + let b = shallowRef({ count: 0 - })) + }) `) // normal declarations left untouched expect(code).toMatch(`let c = () => {}`) expect(code).toMatch(`let d`) - expect(code).toMatch(`label: var e = (ref())`) + expect(code).toMatch(`label: var e = ref()`) expect(rootRefs).toStrictEqual(['foo', 'a', 'b', 'e']) assertCode(code) }) @@ -295,13 +295,16 @@ test('nested destructure', () => { test('$$', () => { const { code } = transform(` let a = $ref(1) + let count = 0 const b = $$(a) const c = $$({ a }) + $$(count++,count) callExternal($$(a)) `) - expect(code).toMatch(`const b = (a)`) - expect(code).toMatch(`const c = ({ a })`) - expect(code).toMatch(`callExternal((a))`) + expect(code).toMatch(`const b = a`) + expect(code).toMatch(`const c = { a }`) + expect(code).toMatch(`callExternal(a)`) + expect(code).toMatch(`(count++,count)`) assertCode(code) }) @@ -358,7 +361,7 @@ test('nested scopes', () => { // inner bar shadowed by function declaration expect(code).toMatch(`bar() // inner bar`) - expect(code).toMatch(`return ({ a, b, c, d })`) + expect(code).toMatch(`return { a, b, c, d }`) assertCode(code) }) @@ -412,7 +415,7 @@ test('macro import alias and removal', () => { // should remove imports expect(code).not.toMatch(`from 'vue/macros'`) expect(code).toMatch(`let a = _ref(1)`) - expect(code).toMatch(`const __$temp_1 = (useMouse())`) + expect(code).toMatch(`const __$temp_1 = useMouse()`) assertCode(code) }) diff --git a/packages/reactivity-transform/src/reactivityTransform.ts b/packages/reactivity-transform/src/reactivityTransform.ts index 34d537d221b..568eccba362 100644 --- a/packages/reactivity-transform/src/reactivityTransform.ts +++ b/packages/reactivity-transform/src/reactivityTransform.ts @@ -284,7 +284,7 @@ export function transformAST( if (method === convertSymbol) { // $ // remove macro - s.remove(call.callee.start! + offset, call.callee.end! + offset) + unwrapMacro(call) if (id.type === 'Identifier') { // single variable registerRefBinding(id) @@ -550,6 +550,22 @@ export function transformAST( } } + /** + * unwrap the code form the macro($、$$), fix #6312 and keep the ideally behavior with the RFC#369 + */ + function unwrapMacro(node: CallExpression) { + const argsLength = node.arguments.length + if (argsLength > 1) { + // some edge cases + s.remove(node.callee.start! + offset, node.callee.end! + offset) + } else if (argsLength) { + // remove macro $( and $$( + s.remove(node.callee.start! + offset, node.arguments[0].start! + offset) + // remove the end of macro + s.remove(node.arguments[argsLength - 1].end! + offset, node.end! + offset) + } + } + // check root scope first walkScope(ast, true) ;(walk as any)(ast, { @@ -623,7 +639,7 @@ export function transformAST( } if (callee === escapeSymbol) { - s.remove(node.callee.start! + offset, node.callee.end! + offset) + unwrapMacro(node) escapeScope = node } From 738f695348207268dd420fe090b8f105addeedf1 Mon Sep 17 00:00:00 2001 From: tuchg Date: Thu, 27 Oct 2022 22:22:26 +0800 Subject: [PATCH 02/13] fix(reactivity-transform): some edge cases of multi-arguments scenario --- .../reactivityTransform.spec.ts.snap | 15 +++++++++++-- .../__tests__/reactivityTransform.spec.ts | 21 ++++++++++++++++--- .../src/reactivityTransform.ts | 11 +++++++++- 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap index 41b3e7ffa13..01d2af8b94e 100644 --- a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap +++ b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap @@ -18,14 +18,25 @@ exports[`$$ 1`] = ` "import { ref as _ref } from 'vue' let a = _ref(1) - let count = 0 const b = a const c = { a } - (count++,count) callExternal(a) " `; +exports[`$$ with some edge cases 1`] = ` +"import { ref as _ref } from 'vue' + + let a = _ref(1) + const af=()=>{} + console.log(a) + ;(count++,count) + let r1 = (count++,count) + let r2 = _ref(af((count++,count))) + let r3 = { a:(count++,count) } + " +`; + exports[`$computed declaration 1`] = ` "import { computed as _computed } from 'vue' diff --git a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts index b3f44c2c1f4..ebe084220d6 100644 --- a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts +++ b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts @@ -295,16 +295,31 @@ test('nested destructure', () => { test('$$', () => { const { code } = transform(` let a = $ref(1) - let count = 0 const b = $$(a) const c = $$({ a }) - $$(count++,count) callExternal($$(a)) `) expect(code).toMatch(`const b = a`) expect(code).toMatch(`const c = { a }`) expect(code).toMatch(`callExternal(a)`) - expect(code).toMatch(`(count++,count)`) + assertCode(code) +}) + +test('$$ with some edge cases',()=>{ + const { code } = transform(` + let a = $ref(1) + const af=()=>{} + console.log($$(a)) + $$(count++,count) + let r1 = $$(count++,count) + let r2 = $ref(af($$(count++,count))) + let r3 = { a:$$(count++,count) } + `) + console.log(code) + expect(code).toMatch(`;(count++,count)`) + expect(code).toMatch(`let r1 = (count++,count)`) + expect(code).toMatch(`let r2 = _ref(af((count++,count)))`) + expect(code).toMatch(`let r3 = { a:(count++,count) }`) assertCode(code) }) diff --git a/packages/reactivity-transform/src/reactivityTransform.ts b/packages/reactivity-transform/src/reactivityTransform.ts index 568eccba362..b5f8ca25153 100644 --- a/packages/reactivity-transform/src/reactivityTransform.ts +++ b/packages/reactivity-transform/src/reactivityTransform.ts @@ -556,8 +556,17 @@ export function transformAST( function unwrapMacro(node: CallExpression) { const argsLength = node.arguments.length if (argsLength > 1) { - // some edge cases + // handle some edge cases s.remove(node.callee.start! + offset, node.callee.end! + offset) + // resolve nested + let i = parentStack.length - 1 + while (i >= 0) { + if (parentStack[i].type === 'VariableDeclarator') { + return + } + i-- + } + s.appendLeft(node.callee.start! + offset, ';') } else if (argsLength) { // remove macro $( and $$( s.remove(node.callee.start! + offset, node.arguments[0].start! + offset) From c99ccd601d369c8cd44bdf1f179c620b43eed790 Mon Sep 17 00:00:00 2001 From: tuchg Date: Fri, 28 Oct 2022 10:21:43 +0800 Subject: [PATCH 03/13] fix(reactivity-transform): more edge cases of $$ scenario --- .../reactivityTransform.spec.ts.snap | 10 +++++-- .../__tests__/reactivityTransform.spec.ts | 15 +++++++--- .../src/reactivityTransform.ts | 29 ++++++++++++------- 3 files changed, 37 insertions(+), 17 deletions(-) diff --git a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap index 01d2af8b94e..7f7313d5da3 100644 --- a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap +++ b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap @@ -27,10 +27,14 @@ exports[`$$ 1`] = ` exports[`$$ with some edge cases 1`] = ` "import { ref as _ref } from 'vue' - let a = _ref(1) - const af=()=>{} - console.log(a) + let a = _ref(1), e = _ref() + () ;(count++,count) + ((count++,count)) + count = (count++,count) + count = ()=>(count++,count) + const af=()=>((count++,count)) + let c = _ref(a.value, (count++,count)) let r1 = (count++,count) let r2 = _ref(af((count++,count))) let r3 = { a:(count++,count) } diff --git a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts index ebe084220d6..7ac93596507 100644 --- a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts +++ b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts @@ -307,16 +307,23 @@ test('$$', () => { test('$$ with some edge cases',()=>{ const { code } = transform(` - let a = $ref(1) - const af=()=>{} - console.log($$(a)) + let a = $ref(1), e = $ref() + $$() $$(count++,count) + ($$(count++,count)) + count = $$(count++,count) + count = ()=>$$(count++,count) + const af=()=>($$(count++,count)) + let c = $ref(a, $$(count++,count)) let r1 = $$(count++,count) let r2 = $ref(af($$(count++,count))) let r3 = { a:$$(count++,count) } `) - console.log(code) expect(code).toMatch(`;(count++,count)`) + expect(code).toMatch(`((count++,count))`) + expect(code).toMatch(`count = (count++,count)`) + expect(code).toMatch(`()=>(count++,count)`) + expect(code).toMatch(`()=>((count++,count))`) expect(code).toMatch(`let r1 = (count++,count)`) expect(code).toMatch(`let r2 = _ref(af((count++,count)))`) expect(code).toMatch(`let r3 = { a:(count++,count) }`) diff --git a/packages/reactivity-transform/src/reactivityTransform.ts b/packages/reactivity-transform/src/reactivityTransform.ts index b5f8ca25153..04c6dbb4469 100644 --- a/packages/reactivity-transform/src/reactivityTransform.ts +++ b/packages/reactivity-transform/src/reactivityTransform.ts @@ -555,23 +555,32 @@ export function transformAST( */ function unwrapMacro(node: CallExpression) { const argsLength = node.arguments.length - if (argsLength > 1) { - // handle some edge cases - s.remove(node.callee.start! + offset, node.callee.end! + offset) + s.remove(node.callee.start! + offset, node.callee.end! + offset) + if (!argsLength) { + return + } else if (argsLength === 1) { + // remove brackets of macro + s.remove(node.callee.end! + offset, node.arguments[0].start! + offset) + s.remove(node.arguments[argsLength - 1].end! + offset, node.end! + offset) + } else { + // handle some edge cases for macro $$ // resolve nested let i = parentStack.length - 1 while (i >= 0) { - if (parentStack[i].type === 'VariableDeclarator') { + const curParent = parentStack[i--] + // see @__tests__:$$ with some edge cases + if ( + curParent.type === 'VariableDeclarator' || + curParent.type === 'AssignmentExpression' || + (curParent.type === 'ExpressionStatement' && + (curParent.expression.extra || + (curParent.expression.type === 'CallExpression' && + curParent.expression.arguments.includes(node)))) + ) { return } - i-- } s.appendLeft(node.callee.start! + offset, ';') - } else if (argsLength) { - // remove macro $( and $$( - s.remove(node.callee.start! + offset, node.arguments[0].start! + offset) - // remove the end of macro - s.remove(node.arguments[argsLength - 1].end! + offset, node.end! + offset) } } From e674d9a0d39a1c7912dee81238cb5e536fcc05ea Mon Sep 17 00:00:00 2001 From: tuchg Date: Fri, 28 Oct 2022 21:11:12 +0800 Subject: [PATCH 04/13] fix(reactivity-transform): more edge cases of $$ scenario --- .../reactivityTransform.spec.ts.snap | 26 ++++--- .../__tests__/reactivityTransform.spec.ts | 43 ++++++------ .../src/reactivityTransform.ts | 68 ++++++++++++------- 3 files changed, 82 insertions(+), 55 deletions(-) diff --git a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap index 7f7313d5da3..95e2466580b 100644 --- a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap +++ b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap @@ -27,17 +27,21 @@ exports[`$$ 1`] = ` exports[`$$ with some edge cases 1`] = ` "import { ref as _ref } from 'vue' - let a = _ref(1), e = _ref() - () - ;(count++,count) - ((count++,count)) - count = (count++,count) - count = ()=>(count++,count) - const af=()=>((count++,count)) - let c = _ref(a.value, (count++,count)) - let r1 = (count++,count) - let r2 = _ref(af((count++,count))) - let r3 = { a:(count++,count) } + a + console.log(a) + ;(a,b) + ;(a,b) + count = (a++,b) + count = ()=>(a++,b) + let r1 = _ref(a, (a++,b)) + let r2 = { a:(a++,b),b:a } + switch(c){ + case d: + a + ;(h,f) + break + } + ((count++,count,(count,a))) " `; diff --git a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts index 7ac93596507..a113fb5a4c7 100644 --- a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts +++ b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts @@ -307,26 +307,31 @@ test('$$', () => { test('$$ with some edge cases',()=>{ const { code } = transform(` - let a = $ref(1), e = $ref() - $$() - $$(count++,count) - ($$(count++,count)) - count = $$(count++,count) - count = ()=>$$(count++,count) - const af=()=>($$(count++,count)) - let c = $ref(a, $$(count++,count)) - let r1 = $$(count++,count) - let r2 = $ref(af($$(count++,count))) - let r3 = { a:$$(count++,count) } + $$(a) + console.log($$($$(a))) + $$(a,b) + $$($$((a,b))) + count = $$(a++,b) + count = ()=>$$(a++,b) + let r1 = $ref(a, $$(a++,b)) + let r2 = { a:$$(a++,b),b:$$(a) } + switch(c){ + case d: + $$(a) + $$($$(h,f)) + break + } + ($$(count++,$$(count),$$(count,a))) `) - expect(code).toMatch(`;(count++,count)`) - expect(code).toMatch(`((count++,count))`) - expect(code).toMatch(`count = (count++,count)`) - expect(code).toMatch(`()=>(count++,count)`) - expect(code).toMatch(`()=>((count++,count))`) - expect(code).toMatch(`let r1 = (count++,count)`) - expect(code).toMatch(`let r2 = _ref(af((count++,count)))`) - expect(code).toMatch(`let r3 = { a:(count++,count) }`) + expect(code).toMatch(`((count++,count,(count,a)))`) + expect(code).toMatch(`;(a,b)`) + expect(code).toMatch(`log(a)`) + expect(code).toMatch(`count = (a++,b)`) + expect(code).toMatch(`()=>(a++,b)`) + expect(code).toMatch(`_ref(a, (a++,b))`) + expect(code).toMatch(`{ a:(a++,b),b:a }`) + expect(code).toMatch(`switch(c)`) + expect(code).toMatch(`;(h,f)`) assertCode(code) }) diff --git a/packages/reactivity-transform/src/reactivityTransform.ts b/packages/reactivity-transform/src/reactivityTransform.ts index 04c6dbb4469..0762c0a537a 100644 --- a/packages/reactivity-transform/src/reactivityTransform.ts +++ b/packages/reactivity-transform/src/reactivityTransform.ts @@ -555,35 +555,53 @@ export function transformAST( */ function unwrapMacro(node: CallExpression) { const argsLength = node.arguments.length - s.remove(node.callee.start! + offset, node.callee.end! + offset) - if (!argsLength) { + const bracketStart = node.callee.end! + offset + + s.remove(node.callee.start! + offset, bracketStart) + + if (argsLength === 1) { + const bracketEnd = node.arguments[argsLength - 1].end! + offset + + // remove brackets of macros + s.remove(bracketStart, bracketStart + 1) + s.remove(bracketEnd, bracketEnd + 1) + + // avoid traversal of like `$$(a)` + if(node.arguments[0].type!=="CallExpression"){ + return; + } + } + + // avoid invalid traversal for $ + if (!escapeScope|| node.extra) { return - } else if (argsLength === 1) { - // remove brackets of macro - s.remove(node.callee.end! + offset, node.arguments[0].start! + offset) - s.remove(node.arguments[argsLength - 1].end! + offset, node.end! + offset) - } else { - // handle some edge cases for macro $$ - // resolve nested - let i = parentStack.length - 1 - while (i >= 0) { - const curParent = parentStack[i--] - // see @__tests__:$$ with some edge cases - if ( - curParent.type === 'VariableDeclarator' || - curParent.type === 'AssignmentExpression' || - (curParent.type === 'ExpressionStatement' && - (curParent.expression.extra || - (curParent.expression.type === 'CallExpression' && - curParent.expression.arguments.includes(node)))) - ) { - return - } + } + + // fix some edge cases for macro $$, eg. $$(a,b) + // resolve nested + let i = parentStack.length - 1 + while (i >= 0) { + const curParent = parentStack[i--] + if ( + curParent.type === 'ExpressionStatement' && + isIsolateExpression(curParent.expression, node) + ) { + // split the unwrapped code `()()` to `();()` + s.appendLeft(node.callee.start! + offset, ';') + return } - s.appendLeft(node.callee.start! + offset, ';') } } + function isIsolateExpression(expression: Expression, node: CallExpression) { + return ( + expression.type === 'CallExpression' && + expression.callee.type === 'Identifier' && + expression.callee.name === escapeSymbol && + !expression.arguments.includes(node) + ) + } + // check root scope first walkScope(ast, true) ;(walk as any)(ast, { @@ -657,8 +675,8 @@ export function transformAST( } if (callee === escapeSymbol) { - unwrapMacro(node) escapeScope = node + unwrapMacro(node) } // TODO remove when out of experimental From 05591322f7d0a1e03011c369892055b0b8144708 Mon Sep 17 00:00:00 2001 From: tuchg Date: Fri, 28 Oct 2022 22:50:45 +0800 Subject: [PATCH 05/13] fix(reactivity-transform): edge case for space --- .../reactivityTransform.spec.ts.snap | 4 +- .../__tests__/reactivityTransform.spec.ts | 8 ++-- .../src/reactivityTransform.ts | 42 ++++++++++++------- 3 files changed, 32 insertions(+), 22 deletions(-) diff --git a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap index 95e2466580b..1e2c5aa1d82 100644 --- a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap +++ b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap @@ -27,11 +27,11 @@ exports[`$$ 1`] = ` exports[`$$ with some edge cases 1`] = ` "import { ref as _ref } from 'vue' - a + count console.log(a) ;(a,b) ;(a,b) - count = (a++,b) + count = ( a++ ,b) count = ()=>(a++,b) let r1 = _ref(a, (a++,b)) let r2 = { a:(a++,b),b:a } diff --git a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts index a113fb5a4c7..6cda0219b07 100644 --- a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts +++ b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts @@ -307,14 +307,14 @@ test('$$', () => { test('$$ with some edge cases',()=>{ const { code } = transform(` - $$(a) + $$ (count ) console.log($$($$(a))) $$(a,b) $$($$((a,b))) - count = $$(a++,b) + count = $$( a++ ,b) count = ()=>$$(a++,b) let r1 = $ref(a, $$(a++,b)) - let r2 = { a:$$(a++,b),b:$$(a) } + let r2 = { a:$$(a++,b),b:$$ (a) } switch(c){ case d: $$(a) @@ -326,7 +326,7 @@ test('$$ with some edge cases',()=>{ expect(code).toMatch(`((count++,count,(count,a)))`) expect(code).toMatch(`;(a,b)`) expect(code).toMatch(`log(a)`) - expect(code).toMatch(`count = (a++,b)`) + expect(code).toMatch(`count = ( a++ ,b)`) expect(code).toMatch(`()=>(a++,b)`) expect(code).toMatch(`_ref(a, (a++,b))`) expect(code).toMatch(`{ a:(a++,b),b:a }`) diff --git a/packages/reactivity-transform/src/reactivityTransform.ts b/packages/reactivity-transform/src/reactivityTransform.ts index 0762c0a537a..ff9f004af3b 100644 --- a/packages/reactivity-transform/src/reactivityTransform.ts +++ b/packages/reactivity-transform/src/reactivityTransform.ts @@ -561,19 +561,25 @@ export function transformAST( if (argsLength === 1) { const bracketEnd = node.arguments[argsLength - 1].end! + offset - // remove brackets of macros - s.remove(bracketStart, bracketStart + 1) - s.remove(bracketEnd, bracketEnd + 1) + if (node.arguments[0].type === 'SequenceExpression') { + // fix $$((a,b)) + s.remove(bracketStart, bracketStart + 1) + s.remove(bracketEnd, bracketEnd + 1) + } else { + // fix space place + s.remove(node.start! + offset, node.arguments[0].start! + offset) + s.remove(bracketEnd, node.end! + offset) + } // avoid traversal of like `$$(a)` - if(node.arguments[0].type!=="CallExpression"){ - return; + if (node.arguments[0].type !== 'CallExpression') { + return } } // avoid invalid traversal for $ - if (!escapeScope|| node.extra) { + if (!escapeScope || node.extra) { return } @@ -584,7 +590,7 @@ export function transformAST( const curParent = parentStack[i--] if ( curParent.type === 'ExpressionStatement' && - isIsolateExpression(curParent.expression, node) + isIsolateExpression(curParent.expression, node, escapeSymbol) ) { // split the unwrapped code `()()` to `();()` s.appendLeft(node.callee.start! + offset, ';') @@ -593,15 +599,6 @@ export function transformAST( } } - function isIsolateExpression(expression: Expression, node: CallExpression) { - return ( - expression.type === 'CallExpression' && - expression.callee.type === 'Identifier' && - expression.callee.name === escapeSymbol && - !expression.arguments.includes(node) - ) - } - // check root scope first walkScope(ast, true) ;(walk as any)(ast, { @@ -717,6 +714,19 @@ export function transformAST( } } +function isIsolateExpression( + expression: Expression, + node: CallExpression, + escapeSymbol: string +) { + return ( + expression.type === 'CallExpression' && + expression.callee.type === 'Identifier' && + expression.callee.name === escapeSymbol && + !expression.arguments.includes(node) + ) +} + const RFC_LINK = `https://github.com/vuejs/rfcs/discussions/369` const hasWarned: Record = {} From 2714a2d61b1135faf6f0e8586736412490304544 Mon Sep 17 00:00:00 2001 From: tuchg Date: Sat, 29 Oct 2022 09:42:27 +0800 Subject: [PATCH 06/13] fix(reactivity-transform): edge case for various expressions --- .../__tests__/reactivityTransform.spec.ts | 10 ++- .../src/reactivityTransform.ts | 63 ++++++++++--------- 2 files changed, 44 insertions(+), 29 deletions(-) diff --git a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts index 6cda0219b07..35315bea450 100644 --- a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts +++ b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts @@ -307,6 +307,11 @@ test('$$', () => { test('$$ with some edge cases',()=>{ const { code } = transform(` + { + a:$$(count,a) + } + $$((count) + 1) + $$([count]) $$ (count ) console.log($$($$(a))) $$(a,b) @@ -323,7 +328,9 @@ test('$$ with some edge cases',()=>{ } ($$(count++,$$(count),$$(count,a))) `) - expect(code).toMatch(`((count++,count,(count,a)))`) + expect(code).toMatch("a:(count,a)") + expect(code).toMatch(";((count) + 1)") + expect(code).toMatch(";([count])") expect(code).toMatch(`;(a,b)`) expect(code).toMatch(`log(a)`) expect(code).toMatch(`count = ( a++ ,b)`) @@ -332,6 +339,7 @@ test('$$ with some edge cases',()=>{ expect(code).toMatch(`{ a:(a++,b),b:a }`) expect(code).toMatch(`switch(c)`) expect(code).toMatch(`;(h,f)`) + expect(code).toMatch(`((count++,count,(count,a)))`) assertCode(code) }) diff --git a/packages/reactivity-transform/src/reactivityTransform.ts b/packages/reactivity-transform/src/reactivityTransform.ts index ff9f004af3b..24f29f615a2 100644 --- a/packages/reactivity-transform/src/reactivityTransform.ts +++ b/packages/reactivity-transform/src/reactivityTransform.ts @@ -562,19 +562,24 @@ export function transformAST( if (argsLength === 1) { const bracketEnd = node.arguments[argsLength - 1].end! + offset // remove brackets of macros - if (node.arguments[0].type === 'SequenceExpression') { - // fix $$((a,b)) - s.remove(bracketStart, bracketStart + 1) - s.remove(bracketEnd, bracketEnd + 1) - } else { + const argsType = node.arguments[0].type + if ( + argsType === 'CallExpression' || + argsType === 'Identifier' || + argsType === 'ObjectExpression' + ) { // fix space place s.remove(node.start! + offset, node.arguments[0].start! + offset) s.remove(bracketEnd, node.end! + offset) - } - // avoid traversal of like `$$(a)` - if (node.arguments[0].type !== 'CallExpression') { - return + // avoid traversal of like `$$(a)` + if (argsType === 'Identifier') { + return + } + } else if (argsType === 'SequenceExpression') { + // fix $$((a,b)) + s.remove(bracketStart, bracketStart + 1) + s.remove(bracketEnd, bracketEnd + 1) } } @@ -585,18 +590,33 @@ export function transformAST( // fix some edge cases for macro $$, eg. $$(a,b) // resolve nested + if (isIsolateExpression(node)) { + // split the unwrapped code `()()` to `();()` + s.appendLeft(node.callee.start! + offset, ';') + } + } + + function isIsolateExpression(node: CallExpression) { let i = parentStack.length - 1 while (i >= 0) { - const curParent = parentStack[i--] + const curParent = parentStack[i] + if (curParent.type !== 'ExpressionStatement') { + i-- + continue + } + const expression = curParent.expression if ( - curParent.type === 'ExpressionStatement' && - isIsolateExpression(curParent.expression, node, escapeSymbol) + expression.type === 'CallExpression' && + expression.callee.type === 'Identifier' && + expression.callee.name === escapeSymbol && + !expression.arguments.includes(node) && + (i < 1 || parentStack[i - 1].type !== 'LabeledStatement') ) { - // split the unwrapped code `()()` to `();()` - s.appendLeft(node.callee.start! + offset, ';') - return + return true } + i-- } + return false } // check root scope first @@ -714,19 +734,6 @@ export function transformAST( } } -function isIsolateExpression( - expression: Expression, - node: CallExpression, - escapeSymbol: string -) { - return ( - expression.type === 'CallExpression' && - expression.callee.type === 'Identifier' && - expression.callee.name === escapeSymbol && - !expression.arguments.includes(node) - ) -} - const RFC_LINK = `https://github.com/vuejs/rfcs/discussions/369` const hasWarned: Record = {} From 276f986496956e974d008af6cf07cd61e447e547 Mon Sep 17 00:00:00 2001 From: tuchg Date: Sat, 29 Oct 2022 09:47:45 +0800 Subject: [PATCH 07/13] fix(reactivity-transform): update tests snapshot --- .../__tests__/__snapshots__/reactivityTransform.spec.ts.snap | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap index 1e2c5aa1d82..5ed2eabe8a4 100644 --- a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap +++ b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap @@ -27,6 +27,11 @@ exports[`$$ 1`] = ` exports[`$$ with some edge cases 1`] = ` "import { ref as _ref } from 'vue' + { + a:(count,a) + } + ;((count) + 1) + ;([count]) count console.log(a) ;(a,b) From 3d97408f98607103d2f08f73c960d8255102d6f5 Mon Sep 17 00:00:00 2001 From: tuchg Date: Sat, 29 Oct 2022 12:09:03 +0800 Subject: [PATCH 08/13] fix(reactivity-transform): edge case for comments --- .../reactivityTransform.spec.ts.snap | 3 +++ .../__tests__/reactivityTransform.spec.ts | 16 +++++++++----- .../src/reactivityTransform.ts | 21 ++++++++++++------- 3 files changed, 27 insertions(+), 13 deletions(-) diff --git a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap index 5ed2eabe8a4..fe859c19f62 100644 --- a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap +++ b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap @@ -27,6 +27,9 @@ exports[`$$ 1`] = ` exports[`$$ with some edge cases 1`] = ` "import { ref as _ref } from 'vue' + /* 2 */ count /* 2 */ + ;( count /* 2 */, /**/ a ) + ; (count /* 2 */, /**/ a /**/ ) { a:(count,a) } diff --git a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts index 35315bea450..551de065519 100644 --- a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts +++ b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts @@ -307,6 +307,9 @@ test('$$', () => { test('$$ with some edge cases',()=>{ const { code } = transform(` + $$( /* 2 */ count /* 2 */ ) + $$( count /* 2 */, /**/ a ) + $$( (count /* 2 */, /**/ a) /**/ ) { a:$$(count,a) } @@ -315,12 +318,12 @@ test('$$ with some edge cases',()=>{ $$ (count ) console.log($$($$(a))) $$(a,b) - $$($$((a,b))) + $$($$((a++,b))) count = $$( a++ ,b) count = ()=>$$(a++,b) let r1 = $ref(a, $$(a++,b)) let r2 = { a:$$(a++,b),b:$$ (a) } - switch(c){ + switch($$(c)){ case d: $$(a) $$($$(h,f)) @@ -328,9 +331,12 @@ test('$$ with some edge cases',()=>{ } ($$(count++,$$(count),$$(count,a))) `) - expect(code).toMatch("a:(count,a)") - expect(code).toMatch(";((count) + 1)") - expect(code).toMatch(";([count])") + expect(code).toMatch(`/* 2 */ count /* 2 */`) + expect(code).toMatch(`;( count /* 2 */, /**/ a )`) + expect(code).toMatch(`; (count /* 2 */, /**/ a /**/ )`) + expect(code).toMatch(`a:(count,a)`) + expect(code).toMatch(`;((count) + 1)`) + expect(code).toMatch(`;([count])`) expect(code).toMatch(`;(a,b)`) expect(code).toMatch(`log(a)`) expect(code).toMatch(`count = ( a++ ,b)`) diff --git a/packages/reactivity-transform/src/reactivityTransform.ts b/packages/reactivity-transform/src/reactivityTransform.ts index 24f29f615a2..7513c31937d 100644 --- a/packages/reactivity-transform/src/reactivityTransform.ts +++ b/packages/reactivity-transform/src/reactivityTransform.ts @@ -554,23 +554,28 @@ export function transformAST( * unwrap the code form the macro($、$$), fix #6312 and keep the ideally behavior with the RFC#369 */ function unwrapMacro(node: CallExpression) { - const argsLength = node.arguments.length const bracketStart = node.callee.end! + offset - s.remove(node.callee.start! + offset, bracketStart) - if (argsLength === 1) { - const bracketEnd = node.arguments[argsLength - 1].end! + offset + if (node.arguments.length === 1) { + const bracketEnd = node.arguments.at(-1)!.end! + offset // remove brackets of macros - const argsType = node.arguments[0].type + const firstArg = node.arguments[0] + const argsType = firstArg.type if ( argsType === 'CallExpression' || argsType === 'Identifier' || argsType === 'ObjectExpression' ) { - // fix space place - s.remove(node.start! + offset, node.arguments[0].start! + offset) - s.remove(bracketEnd, node.end! + offset) + const leading = firstArg.leadingComments?.at(0)!.start ?? Infinity + const trailing = firstArg.trailingComments?.at(-1)!.end ?? 0 + console.log(leading, trailing) + // fix space & comments place + s.remove( + node.start! + offset, + Math.min(firstArg.start!, leading) + offset + ) + s.remove(Math.max(bracketEnd, trailing + offset), node.end! + offset) // avoid traversal of like `$$(a)` if (argsType === 'Identifier') { From 1d62c92dbf7874864463182974f059af56bb4c1e Mon Sep 17 00:00:00 2001 From: tuchg Date: Sat, 29 Oct 2022 12:15:12 +0800 Subject: [PATCH 09/13] fix(reactivity-transform): update snaps --- .../__tests__/__snapshots__/reactivityTransform.spec.ts.snap | 2 +- packages/reactivity-transform/src/reactivityTransform.ts | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap index fe859c19f62..170366c0c17 100644 --- a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap +++ b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap @@ -38,7 +38,7 @@ exports[`$$ with some edge cases 1`] = ` count console.log(a) ;(a,b) - ;(a,b) + ;(a++,b) count = ( a++ ,b) count = ()=>(a++,b) let r1 = _ref(a, (a++,b)) diff --git a/packages/reactivity-transform/src/reactivityTransform.ts b/packages/reactivity-transform/src/reactivityTransform.ts index 7513c31937d..f453819ffc7 100644 --- a/packages/reactivity-transform/src/reactivityTransform.ts +++ b/packages/reactivity-transform/src/reactivityTransform.ts @@ -569,7 +569,6 @@ export function transformAST( ) { const leading = firstArg.leadingComments?.at(0)!.start ?? Infinity const trailing = firstArg.trailingComments?.at(-1)!.end ?? 0 - console.log(leading, trailing) // fix space & comments place s.remove( node.start! + offset, From 1b8622603f8f1a2de0ac7d5e33788363acccbcfc Mon Sep 17 00:00:00 2001 From: tuchg Date: Wed, 9 Nov 2022 09:13:30 +0800 Subject: [PATCH 10/13] fix: update snap --- .../__snapshots__/reactivityTransform.spec.ts.snap | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap index 170366c0c17..d6e87661da1 100644 --- a/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap +++ b/packages/reactivity-transform/__tests__/__snapshots__/reactivityTransform.spec.ts.snap @@ -90,7 +90,7 @@ exports[`array destructure 1`] = ` let n = _ref(1), __$temp_1 = useFoo(), a = _toRef(__$temp_1, 0), - b = _toRef(__$temp_1, 1, 1) + b = _toRef(__$temp_1, 1, 1); console.log(n.value, a.value, b.value) " `; @@ -119,7 +119,7 @@ exports[`macro import alias and removal 1`] = ` let a = _ref(1) const __$temp_1 = useMouse(), x = _toRef(__$temp_1, 'x'), - y = _toRef(__$temp_1, 'y') + y = _toRef(__$temp_1, 'y'); " `; @@ -159,10 +159,10 @@ exports[`nested destructure 1`] = ` "import { toRef as _toRef } from 'vue' let __$temp_1 = useFoo(), - b = _toRef(__$temp_1[0].a, 'b') + b = _toRef(__$temp_1[0].a, 'b'); let __$temp_2 = useBar(), d = _toRef(__$temp_2.c, 0), - e = _toRef(__$temp_2.c, 1) + e = _toRef(__$temp_2.c, 1); console.log(b.value, d.value, e.value) " `; @@ -212,9 +212,9 @@ exports[`object destructure 1`] = ` c = _toRef(__$temp_1, 'b'), d = _toRef(__$temp_1, 'd', 1), f = _toRef(__$temp_1, 'e', 2), - h = _toRef(__$temp_1, g) + h = _toRef(__$temp_1, g); let __$temp_2 = useSomething(() => 1), - foo = _toRef(__$temp_2, 'foo'); + foo = _toRef(__$temp_2, 'foo');; console.log(n.value, a.value, c.value, d.value, f.value, h.value, foo.value) " `; @@ -223,7 +223,7 @@ exports[`object destructure w/ mid-path default values 1`] = ` "import { toRef as _toRef } from 'vue' const __$temp_1 = useFoo(), - b = _toRef((__$temp_1.a || { b: 123 }), 'b') + b = _toRef((__$temp_1.a || { b: 123 }), 'b'); console.log(b.value) " `; From b664c09133f95f2919165cfb69b083bbc2e4d558 Mon Sep 17 00:00:00 2001 From: tuchg Date: Wed, 9 Nov 2022 09:30:20 +0800 Subject: [PATCH 11/13] fix: code style --- .../reactivity-transform/__tests__/reactivityTransform.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts index 551de065519..8e9dcdb9ef8 100644 --- a/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts +++ b/packages/reactivity-transform/__tests__/reactivityTransform.spec.ts @@ -305,7 +305,7 @@ test('$$', () => { assertCode(code) }) -test('$$ with some edge cases',()=>{ +test('$$ with some edge cases', () => { const { code } = transform(` $$( /* 2 */ count /* 2 */ ) $$( count /* 2 */, /**/ a ) From 7777607e28246d8e3b0e4f20ced5ae31f337bf9c Mon Sep 17 00:00:00 2001 From: tuchg Date: Wed, 9 Nov 2022 10:39:29 +0800 Subject: [PATCH 12/13] fix: format --- .../src/reactivityTransform.ts | 262 +++++++++--------- 1 file changed, 131 insertions(+), 131 deletions(-) diff --git a/packages/reactivity-transform/src/reactivityTransform.ts b/packages/reactivity-transform/src/reactivityTransform.ts index 82cb0c10f77..73c8b5e31b3 100644 --- a/packages/reactivity-transform/src/reactivityTransform.ts +++ b/packages/reactivity-transform/src/reactivityTransform.ts @@ -61,13 +61,13 @@ export interface ImportBinding { } export function transform( - src: string, - { - filename, - sourceMap, - parserPlugins, - importHelpersFrom = 'vue' - }: RefTransformOptions = {} + src: string, + { + filename, + sourceMap, + parserPlugins, + importHelpersFrom = 'vue' + }: RefTransformOptions = {} ): RefTransformResults { const plugins: ParserPlugin[] = parserPlugins || [] if (filename) { @@ -89,9 +89,9 @@ export function transform( // inject helper imports if (res.importedHelpers.length) { s.prepend( - `import { ${res.importedHelpers - .map(h => `${h} as _${h}`) - .join(', ')} } from '${importHelpersFrom}'\n` + `import { ${res.importedHelpers + .map(h => `${h} as _${h}`) + .join(', ')} } from '${importHelpersFrom}'\n` ) } @@ -99,27 +99,27 @@ export function transform( ...res, code: s.toString(), map: sourceMap - ? s.generateMap({ + ? s.generateMap({ source: filename, hires: true, includeContent: true }) - : null + : null } } export function transformAST( - ast: Program, - s: MagicString, - offset = 0, - knownRefs?: string[], - knownProps?: Record< - string, // public prop key - { - local: string // local identifier, may be different - default?: any - } - > + ast: Program, + s: MagicString, + offset = 0, + knownRefs?: string[], + knownProps?: Record< + string, // public prop key + { + local: string // local identifier, may be different + default?: any + } + > ): { rootRefs: string[] importedHelpers: string[] @@ -137,7 +137,7 @@ export function transformAST( let convertSymbol: string | undefined let escapeSymbol: string | undefined for (const { local, imported, source, specifier } of Object.values( - userImports + userImports )) { if (source === IMPORT_SOURCE) { if (imported === ESCAPE_SYMBOL) { @@ -146,8 +146,8 @@ export function transformAST( convertSymbol = local } else if (imported !== local) { error( - `macro imports for ref-creating methods do not support aliasing.`, - specifier + `macro imports for ref-creating methods do not support aliasing.`, + specifier ) } } @@ -192,10 +192,10 @@ export function transformAST( for (const specifier of node.specifiers) { const local = specifier.local.name const imported = - (specifier.type === 'ImportSpecifier' && - specifier.imported.type === 'Identifier' && - specifier.imported.name) || - 'default' + (specifier.type === 'ImportSpecifier' && + specifier.imported.type === 'Identifier' && + specifier.imported.name) || + 'default' userImports[local] = { source, local, @@ -235,8 +235,8 @@ export function transformAST( currentScope[id.name] = isRef } else { error( - 'registerBinding called without active scope, something is wrong.', - id + 'registerBinding called without active scope, something is wrong.', + id ) } } @@ -257,25 +257,25 @@ export function transformAST( if (stmt.type === 'VariableDeclaration') { walkVariableDeclaration(stmt, isRoot) } else if ( - stmt.type === 'FunctionDeclaration' || - stmt.type === 'ClassDeclaration' + stmt.type === 'FunctionDeclaration' || + stmt.type === 'ClassDeclaration' ) { if (stmt.declare || !stmt.id) continue registerBinding(stmt.id) } else if ( - (stmt.type === 'ForOfStatement' || stmt.type === 'ForInStatement') && - stmt.left.type === 'VariableDeclaration' + (stmt.type === 'ForOfStatement' || stmt.type === 'ForInStatement') && + stmt.left.type === 'VariableDeclaration' ) { walkVariableDeclaration(stmt.left) } else if ( - stmt.type === 'ExportNamedDeclaration' && - stmt.declaration && - stmt.declaration.type === 'VariableDeclaration' + stmt.type === 'ExportNamedDeclaration' && + stmt.declaration && + stmt.declaration.type === 'VariableDeclaration' ) { walkVariableDeclaration(stmt.declaration, isRoot) } else if ( - stmt.type === 'LabeledStatement' && - stmt.body.type === 'VariableDeclaration' + stmt.type === 'LabeledStatement' && + stmt.body.type === 'VariableDeclaration' ) { walkVariableDeclaration(stmt.body, isRoot) } @@ -289,17 +289,17 @@ export function transformAST( for (const decl of stmt.declarations) { let refCall const isCall = - decl.init && - decl.init.type === 'CallExpression' && - decl.init.callee.type === 'Identifier' + decl.init && + decl.init.type === 'CallExpression' && + decl.init.callee.type === 'Identifier' if ( - isCall && - (refCall = isRefCreationCall((decl as any).init.callee.name)) + isCall && + (refCall = isRefCreationCall((decl as any).init.callee.name)) ) { processRefDeclaration(refCall, decl.id, decl.init as CallExpression) } else { const isProps = - isRoot && isCall && (decl as any).init.callee.name === 'defineProps' + isRoot && isCall && (decl as any).init.callee.name === 'defineProps' for (const id of extractIdentifiers(decl.id)) { if (isProps) { // for defineProps destructure, only exclude them since they @@ -314,9 +314,9 @@ export function transformAST( } function processRefDeclaration( - method: string, - id: VariableDeclarator['id'], - call: CallExpression + method: string, + id: VariableDeclarator['id'], + call: CallExpression ) { excludedIds.add(call.callee as Identifier) if (method === convertSymbol) { @@ -337,9 +337,9 @@ export function transformAST( registerRefBinding(id) // replace call s.overwrite( - call.start! + offset, - call.start! + method.length + offset, - helper(method.slice(1)) + call.start! + offset, + call.start! + method.length + offset, + helper(method.slice(1)) ) } else { error(`${method}() cannot be used with destructure patterns.`, call) @@ -348,10 +348,10 @@ export function transformAST( } function processRefObjectPattern( - pattern: ObjectPattern, - call: CallExpression, - tempVar?: string, - path: PathSegment[] = [] + pattern: ObjectPattern, + call: CallExpression, + tempVar?: string, + path: PathSegment[] = [] ) { if (!tempVar) { tempVar = genTempVar() @@ -371,8 +371,8 @@ export function transformAST( // avoid shorthand value identifier from being processed excludedIds.add(p.value) } else if ( - p.value.type === 'AssignmentPattern' && - p.value.left.type === 'Identifier' + p.value.type === 'AssignmentPattern' && + p.value.left.type === 'Identifier' ) { // { foo = 1 } excludedIds.add(p.value.left) @@ -416,16 +416,16 @@ export function transformAST( // inject toRef() after original replaced pattern const source = pathToString(tempVar, path) const keyStr = isString(key) - ? `'${key}'` - : key - ? snip(key) - : `'${nameId.name}'` + ? `'${key}'` + : key + ? snip(key) + : `'${nameId.name}'` const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : `` s.appendLeft( - call.end! + offset, - `,\n ${nameId.name} = ${helper( - 'toRef' - )}(${source}, ${keyStr}${defaultStr})` + call.end! + offset, + `,\n ${nameId.name} = ${helper( + 'toRef' + )}(${source}, ${keyStr}${defaultStr})` ) } } @@ -435,10 +435,10 @@ export function transformAST( } function processRefArrayPattern( - pattern: ArrayPattern, - call: CallExpression, - tempVar?: string, - path: PathSegment[] = [] + pattern: ArrayPattern, + call: CallExpression, + tempVar?: string, + path: PathSegment[] = [] ) { if (!tempVar) { // const [x] = $(useFoo()) --> const __$temp_1 = useFoo() @@ -472,10 +472,10 @@ export function transformAST( const source = pathToString(tempVar, path) const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : `` s.appendLeft( - call.end! + offset, - `,\n ${nameId.name} = ${helper( - 'toRef' - )}(${source}, ${i}${defaultStr})` + call.end! + offset, + `,\n ${nameId.name} = ${helper( + 'toRef' + )}(${source}, ${i}${defaultStr})` ) } } @@ -487,8 +487,8 @@ export function transformAST( type PathSegmentAtom = Expression | string | number type PathSegment = - | PathSegmentAtom - | [PathSegmentAtom, Expression /* default value */] + | PathSegmentAtom + | [PathSegmentAtom, Expression /* default value */] function pathToString(source: string, path: PathSegment[]): string { if (path.length) { @@ -514,10 +514,10 @@ export function transformAST( } function rewriteId( - scope: Scope, - id: Identifier, - parent: Node, - parentStack: Node[] + scope: Scope, + id: Identifier, + parent: Node, + parentStack: Node[] ): boolean { if (hasOwn(scope, id.name)) { const bindingType = scope[id.name] @@ -527,8 +527,8 @@ export function transformAST( // let binding used in a property shorthand // skip for destructure patterns if ( - !(parent as any).inPattern || - isInDestructureAssignment(parent, parentStack) + !(parent as any).inPattern || + isInDestructureAssignment(parent, parentStack) ) { if (isProp) { if (escapeScope) { @@ -536,14 +536,14 @@ export function transformAST( // { prop } -> { prop: __props_prop } registerEscapedPropBinding(id) s.appendLeft( - id.end! + offset, - `: __props_${propsLocalToPublicMap[id.name]}` + id.end! + offset, + `: __props_${propsLocalToPublicMap[id.name]}` ) } else { // { prop } -> { prop: __props.prop } s.appendLeft( - id.end! + offset, - `: ${genPropsAccessExp(propsLocalToPublicMap[id.name])}` + id.end! + offset, + `: ${genPropsAccessExp(propsLocalToPublicMap[id.name])}` ) } } else { @@ -557,16 +557,16 @@ export function transformAST( // x --> __props_x registerEscapedPropBinding(id) s.overwrite( - id.start! + offset, - id.end! + offset, - `__props_${propsLocalToPublicMap[id.name]}` + id.start! + offset, + id.end! + offset, + `__props_${propsLocalToPublicMap[id.name]}` ) } else { // x --> __props.x s.overwrite( - id.start! + offset, - id.end! + offset, - genPropsAccessExp(propsLocalToPublicMap[id.name]) + id.start! + offset, + id.end! + offset, + genPropsAccessExp(propsLocalToPublicMap[id.name]) ) } } else { @@ -586,10 +586,10 @@ export function transformAST( propBindingRefs[id.name] = true const publicKey = propsLocalToPublicMap[id.name] s.prependRight( - offset, - `const __props_${publicKey} = ${helper( - `toRef` - )}(__props, '${publicKey}');\n` + offset, + `const __props_${publicKey} = ${helper( + `toRef` + )}(__props, '${publicKey}');\n` ) } } @@ -607,16 +607,16 @@ export function transformAST( const firstArg = node.arguments[0] const argsType = firstArg.type if ( - argsType === 'CallExpression' || - argsType === 'Identifier' || - argsType === 'ObjectExpression' + argsType === 'CallExpression' || + argsType === 'Identifier' || + argsType === 'ObjectExpression' ) { const leading = firstArg.leadingComments?.at(0)!.start ?? Infinity const trailing = firstArg.trailingComments?.at(-1)!.end ?? 0 // fix space & comments place s.remove( - node.start! + offset, - Math.min(firstArg.start!, leading) + offset + node.start! + offset, + Math.min(firstArg.start!, leading) + offset ) s.remove(Math.max(bracketEnd, trailing + offset), node.end! + offset) @@ -654,11 +654,11 @@ export function transformAST( } const expression = curParent.expression if ( - expression.type === 'CallExpression' && - expression.callee.type === 'Identifier' && - expression.callee.name === escapeSymbol && - !expression.arguments.includes(node) && - (i < 1 || parentStack[i - 1].type !== 'LabeledStatement') + expression.type === 'CallExpression' && + expression.callee.type === 'Identifier' && + expression.callee.name === escapeSymbol && + !expression.arguments.includes(node) && + (i < 1 || parentStack[i - 1].type !== 'LabeledStatement') ) { return true } @@ -702,21 +702,21 @@ export function transformAST( // skip type nodes if ( - parent && - parent.type.startsWith('TS') && - parent.type !== 'TSAsExpression' && - parent.type !== 'TSNonNullExpression' && - parent.type !== 'TSTypeAssertion' + parent && + parent.type.startsWith('TS') && + parent.type !== 'TSAsExpression' && + parent.type !== 'TSNonNullExpression' && + parent.type !== 'TSTypeAssertion' ) { return this.skip() } if ( - node.type === 'Identifier' && - // if inside $$(), skip unless this is a destructured prop binding - !(escapeScope && rootScope[node.name] !== 'prop') && - isReferencedIdentifier(node, parent!, parentStack) && - !excludedIds.has(node) + node.type === 'Identifier' && + // if inside $$(), skip unless this is a destructured prop binding + !(escapeScope && rootScope[node.name] !== 'prop') && + isReferencedIdentifier(node, parent!, parentStack) && + !excludedIds.has(node) ) { // walk up the scope chain to check if id should be appended .value let i = scopeStack.length @@ -733,16 +733,16 @@ export function transformAST( const refCall = isRefCreationCall(callee) if (refCall && (!parent || parent.type !== 'VariableDeclarator')) { return error( - `${refCall} can only be used as the initializer of ` + + `${refCall} can only be used as the initializer of ` + `a variable declaration.`, - node + node ) } if ( - escapeSymbol && - currentScope[escapeSymbol] === undefined && - callee === escapeSymbol + escapeSymbol && + currentScope[escapeSymbol] === undefined && + callee === escapeSymbol ) { escapeScope = node unwrapMacro(node) @@ -751,16 +751,16 @@ export function transformAST( // TODO remove when out of experimental if (callee === '$raw') { error( - `$raw() has been replaced by $$(). ` + + `$raw() has been replaced by $$(). ` + `See ${RFC_LINK} for latest updates.`, - node + node ) } if (callee === '$fromRef') { error( - `$fromRef() has been replaced by $(). ` + + `$fromRef() has been replaced by $(). ` + `See ${RFC_LINK} for latest updates.`, - node + node ) } } @@ -768,8 +768,8 @@ export function transformAST( leave(node: Node, parent?: Node) { parent && parentStack.pop() if ( - (node.type === 'BlockStatement' && !isFunctionType(parent!)) || - isFunctionType(node) + (node.type === 'BlockStatement' && !isFunctionType(parent!)) || + isFunctionType(node) ) { scopeStack.pop() currentScope = scopeStack[scopeStack.length - 1] || null @@ -795,7 +795,7 @@ function warnExperimental() { return } warnOnce( - `Reactivity transform is an experimental feature.\n` + + `Reactivity transform is an experimental feature.\n` + `Experimental features may change behavior between patch versions.\n` + `It is recommended to pin your vue dependencies to exact versions to avoid breakage.\n` + `You can follow the proposal's status at ${RFC_LINK}.` @@ -804,7 +804,7 @@ function warnExperimental() { function warnOnce(msg: string) { const isNodeProd = - typeof process !== 'undefined' && process.env.NODE_ENV === 'production' + typeof process !== 'undefined' && process.env.NODE_ENV === 'production' if (!isNodeProd && !__TEST__ && !hasWarned[msg]) { hasWarned[msg] = true warn(msg) @@ -813,6 +813,6 @@ function warnOnce(msg: string) { function warn(msg: string) { console.warn( - `\x1b[1m\x1b[33m[@vue/reactivity-transform]\x1b[0m\x1b[33m ${msg}\x1b[0m\n` + `\x1b[1m\x1b[33m[@vue/reactivity-transform]\x1b[0m\x1b[33m ${msg}\x1b[0m\n` ) } From 9f1281acccbd47554c454aaf317fdbc3231882bd Mon Sep 17 00:00:00 2001 From: Evan You Date: Sun, 13 Nov 2022 21:26:59 -0500 Subject: [PATCH 13/13] Update packages/reactivity-transform/src/reactivityTransform.ts --- packages/reactivity-transform/src/reactivityTransform.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/reactivity-transform/src/reactivityTransform.ts b/packages/reactivity-transform/src/reactivityTransform.ts index 73c8b5e31b3..ef4cb6a29e4 100644 --- a/packages/reactivity-transform/src/reactivityTransform.ts +++ b/packages/reactivity-transform/src/reactivityTransform.ts @@ -595,7 +595,7 @@ export function transformAST( } /** - * unwrap the code form the macro($、$$), fix #6312 and keep the ideally behavior with the RFC#369 + * unwrap the code form the macro($、$$), fix #6312 and keep the desired behavior from RFC#369 */ function unwrapMacro(node: CallExpression) { const bracketStart = node.callee.end! + offset