Skip to content

Commit

Permalink
[feat] support class static block
Browse files Browse the repository at this point in the history
  • Loading branch information
Siubaak committed Jan 30, 2024
1 parent 941b303 commit dacb773
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 5 deletions.
8 changes: 7 additions & 1 deletion src/evaluate/declaration.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { NOINIT, DEADZONE, PRIVATE } from '../share/const'
import { pattern, createFunc, createClass } from './helper'
import { define, getDptor, assign } from '../share/util'
import { BlockStatement } from './statement'
import { VarKind } from '../scope/variable'
import * as acorn from 'acorn'
import Scope from '../scope'
Expand Down Expand Up @@ -199,5 +200,10 @@ export function* PropertyDefinition(node: acorn.PropertyDefinition, scope: Scope
}

export function* StaticBlock(node: acorn.StaticBlock, scope: Scope, options: ClassOptions = {}) {
// TODO
const { klass } = options

const subScope: Scope = new Scope(scope, true)
subScope.const('this', klass)

return yield* BlockStatement(node, subScope, { invasived: true })
}
2 changes: 1 addition & 1 deletion src/evaluate/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export interface hoistOptions {
}

export function* hoist(
block: acorn.Program | acorn.BlockStatement,
block: acorn.Program | acorn.BlockStatement | acorn.StaticBlock,
scope: Scope,
options: hoistOptions = {}
) {
Expand Down
2 changes: 1 addition & 1 deletion src/evaluate/statement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export interface BlockOptions {
}

export function* BlockStatement(
block: acorn.BlockStatement,
block: acorn.BlockStatement | acorn.StaticBlock,
scope: Scope,
options: BlockOptions = {},
) {
Expand Down
31 changes: 29 additions & 2 deletions tests/class.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -547,15 +547,42 @@ describe('testing src/index.ts', () => {
expect(this.c).toBe(3)
expect(this.#d()).toBe(4)
expect(this.e).toBe(5)
expect(A.f).toBe(6)
expect(A.#g).toBe(7)
expect(A.h()).toBe(8)
}
static f = 6
static #g = this.f + 1
static h = () => this.#g + 1
}
expect(A.f).toBe(6)
expect(A.h()).toBe(8)
new A()
`)
})

it('should support class static block', () => {
const interpreter = new Sval()
interpreter.import('expect', expect)
interpreter.run(`
class A {
static l = []
static {
this.l.push(1)
}
static {
this.l.push(2)
}
}
class B extends A {
static l = []
static {
expect(A.l).toEqual([1, 2])
this.l.push(3)
}
static {
this.l.push(4)
}
}
expect(B.l).toEqual([3, 4])
`)
})
})

0 comments on commit dacb773

Please sign in to comment.