Skip to content

fix(compiler-vapor): prevent caching UpdateExpression #13346

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: vapor
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,25 @@ export function render(_ctx, $props, $emit, $attrs, $slots) {
return n0
}"
`;

exports[`compiler: expression > update expression 1`] = `
"import { child as _child, toDisplayString as _toDisplayString, setText as _setText, setProp as _setProp, renderEffect as _renderEffect, template as _template } from 'vue';
const t0 = _template("<div> </div>", true)

export function render(_ctx) {
const n1 = t0()
const n0 = _child(n1)
const x1 = _child(n1)
_renderEffect(() => {
const _String = String
const _foo = _ctx.foo

_setText(n0, _toDisplayString(_String(_foo.id++)) + " " + _toDisplayString(_foo) + " " + _toDisplayString(_ctx.bar))
_setText(x1, _toDisplayString(_String(_foo.id++)) + " " + _toDisplayString(_foo) + " " + _toDisplayString(_ctx.bar))
_setProp(n1, "id", _String(_foo.id++))
_setProp(n1, "foo", _foo)
_setProp(n1, "bar", _ctx.bar++)
})
return n1
}"
`;
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,19 @@ export function render(_ctx) {
}"
`;

exports[`compiler: template ref transform > function ref 1`] = `
"import { createTemplateRefSetter as _createTemplateRefSetter, renderEffect as _renderEffect, template as _template } from 'vue';
const t0 = _template("<div></div>", true)

export function render(_ctx) {
const _setTemplateRef = _createTemplateRefSetter()
const n0 = t0()
let r0
_renderEffect(() => r0 = _setTemplateRef(n0, bar => _ctx.foo = bar, r0))
return n0
}"
`;

exports[`compiler: template ref transform > ref + v-for 1`] = `
"import { createTemplateRefSetter as _createTemplateRefSetter, createFor as _createFor, template as _template } from 'vue';
const t0 = _template("<div></div>", true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,17 @@ export function render(_ctx) {
}"
`;

exports[`cache multiple access > not cache variable in function expression 1`] = `
"import { setDynamicProps as _setDynamicProps, renderEffect as _renderEffect, template as _template } from 'vue';
const t0 = _template("<div></div>", true)

export function render(_ctx) {
const n0 = t0()
_renderEffect(() => _setDynamicProps(n0, [{ foo: bar => _ctx.foo = bar }], true))
return n0
}"
`;

exports[`cache multiple access > not cache variable only used in property shorthand 1`] = `
"import { setStyle as _setStyle, renderEffect as _renderEffect, template as _template } from 'vue';
const t0 = _template("<div></div>", true)
Expand Down
20 changes: 18 additions & 2 deletions packages/compiler-vapor/__tests__/transforms/expression.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { BindingTypes } from '@vue/compiler-dom'
import { transformChildren, transformText } from '../../src'
import {
transformChildren,
transformElement,
transformText,
transformVBind,
} from '../../src'
import { makeCompile } from './_utils'

const compileWithExpression = makeCompile({
nodeTransforms: [transformChildren, transformText],
nodeTransforms: [transformElement, transformChildren, transformText],
directiveTransforms: { bind: transformVBind },
})

describe('compiler: expression', () => {
Expand Down Expand Up @@ -31,4 +37,14 @@ describe('compiler: expression', () => {
expect(code).toMatchSnapshot()
expect(code).contains(`$props['bar']`)
})

test('update expression', () => {
const { code } = compileWithExpression(`
<div :id="String(foo.id++)" :foo="foo" :bar="bar++">
{{ String(foo.id++) }} {{ foo }} {{ bar }}
</div>
`)
expect(code).toMatchSnapshot()
expect(code).contains(`_String(_foo.id++)`)
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,40 @@ describe('compiler: template ref transform', () => {
expect(code).contains('_setTemplateRef(n0, _ctx.foo, r0)')
})

test('function ref', () => {
const { ir, code } = compileWithTransformRef(
`<div :ref="bar => foo = bar" />`,
)
expect(ir.block.dynamic.children[0]).toMatchObject({
id: 0,
flags: DynamicFlag.REFERENCED,
})
expect(ir.template).toEqual(['<div></div>'])
expect(ir.block.operation).toMatchObject([
{
type: IRNodeTypes.DECLARE_OLD_REF,
id: 0,
},
])
expect(ir.block.effect).toMatchObject([
{
operations: [
{
type: IRNodeTypes.SET_TEMPLATE_REF,
element: 0,
value: {
content: 'bar => foo = bar',
isStatic: false,
},
},
],
},
])
expect(code).toMatchSnapshot()
expect(code).contains('const _setTemplateRef = _createTemplateRefSetter()')
expect(code).contains('_setTemplateRef(n0, bar => _ctx.foo = bar, r0)')
})

test('ref + v-if', () => {
const { ir, code } = compileWithTransformRef(
`<div ref="foo" v-if="true" />`,
Expand Down
8 changes: 8 additions & 0 deletions packages/compiler-vapor/__tests__/transforms/vBind.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -809,4 +809,12 @@ describe('cache multiple access', () => {
expect(code).matchSnapshot()
expect(code).not.contains('const _bar = _ctx.bar')
})

test('not cache variable in function expression', () => {
const { code } = compileWithVBind(`
<div v-bind="{ foo: bar => foo = bar }"></div>
`)
expect(code).matchSnapshot()
expect(code).not.contains('const _bar = _ctx.bar')
})
})
78 changes: 46 additions & 32 deletions packages/compiler-vapor/src/generators/expression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import type { Identifier, Node } from '@babel/types'
import type { CodegenContext } from '../generate'
import { isConstantExpression } from '../utils'
import { type CodeFragment, NEWLINE, buildCodeFragment } from './utils'
import { walk } from 'estree-walker'
import { type ParserOptions, parseExpression } from '@babel/parser'

export function genExpression(
Expand Down Expand Up @@ -245,8 +244,13 @@ export function processExpressions(
expressions: SimpleExpressionNode[],
): DeclarationResult {
// analyze variables
const { seenVariable, variableToExpMap, expToVariableMap, seenIdentifier } =
analyzeExpressions(expressions)
const {
seenVariable,
variableToExpMap,
expToVariableMap,
seenIdentifier,
updatedVariable,
} = analyzeExpressions(expressions)

// process repeated identifiers and member expressions
// e.g., `foo[baz]` will be transformed into `foo_baz`
Expand All @@ -256,6 +260,7 @@ export function processExpressions(
variableToExpMap,
expToVariableMap,
seenIdentifier,
updatedVariable,
)

// process duplicate expressions after identifier and member expression handling.
Expand All @@ -264,6 +269,8 @@ export function processExpressions(
context,
expressions,
varDeclarations,
updatedVariable,
expToVariableMap,
)

return genDeclarations([...varDeclarations, ...expDeclarations], context)
Expand All @@ -274,11 +281,13 @@ function analyzeExpressions(expressions: SimpleExpressionNode[]) {
const variableToExpMap = new Map<string, Set<SimpleExpressionNode>>()
const expToVariableMap = new Map<SimpleExpressionNode, string[]>()
const seenIdentifier = new Set<string>()
const updatedVariable = new Set<string>()

const registerVariable = (
name: string,
exp: SimpleExpressionNode,
isIdentifier: boolean,
parentStack: Node[] = [],
) => {
if (isIdentifier) seenIdentifier.add(name)
seenVariable[name] = (seenVariable[name] || 0) + 1
Expand All @@ -287,6 +296,8 @@ function analyzeExpressions(expressions: SimpleExpressionNode[]) {
(variableToExpMap.get(name) || new Set()).add(exp),
)
expToVariableMap.set(exp, (expToVariableMap.get(exp) || []).concat(name))
if (parentStack.some(p => p.type === 'UpdateExpression'))
updatedVariable.add(name)
}

for (const exp of expressions) {
Expand All @@ -295,37 +306,25 @@ function analyzeExpressions(expressions: SimpleExpressionNode[]) {
continue
}

walk(exp.ast, {
enter(currentNode: Node, parent: Node | null) {
if (currentNode.type === 'MemberExpression') {
const memberExp = extractMemberExpression(
currentNode,
(name: string) => {
registerVariable(name, exp, true)
},
)
registerVariable(memberExp, exp, false)
return this.skip()
}

// skip shorthand or non-computed property keys
if (
parent &&
parent.type === 'ObjectProperty' &&
parent.key === currentNode &&
(parent.shorthand || !parent.computed)
) {
return this.skip()
}

if (currentNode.type === 'Identifier') {
registerVariable(currentNode.name, exp, true)
}
},
walkIdentifiers(exp.ast, (currentNode, parent, parentStack) => {
if (parent && isMemberExpression(parent)) {
const memberExp = extractMemberExpression(parent, name => {
registerVariable(name, exp, true)
})
registerVariable(memberExp, exp, false, parentStack)
} else if (!parentStack.some(isMemberExpression)) {
registerVariable(currentNode.name, exp, true, parentStack)
}
})
}

return { seenVariable, seenIdentifier, variableToExpMap, expToVariableMap }
return {
seenVariable,
seenIdentifier,
variableToExpMap,
expToVariableMap,
updatedVariable,
}
}

function processRepeatedVariables(
Expand All @@ -334,9 +333,11 @@ function processRepeatedVariables(
variableToExpMap: Map<string, Set<SimpleExpressionNode>>,
expToVariableMap: Map<SimpleExpressionNode, string[]>,
seenIdentifier: Set<string>,
updatedVariable: Set<string>,
): DeclarationValue[] {
const declarations: DeclarationValue[] = []
for (const [name, exps] of variableToExpMap) {
if (updatedVariable.has(name)) continue
if (seenVariable[name] > 1 && exps.size > 0) {
const isIdentifier = seenIdentifier.has(name)
const varName = isIdentifier ? name : genVarName(name)
Expand Down Expand Up @@ -428,12 +429,19 @@ function processRepeatedExpressions(
context: CodegenContext,
expressions: SimpleExpressionNode[],
varDeclarations: DeclarationValue[],
updatedVariable: Set<string>,
expToVariableMap: Map<SimpleExpressionNode, string[]>,
): DeclarationValue[] {
const declarations: DeclarationValue[] = []
const seenExp = expressions.reduce(
(acc, exp) => {
const variables = expToVariableMap.get(exp)
// only handle expressions that are not identifiers
if (exp.ast && exp.ast.type !== 'Identifier') {
if (
exp.ast &&
exp.ast.type !== 'Identifier' &&
!(variables && variables.some(v => updatedVariable.has(v)))
) {
acc[exp.content] = (acc[exp.content] || 0) + 1
}
return acc
Expand Down Expand Up @@ -580,3 +588,9 @@ function extractMemberExpression(
return ''
}
}

const isMemberExpression = (node: Node) => {
return (
node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression'
)
}