Skip to content

Commit

Permalink
[feature] support labeled statement for block
Browse files Browse the repository at this point in the history
  • Loading branch information
Siubaak committed Jan 7, 2025
1 parent d104a64 commit 6f6a961
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
15 changes: 12 additions & 3 deletions src/evaluate/statement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export interface BlockOptions {
export function* BlockStatement(
block: acorn.BlockStatement | acorn.StaticBlock,
scope: Scope,
options: BlockOptions = {},
options: BlockOptions & LabelOptions = {},
) {
const {
invasived = false,
Expand All @@ -36,7 +36,13 @@ export function* BlockStatement(

for (let i = 0; i < block.body.length; i++) {
const result = yield* evaluate(block.body[i], subScope)
if (result === BREAK || result === CONTINUE || result === RETURN) {
if (result === BREAK) {
if (options.label && result.LABEL === options.label) {
break
}
return result
}
if (result === CONTINUE || result === RETURN) {
return result
}
}
Expand Down Expand Up @@ -88,7 +94,10 @@ export function* LabeledStatement(node: acorn.LabeledStatement, scope: Scope) {
if (node.body.type === 'ForOfStatement') {
return yield* ForOfStatement(node.body, scope, { label })
}
throw new SyntaxError(`${node.body.type} cannot be labelled`)
if (node.body.type === 'BlockStatement') {
return yield* BlockStatement(node.body, scope, { label })
}
throw new SyntaxError(`${node.body.type} cannot be labeled`)
}

export function* IfStatement(node: acorn.IfStatement, scope: Scope) {
Expand Down
16 changes: 15 additions & 1 deletion tests/statement.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ describe('testing src/index.ts', () => {
expect(interpreter.exports.d).toBeTruthy()
})

it('should labeled statement run normally', () => {
it('should labeled loop statement and continue/break run normally', () => {
const interpreter = new Sval({ ecmaVer: 10 })
interpreter.run(`
let x = 0
Expand All @@ -299,4 +299,18 @@ describe('testing src/index.ts', () => {
`)
expect(interpreter.exports.a).toBe(3)
})

it('should labeled statement and break run normally', () => {
const interpreter = new Sval({ ecmaVer: 10 })
interpreter.run(`
let x = 0
a: {
x++
break a
x++
}
exports.a = x
`)
expect(interpreter.exports.a).toBe(1)
})
})

0 comments on commit 6f6a961

Please sign in to comment.