Skip to content

Commit be6a0bf

Browse files
committed
refactor: simplify logic
1 parent a0290fe commit be6a0bf

File tree

1 file changed

+17
-23
lines changed

1 file changed

+17
-23
lines changed

packages/compiler-sfc/src/compileScript.ts

+17-23
Original file line numberDiff line numberDiff line change
@@ -1126,48 +1126,42 @@ export function compileScript(
11261126

11271127
// walk statements & named exports / variable declarations for top level
11281128
// await
1129-
let body = scriptSetupAst.body
11301129
if (
11311130
(node.type === 'VariableDeclaration' && !node.declare) ||
11321131
node.type.endsWith('Statement')
11331132
) {
1133+
const scope: Statement[][] = [scriptSetupAst.body]
11341134
;(walk as any)(node, {
11351135
enter(child: Node, parent: Node) {
11361136
if (isFunctionType(child)) {
11371137
this.skip()
11381138
}
1139-
if (child.type === 'ExpressionStatement') {
1140-
if (
1141-
child.expression.type === 'AwaitExpression' ||
1142-
child.expression.type === 'BinaryExpression'
1143-
) {
1144-
// set the parent of the AwaitExpression's body to the variable body
1145-
if (parent && parent.type === 'BlockStatement') {
1146-
body = parent.body
1147-
} else {
1148-
body = scriptSetupAst.body
1149-
}
1150-
}
1139+
if (child.type === 'BlockStatement') {
1140+
scope.push(child.body)
11511141
}
11521142
if (child.type === 'AwaitExpression') {
11531143
hasAwait = true
1154-
// set the AwaitExpression's index in the parent of the AwaitExpression's body to the variable AwaitIndex
1155-
let AwaitIndex = 0
1156-
let needsSemi = body.some((n, index) => {
1157-
AwaitIndex = index
1158-
return n.type === 'ExpressionStatement' && n.start === child.start
1144+
// if the await expression is an expression statement and
1145+
// - is in the root scope
1146+
// - or is not the first statement in a nested block scope
1147+
// then it needs a semicolon before the generated code.
1148+
const currentScope = scope[scope.length - 1]
1149+
const needsSemi = currentScope.some((n, i) => {
1150+
return (
1151+
(scope.length === 1 || i > 0) &&
1152+
n.type === 'ExpressionStatement' &&
1153+
n.start === child.start
1154+
)
11591155
})
1160-
// if the variable body is not equal scriptSetupAst.body
1161-
if (body !== scriptSetupAst.body) {
1162-
// judge the AwaitExpression is not in the first of the parent of the AwaitExpression's body
1163-
needsSemi = needsSemi && AwaitIndex > 0
1164-
}
11651156
processAwait(
11661157
child,
11671158
needsSemi,
11681159
parent.type === 'ExpressionStatement'
11691160
)
11701161
}
1162+
},
1163+
exit(node: Node) {
1164+
if (node.type === 'BlockStatement') scope.pop()
11711165
}
11721166
})
11731167
}

0 commit comments

Comments
 (0)