compiler.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  1. package goja
  2. import (
  3. "fmt"
  4. "github.com/dop251/goja/token"
  5. "sort"
  6. "github.com/dop251/goja/ast"
  7. "github.com/dop251/goja/file"
  8. "github.com/dop251/goja/unistring"
  9. )
  10. type blockType int
  11. const (
  12. blockLoop blockType = iota
  13. blockLoopEnum
  14. blockTry
  15. blockLabel
  16. blockSwitch
  17. blockWith
  18. blockScope
  19. blockIterScope
  20. blockOptChain
  21. )
  22. const (
  23. maskConst = 1 << 31
  24. maskVar = 1 << 30
  25. maskDeletable = 1 << 29
  26. maskStrict = maskDeletable
  27. maskTyp = maskConst | maskVar | maskDeletable
  28. )
  29. type varType byte
  30. const (
  31. varTypeVar varType = iota
  32. varTypeLet
  33. varTypeStrictConst
  34. varTypeConst
  35. )
  36. const thisBindingName = " this" // must not be a valid identifier
  37. type CompilerError struct {
  38. Message string
  39. File *file.File
  40. Offset int
  41. }
  42. type CompilerSyntaxError struct {
  43. CompilerError
  44. }
  45. type CompilerReferenceError struct {
  46. CompilerError
  47. }
  48. type srcMapItem struct {
  49. pc int
  50. srcPos int
  51. }
  52. type Program struct {
  53. code []instruction
  54. values []Value
  55. funcName unistring.String
  56. src *file.File
  57. srcMap []srcMapItem
  58. }
  59. type compiler struct {
  60. p *Program
  61. scope *scope
  62. block *block
  63. classScope *classScope
  64. enumGetExpr compiledEnumGetExpr
  65. evalVM *vm // VM used to evaluate constant expressions
  66. ctxVM *vm // VM in which an eval() code is compiled
  67. codeScratchpad []instruction
  68. }
  69. type binding struct {
  70. scope *scope
  71. name unistring.String
  72. accessPoints map[*scope]*[]int
  73. isConst bool
  74. isStrict bool
  75. isArg bool
  76. isVar bool
  77. inStash bool
  78. }
  79. func (b *binding) getAccessPointsForScope(s *scope) *[]int {
  80. m := b.accessPoints[s]
  81. if m == nil {
  82. a := make([]int, 0, 1)
  83. m = &a
  84. if b.accessPoints == nil {
  85. b.accessPoints = make(map[*scope]*[]int)
  86. }
  87. b.accessPoints[s] = m
  88. }
  89. return m
  90. }
  91. func (b *binding) markAccessPointAt(pos int) {
  92. scope := b.scope.c.scope
  93. m := b.getAccessPointsForScope(scope)
  94. *m = append(*m, pos-scope.base)
  95. }
  96. func (b *binding) markAccessPointAtScope(scope *scope, pos int) {
  97. m := b.getAccessPointsForScope(scope)
  98. *m = append(*m, pos-scope.base)
  99. }
  100. func (b *binding) markAccessPoint() {
  101. scope := b.scope.c.scope
  102. m := b.getAccessPointsForScope(scope)
  103. *m = append(*m, len(scope.prg.code)-scope.base)
  104. }
  105. func (b *binding) emitGet() {
  106. b.markAccessPoint()
  107. if b.isVar && !b.isArg {
  108. b.scope.c.emit(loadStack(0))
  109. } else {
  110. b.scope.c.emit(loadStackLex(0))
  111. }
  112. }
  113. func (b *binding) emitGetAt(pos int) {
  114. b.markAccessPointAt(pos)
  115. if b.isVar && !b.isArg {
  116. b.scope.c.p.code[pos] = loadStack(0)
  117. } else {
  118. b.scope.c.p.code[pos] = loadStackLex(0)
  119. }
  120. }
  121. func (b *binding) emitGetP() {
  122. if b.isVar && !b.isArg {
  123. // no-op
  124. } else {
  125. // make sure TDZ is checked
  126. b.markAccessPoint()
  127. b.scope.c.emit(loadStackLex(0), pop)
  128. }
  129. }
  130. func (b *binding) emitSet() {
  131. if b.isConst {
  132. if b.isStrict || b.scope.c.scope.strict {
  133. b.scope.c.emit(throwAssignToConst)
  134. }
  135. return
  136. }
  137. b.markAccessPoint()
  138. if b.isVar && !b.isArg {
  139. b.scope.c.emit(storeStack(0))
  140. } else {
  141. b.scope.c.emit(storeStackLex(0))
  142. }
  143. }
  144. func (b *binding) emitSetP() {
  145. if b.isConst {
  146. if b.isStrict || b.scope.c.scope.strict {
  147. b.scope.c.emit(throwAssignToConst)
  148. }
  149. return
  150. }
  151. b.markAccessPoint()
  152. if b.isVar && !b.isArg {
  153. b.scope.c.emit(storeStackP(0))
  154. } else {
  155. b.scope.c.emit(storeStackLexP(0))
  156. }
  157. }
  158. func (b *binding) emitInitP() {
  159. if !b.isVar && b.scope.outer == nil {
  160. b.scope.c.emit(initGlobalP(b.name))
  161. } else {
  162. b.markAccessPoint()
  163. b.scope.c.emit(initStackP(0))
  164. }
  165. }
  166. func (b *binding) emitInit() {
  167. if !b.isVar && b.scope.outer == nil {
  168. b.scope.c.emit(initGlobal(b.name))
  169. } else {
  170. b.markAccessPoint()
  171. b.scope.c.emit(initStack(0))
  172. }
  173. }
  174. func (b *binding) emitInitAt(pos int) {
  175. if !b.isVar && b.scope.outer == nil {
  176. b.scope.c.p.code[pos] = initGlobal(b.name)
  177. } else {
  178. b.markAccessPointAt(pos)
  179. b.scope.c.p.code[pos] = initStack(0)
  180. }
  181. }
  182. func (b *binding) emitInitAtScope(scope *scope, pos int) {
  183. if !b.isVar && scope.outer == nil {
  184. scope.c.p.code[pos] = initGlobal(b.name)
  185. } else {
  186. b.markAccessPointAtScope(scope, pos)
  187. scope.c.p.code[pos] = initStack(0)
  188. }
  189. }
  190. func (b *binding) emitInitPAtScope(scope *scope, pos int) {
  191. if !b.isVar && scope.outer == nil {
  192. scope.c.p.code[pos] = initGlobalP(b.name)
  193. } else {
  194. b.markAccessPointAtScope(scope, pos)
  195. scope.c.p.code[pos] = initStackP(0)
  196. }
  197. }
  198. func (b *binding) emitGetVar(callee bool) {
  199. b.markAccessPoint()
  200. if b.isVar && !b.isArg {
  201. b.scope.c.emit(&loadMixed{name: b.name, callee: callee})
  202. } else {
  203. b.scope.c.emit(&loadMixedLex{name: b.name, callee: callee})
  204. }
  205. }
  206. func (b *binding) emitResolveVar(strict bool) {
  207. b.markAccessPoint()
  208. if b.isVar && !b.isArg {
  209. b.scope.c.emit(&resolveMixed{name: b.name, strict: strict, typ: varTypeVar})
  210. } else {
  211. var typ varType
  212. if b.isConst {
  213. if b.isStrict {
  214. typ = varTypeStrictConst
  215. } else {
  216. typ = varTypeConst
  217. }
  218. } else {
  219. typ = varTypeLet
  220. }
  221. b.scope.c.emit(&resolveMixed{name: b.name, strict: strict, typ: typ})
  222. }
  223. }
  224. func (b *binding) moveToStash() {
  225. if b.isArg && !b.scope.argsInStash {
  226. b.scope.moveArgsToStash()
  227. } else {
  228. b.inStash = true
  229. b.scope.needStash = true
  230. }
  231. }
  232. func (b *binding) useCount() (count int) {
  233. for _, a := range b.accessPoints {
  234. count += len(*a)
  235. }
  236. return
  237. }
  238. type scope struct {
  239. c *compiler
  240. prg *Program
  241. outer *scope
  242. nested []*scope
  243. boundNames map[unistring.String]*binding
  244. bindings []*binding
  245. base int
  246. numArgs int
  247. // function type. If not funcNone, this is a function or a top-level lexical environment
  248. funcType funcType
  249. // in strict mode
  250. strict bool
  251. // eval top-level scope
  252. eval bool
  253. // at least one inner scope has direct eval() which can lookup names dynamically (by name)
  254. dynLookup bool
  255. // at least one binding has been marked for placement in stash
  256. needStash bool
  257. // is a variable environment, i.e. the target for dynamically created var bindings
  258. variable bool
  259. // a function scope that has at least one direct eval() and non-strict, so the variables can be added dynamically
  260. dynamic bool
  261. // arguments have been marked for placement in stash (functions only)
  262. argsInStash bool
  263. // need 'arguments' object (functions only)
  264. argsNeeded bool
  265. }
  266. type block struct {
  267. typ blockType
  268. label unistring.String
  269. cont int
  270. breaks []int
  271. conts []int
  272. outer *block
  273. breaking *block // set when the 'finally' block is an empty break statement sequence
  274. needResult bool
  275. }
  276. func (c *compiler) leaveScopeBlock(enter *enterBlock) {
  277. c.updateEnterBlock(enter)
  278. leave := &leaveBlock{
  279. stackSize: enter.stackSize,
  280. popStash: enter.stashSize > 0,
  281. }
  282. c.emit(leave)
  283. for _, pc := range c.block.breaks {
  284. c.p.code[pc] = leave
  285. }
  286. c.block.breaks = nil
  287. c.leaveBlock()
  288. }
  289. func (c *compiler) leaveBlock() {
  290. lbl := len(c.p.code)
  291. for _, item := range c.block.breaks {
  292. c.p.code[item] = jump(lbl - item)
  293. }
  294. if t := c.block.typ; t == blockLoop || t == blockLoopEnum {
  295. for _, item := range c.block.conts {
  296. c.p.code[item] = jump(c.block.cont - item)
  297. }
  298. }
  299. c.block = c.block.outer
  300. }
  301. func (e *CompilerSyntaxError) Error() string {
  302. if e.File != nil {
  303. return fmt.Sprintf("SyntaxError: %s at %s", e.Message, e.File.Position(e.Offset))
  304. }
  305. return fmt.Sprintf("SyntaxError: %s", e.Message)
  306. }
  307. func (e *CompilerReferenceError) Error() string {
  308. return fmt.Sprintf("ReferenceError: %s", e.Message)
  309. }
  310. func (c *compiler) newScope() {
  311. strict := false
  312. if c.scope != nil {
  313. strict = c.scope.strict
  314. }
  315. c.scope = &scope{
  316. c: c,
  317. prg: c.p,
  318. outer: c.scope,
  319. strict: strict,
  320. }
  321. }
  322. func (c *compiler) newBlockScope() {
  323. c.newScope()
  324. if outer := c.scope.outer; outer != nil {
  325. outer.nested = append(outer.nested, c.scope)
  326. }
  327. c.scope.base = len(c.p.code)
  328. }
  329. func (c *compiler) popScope() {
  330. c.scope = c.scope.outer
  331. }
  332. func newCompiler() *compiler {
  333. c := &compiler{
  334. p: &Program{},
  335. }
  336. c.enumGetExpr.init(c, file.Idx(0))
  337. return c
  338. }
  339. func (p *Program) defineLiteralValue(val Value) uint32 {
  340. for idx, v := range p.values {
  341. if v.SameAs(val) {
  342. return uint32(idx)
  343. }
  344. }
  345. idx := uint32(len(p.values))
  346. p.values = append(p.values, val)
  347. return idx
  348. }
  349. func (p *Program) dumpCode(logger func(format string, args ...interface{})) {
  350. p._dumpCode("", logger)
  351. }
  352. func (p *Program) _dumpCode(indent string, logger func(format string, args ...interface{})) {
  353. logger("values: %+v", p.values)
  354. dumpInitFields := func(initFields *Program) {
  355. i := indent + ">"
  356. logger("%s ---- init_fields:", i)
  357. initFields._dumpCode(i, logger)
  358. logger("%s ----", i)
  359. }
  360. for pc, ins := range p.code {
  361. logger("%s %d: %T(%v)", indent, pc, ins, ins)
  362. var prg *Program
  363. switch f := ins.(type) {
  364. case *newFunc:
  365. prg = f.prg
  366. case *newAsyncFunc:
  367. prg = f.prg
  368. case *newArrowFunc:
  369. prg = f.prg
  370. case *newAsyncArrowFunc:
  371. prg = f.prg
  372. case *newMethod:
  373. prg = f.prg
  374. case *newAsyncMethod:
  375. prg = f.prg
  376. case *newDerivedClass:
  377. if f.initFields != nil {
  378. dumpInitFields(f.initFields)
  379. }
  380. prg = f.ctor
  381. case *newClass:
  382. if f.initFields != nil {
  383. dumpInitFields(f.initFields)
  384. }
  385. prg = f.ctor
  386. case *newStaticFieldInit:
  387. if f.initFields != nil {
  388. dumpInitFields(f.initFields)
  389. }
  390. }
  391. if prg != nil {
  392. prg._dumpCode(indent+">", logger)
  393. }
  394. }
  395. }
  396. func (p *Program) sourceOffset(pc int) int {
  397. i := sort.Search(len(p.srcMap), func(idx int) bool {
  398. return p.srcMap[idx].pc > pc
  399. }) - 1
  400. if i >= 0 {
  401. return p.srcMap[i].srcPos
  402. }
  403. return 0
  404. }
  405. func (p *Program) addSrcMap(srcPos int) {
  406. if len(p.srcMap) > 0 && p.srcMap[len(p.srcMap)-1].srcPos == srcPos {
  407. return
  408. }
  409. p.srcMap = append(p.srcMap, srcMapItem{pc: len(p.code), srcPos: srcPos})
  410. }
  411. func (s *scope) lookupName(name unistring.String) (binding *binding, noDynamics bool) {
  412. noDynamics = true
  413. toStash := false
  414. for curScope := s; ; curScope = curScope.outer {
  415. if curScope.outer != nil {
  416. if b, exists := curScope.boundNames[name]; exists {
  417. if toStash && !b.inStash {
  418. b.moveToStash()
  419. }
  420. binding = b
  421. return
  422. }
  423. } else {
  424. noDynamics = false
  425. return
  426. }
  427. if curScope.dynamic {
  428. noDynamics = false
  429. }
  430. if name == "arguments" && curScope.funcType != funcNone && curScope.funcType != funcArrow {
  431. if curScope.funcType == funcClsInit {
  432. s.c.throwSyntaxError(0, "'arguments' is not allowed in class field initializer or static initialization block")
  433. }
  434. curScope.argsNeeded = true
  435. binding, _ = curScope.bindName(name)
  436. return
  437. }
  438. if curScope.isFunction() {
  439. toStash = true
  440. }
  441. }
  442. }
  443. func (s *scope) lookupThis() (*binding, bool) {
  444. toStash := false
  445. for curScope := s; curScope != nil; curScope = curScope.outer {
  446. if curScope.outer == nil {
  447. if curScope.eval {
  448. return nil, true
  449. }
  450. }
  451. if b, exists := curScope.boundNames[thisBindingName]; exists {
  452. if toStash && !b.inStash {
  453. b.moveToStash()
  454. }
  455. return b, false
  456. }
  457. if curScope.isFunction() {
  458. toStash = true
  459. }
  460. }
  461. return nil, false
  462. }
  463. func (s *scope) ensureBoundNamesCreated() {
  464. if s.boundNames == nil {
  465. s.boundNames = make(map[unistring.String]*binding)
  466. }
  467. }
  468. func (s *scope) addBinding(offset int) *binding {
  469. if len(s.bindings) >= (1<<24)-1 {
  470. s.c.throwSyntaxError(offset, "Too many variables")
  471. }
  472. b := &binding{
  473. scope: s,
  474. }
  475. s.bindings = append(s.bindings, b)
  476. return b
  477. }
  478. func (s *scope) bindNameLexical(name unistring.String, unique bool, offset int) (*binding, bool) {
  479. if b := s.boundNames[name]; b != nil {
  480. if unique {
  481. s.c.throwSyntaxError(offset, "Identifier '%s' has already been declared", name)
  482. }
  483. return b, false
  484. }
  485. b := s.addBinding(offset)
  486. b.name = name
  487. s.ensureBoundNamesCreated()
  488. s.boundNames[name] = b
  489. return b, true
  490. }
  491. func (s *scope) createThisBinding() *binding {
  492. thisBinding, _ := s.bindNameLexical(thisBindingName, false, 0)
  493. thisBinding.isVar = true // don't check on load
  494. return thisBinding
  495. }
  496. func (s *scope) bindName(name unistring.String) (*binding, bool) {
  497. if !s.isFunction() && !s.variable && s.outer != nil {
  498. return s.outer.bindName(name)
  499. }
  500. b, created := s.bindNameLexical(name, false, 0)
  501. if created {
  502. b.isVar = true
  503. }
  504. return b, created
  505. }
  506. func (s *scope) bindNameShadow(name unistring.String) (*binding, bool) {
  507. if !s.isFunction() && s.outer != nil {
  508. return s.outer.bindNameShadow(name)
  509. }
  510. _, exists := s.boundNames[name]
  511. b := &binding{
  512. scope: s,
  513. name: name,
  514. }
  515. s.bindings = append(s.bindings, b)
  516. s.ensureBoundNamesCreated()
  517. s.boundNames[name] = b
  518. return b, !exists
  519. }
  520. func (s *scope) nearestFunction() *scope {
  521. for sc := s; sc != nil; sc = sc.outer {
  522. if sc.isFunction() {
  523. return sc
  524. }
  525. }
  526. return nil
  527. }
  528. func (s *scope) nearestThis() *scope {
  529. for sc := s; sc != nil; sc = sc.outer {
  530. if sc.eval || sc.isFunction() && sc.funcType != funcArrow {
  531. return sc
  532. }
  533. }
  534. return nil
  535. }
  536. func (s *scope) finaliseVarAlloc(stackOffset int) (stashSize, stackSize int) {
  537. argsInStash := false
  538. if f := s.nearestFunction(); f != nil {
  539. argsInStash = f.argsInStash
  540. }
  541. stackIdx, stashIdx := 0, 0
  542. allInStash := s.isDynamic()
  543. var derivedCtor bool
  544. if fs := s.nearestThis(); fs != nil && fs.funcType == funcDerivedCtor {
  545. derivedCtor = true
  546. }
  547. for i, b := range s.bindings {
  548. var this bool
  549. if b.name == thisBindingName {
  550. this = true
  551. }
  552. if allInStash || b.inStash {
  553. for scope, aps := range b.accessPoints {
  554. var level uint32
  555. for sc := scope; sc != nil && sc != s; sc = sc.outer {
  556. if sc.needStash || sc.isDynamic() {
  557. level++
  558. }
  559. }
  560. if level > 255 {
  561. s.c.throwSyntaxError(0, "Maximum nesting level (256) exceeded")
  562. }
  563. idx := (level << 24) | uint32(stashIdx)
  564. base := scope.base
  565. code := scope.prg.code
  566. if this {
  567. if derivedCtor {
  568. for _, pc := range *aps {
  569. ap := &code[base+pc]
  570. switch (*ap).(type) {
  571. case loadStack:
  572. *ap = loadThisStash(idx)
  573. case initStack:
  574. *ap = initStash(idx)
  575. case resolveThisStack:
  576. *ap = resolveThisStash(idx)
  577. case _ret:
  578. *ap = cret(idx)
  579. default:
  580. s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for 'this'")
  581. }
  582. }
  583. } else {
  584. for _, pc := range *aps {
  585. ap := &code[base+pc]
  586. switch (*ap).(type) {
  587. case loadStack:
  588. *ap = loadStash(idx)
  589. case initStack:
  590. *ap = initStash(idx)
  591. default:
  592. s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for 'this'")
  593. }
  594. }
  595. }
  596. } else {
  597. for _, pc := range *aps {
  598. ap := &code[base+pc]
  599. switch i := (*ap).(type) {
  600. case loadStack:
  601. *ap = loadStash(idx)
  602. case storeStack:
  603. *ap = storeStash(idx)
  604. case storeStackP:
  605. *ap = storeStashP(idx)
  606. case loadStackLex:
  607. *ap = loadStashLex(idx)
  608. case storeStackLex:
  609. *ap = storeStashLex(idx)
  610. case storeStackLexP:
  611. *ap = storeStashLexP(idx)
  612. case initStackP:
  613. *ap = initStashP(idx)
  614. case initStack:
  615. *ap = initStash(idx)
  616. case *loadMixed:
  617. i.idx = idx
  618. case *loadMixedLex:
  619. i.idx = idx
  620. case *resolveMixed:
  621. i.idx = idx
  622. default:
  623. s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for binding: %T", i)
  624. }
  625. }
  626. }
  627. }
  628. stashIdx++
  629. } else {
  630. var idx int
  631. if !this {
  632. if i < s.numArgs {
  633. idx = -(i + 1)
  634. } else {
  635. stackIdx++
  636. idx = stackIdx + stackOffset
  637. }
  638. }
  639. for scope, aps := range b.accessPoints {
  640. var level int
  641. for sc := scope; sc != nil && sc != s; sc = sc.outer {
  642. if sc.needStash || sc.isDynamic() {
  643. level++
  644. }
  645. }
  646. if level > 255 {
  647. s.c.throwSyntaxError(0, "Maximum nesting level (256) exceeded")
  648. }
  649. code := scope.prg.code
  650. base := scope.base
  651. if this {
  652. if derivedCtor {
  653. for _, pc := range *aps {
  654. ap := &code[base+pc]
  655. switch (*ap).(type) {
  656. case loadStack:
  657. *ap = loadThisStack{}
  658. case initStack:
  659. // no-op
  660. case resolveThisStack:
  661. // no-op
  662. case _ret:
  663. // no-op, already in the right place
  664. default:
  665. s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for 'this'")
  666. }
  667. }
  668. } /*else {
  669. no-op
  670. }*/
  671. } else if argsInStash {
  672. for _, pc := range *aps {
  673. ap := &code[base+pc]
  674. switch i := (*ap).(type) {
  675. case loadStack:
  676. *ap = loadStack1(idx)
  677. case storeStack:
  678. *ap = storeStack1(idx)
  679. case storeStackP:
  680. *ap = storeStack1P(idx)
  681. case loadStackLex:
  682. *ap = loadStack1Lex(idx)
  683. case storeStackLex:
  684. *ap = storeStack1Lex(idx)
  685. case storeStackLexP:
  686. *ap = storeStack1LexP(idx)
  687. case initStackP:
  688. *ap = initStack1P(idx)
  689. case initStack:
  690. *ap = initStack1(idx)
  691. case *loadMixed:
  692. *ap = &loadMixedStack1{name: i.name, idx: idx, level: uint8(level), callee: i.callee}
  693. case *loadMixedLex:
  694. *ap = &loadMixedStack1Lex{name: i.name, idx: idx, level: uint8(level), callee: i.callee}
  695. case *resolveMixed:
  696. *ap = &resolveMixedStack1{typ: i.typ, name: i.name, idx: idx, level: uint8(level), strict: i.strict}
  697. default:
  698. s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for binding: %T", i)
  699. }
  700. }
  701. } else {
  702. for _, pc := range *aps {
  703. ap := &code[base+pc]
  704. switch i := (*ap).(type) {
  705. case loadStack:
  706. *ap = loadStack(idx)
  707. case storeStack:
  708. *ap = storeStack(idx)
  709. case storeStackP:
  710. *ap = storeStackP(idx)
  711. case loadStackLex:
  712. *ap = loadStackLex(idx)
  713. case storeStackLex:
  714. *ap = storeStackLex(idx)
  715. case storeStackLexP:
  716. *ap = storeStackLexP(idx)
  717. case initStack:
  718. *ap = initStack(idx)
  719. case initStackP:
  720. *ap = initStackP(idx)
  721. case *loadMixed:
  722. *ap = &loadMixedStack{name: i.name, idx: idx, level: uint8(level), callee: i.callee}
  723. case *loadMixedLex:
  724. *ap = &loadMixedStackLex{name: i.name, idx: idx, level: uint8(level), callee: i.callee}
  725. case *resolveMixed:
  726. *ap = &resolveMixedStack{typ: i.typ, name: i.name, idx: idx, level: uint8(level), strict: i.strict}
  727. default:
  728. s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for binding: %T", i)
  729. }
  730. }
  731. }
  732. }
  733. }
  734. }
  735. for _, nested := range s.nested {
  736. nested.finaliseVarAlloc(stackIdx + stackOffset)
  737. }
  738. return stashIdx, stackIdx
  739. }
  740. func (s *scope) moveArgsToStash() {
  741. for _, b := range s.bindings {
  742. if !b.isArg {
  743. break
  744. }
  745. b.inStash = true
  746. }
  747. s.argsInStash = true
  748. s.needStash = true
  749. }
  750. func (c *compiler) trimCode(delta int) {
  751. src := c.p.code[delta:]
  752. newCode := make([]instruction, len(src))
  753. copy(newCode, src)
  754. if cap(c.codeScratchpad) < cap(c.p.code) {
  755. c.codeScratchpad = c.p.code[:0]
  756. }
  757. c.p.code = newCode
  758. }
  759. func (s *scope) trimCode(delta int) {
  760. s.c.trimCode(delta)
  761. if delta != 0 {
  762. srcMap := s.c.p.srcMap
  763. for i := range srcMap {
  764. srcMap[i].pc -= delta
  765. }
  766. s.adjustBase(-delta)
  767. }
  768. }
  769. func (s *scope) adjustBase(delta int) {
  770. s.base += delta
  771. for _, nested := range s.nested {
  772. nested.adjustBase(delta)
  773. }
  774. }
  775. func (s *scope) makeNamesMap() map[unistring.String]uint32 {
  776. l := len(s.bindings)
  777. if l == 0 {
  778. return nil
  779. }
  780. names := make(map[unistring.String]uint32, l)
  781. for i, b := range s.bindings {
  782. idx := uint32(i)
  783. if b.isConst {
  784. idx |= maskConst
  785. if b.isStrict {
  786. idx |= maskStrict
  787. }
  788. }
  789. if b.isVar {
  790. idx |= maskVar
  791. }
  792. names[b.name] = idx
  793. }
  794. return names
  795. }
  796. func (s *scope) isDynamic() bool {
  797. return s.dynLookup || s.dynamic
  798. }
  799. func (s *scope) isFunction() bool {
  800. return s.funcType != funcNone && !s.eval
  801. }
  802. func (s *scope) deleteBinding(b *binding) {
  803. idx := 0
  804. for i, bb := range s.bindings {
  805. if bb == b {
  806. idx = i
  807. goto found
  808. }
  809. }
  810. return
  811. found:
  812. delete(s.boundNames, b.name)
  813. copy(s.bindings[idx:], s.bindings[idx+1:])
  814. l := len(s.bindings) - 1
  815. s.bindings[l] = nil
  816. s.bindings = s.bindings[:l]
  817. }
  818. func (c *compiler) compile(in *ast.Program, strict, inGlobal bool, evalVm *vm) {
  819. c.ctxVM = evalVm
  820. eval := evalVm != nil
  821. c.p.src = in.File
  822. c.newScope()
  823. scope := c.scope
  824. scope.dynamic = true
  825. scope.eval = eval
  826. if !strict && len(in.Body) > 0 {
  827. strict = c.isStrict(in.Body) != nil
  828. }
  829. scope.strict = strict
  830. ownVarScope := eval && strict
  831. ownLexScope := !inGlobal || eval
  832. if ownVarScope {
  833. c.newBlockScope()
  834. scope = c.scope
  835. scope.variable = true
  836. }
  837. if eval && !inGlobal {
  838. for s := evalVm.stash; s != nil; s = s.outer {
  839. if ft := s.funcType; ft != funcNone && ft != funcArrow {
  840. scope.funcType = ft
  841. break
  842. }
  843. }
  844. }
  845. funcs := c.extractFunctions(in.Body)
  846. c.createFunctionBindings(funcs)
  847. numFuncs := len(scope.bindings)
  848. if inGlobal && !ownVarScope {
  849. if numFuncs == len(funcs) {
  850. c.compileFunctionsGlobalAllUnique(funcs)
  851. } else {
  852. c.compileFunctionsGlobal(funcs)
  853. }
  854. }
  855. c.compileDeclList(in.DeclarationList, false)
  856. numVars := len(scope.bindings) - numFuncs
  857. vars := make([]unistring.String, len(scope.bindings))
  858. for i, b := range scope.bindings {
  859. vars[i] = b.name
  860. }
  861. if len(vars) > 0 && !ownVarScope && ownLexScope {
  862. if inGlobal {
  863. c.emit(&bindGlobal{
  864. vars: vars[numFuncs:],
  865. funcs: vars[:numFuncs],
  866. deletable: eval,
  867. })
  868. } else {
  869. c.emit(&bindVars{names: vars, deletable: eval})
  870. }
  871. }
  872. var enter *enterBlock
  873. if c.compileLexicalDeclarations(in.Body, ownVarScope || !ownLexScope) {
  874. if ownLexScope {
  875. c.block = &block{
  876. outer: c.block,
  877. typ: blockScope,
  878. needResult: true,
  879. }
  880. enter = &enterBlock{}
  881. c.emit(enter)
  882. }
  883. }
  884. if len(scope.bindings) > 0 && !ownLexScope {
  885. var lets, consts []unistring.String
  886. for _, b := range c.scope.bindings[numFuncs+numVars:] {
  887. if b.isConst {
  888. consts = append(consts, b.name)
  889. } else {
  890. lets = append(lets, b.name)
  891. }
  892. }
  893. c.emit(&bindGlobal{
  894. vars: vars[numFuncs:],
  895. funcs: vars[:numFuncs],
  896. lets: lets,
  897. consts: consts,
  898. })
  899. }
  900. if !inGlobal || ownVarScope {
  901. c.compileFunctions(funcs)
  902. }
  903. c.compileStatements(in.Body, true)
  904. if enter != nil {
  905. c.leaveScopeBlock(enter)
  906. c.popScope()
  907. }
  908. scope.finaliseVarAlloc(0)
  909. }
  910. func (c *compiler) compileDeclList(v []*ast.VariableDeclaration, inFunc bool) {
  911. for _, value := range v {
  912. c.createVarBindings(value, inFunc)
  913. }
  914. }
  915. func (c *compiler) extractLabelled(st ast.Statement) ast.Statement {
  916. if st, ok := st.(*ast.LabelledStatement); ok {
  917. return c.extractLabelled(st.Statement)
  918. }
  919. return st
  920. }
  921. func (c *compiler) extractFunctions(list []ast.Statement) (funcs []*ast.FunctionDeclaration) {
  922. for _, st := range list {
  923. var decl *ast.FunctionDeclaration
  924. switch st := c.extractLabelled(st).(type) {
  925. case *ast.FunctionDeclaration:
  926. decl = st
  927. case *ast.LabelledStatement:
  928. if st1, ok := st.Statement.(*ast.FunctionDeclaration); ok {
  929. decl = st1
  930. } else {
  931. continue
  932. }
  933. default:
  934. continue
  935. }
  936. funcs = append(funcs, decl)
  937. }
  938. return
  939. }
  940. func (c *compiler) createFunctionBindings(funcs []*ast.FunctionDeclaration) {
  941. s := c.scope
  942. if s.outer != nil {
  943. unique := !s.isFunction() && !s.variable && s.strict
  944. if !unique {
  945. hasNonStandard := false
  946. for _, decl := range funcs {
  947. if !decl.Function.Async {
  948. s.bindNameLexical(decl.Function.Name.Name, false, int(decl.Function.Name.Idx1())-1)
  949. } else {
  950. hasNonStandard = true
  951. }
  952. }
  953. if hasNonStandard {
  954. for _, decl := range funcs {
  955. if decl.Function.Async {
  956. s.bindNameLexical(decl.Function.Name.Name, true, int(decl.Function.Name.Idx1())-1)
  957. }
  958. }
  959. }
  960. } else {
  961. for _, decl := range funcs {
  962. s.bindNameLexical(decl.Function.Name.Name, true, int(decl.Function.Name.Idx1())-1)
  963. }
  964. }
  965. } else {
  966. for _, decl := range funcs {
  967. s.bindName(decl.Function.Name.Name)
  968. }
  969. }
  970. }
  971. func (c *compiler) compileFunctions(list []*ast.FunctionDeclaration) {
  972. for _, decl := range list {
  973. c.compileFunction(decl)
  974. }
  975. }
  976. func (c *compiler) compileFunctionsGlobalAllUnique(list []*ast.FunctionDeclaration) {
  977. for _, decl := range list {
  978. c.compileFunctionLiteral(decl.Function, false).emitGetter(true)
  979. }
  980. }
  981. func (c *compiler) compileFunctionsGlobal(list []*ast.FunctionDeclaration) {
  982. m := make(map[unistring.String]int, len(list))
  983. for i := len(list) - 1; i >= 0; i-- {
  984. name := list[i].Function.Name.Name
  985. if _, exists := m[name]; !exists {
  986. m[name] = i
  987. }
  988. }
  989. idx := 0
  990. for i, decl := range list {
  991. name := decl.Function.Name.Name
  992. if m[name] == i {
  993. c.compileFunctionLiteral(decl.Function, false).emitGetter(true)
  994. c.scope.bindings[idx] = c.scope.boundNames[name]
  995. idx++
  996. } else {
  997. leave := c.enterDummyMode()
  998. c.compileFunctionLiteral(decl.Function, false).emitGetter(false)
  999. leave()
  1000. }
  1001. }
  1002. }
  1003. func (c *compiler) createVarIdBinding(name unistring.String, offset int, inFunc bool) {
  1004. if c.scope.strict {
  1005. c.checkIdentifierLName(name, offset)
  1006. c.checkIdentifierName(name, offset)
  1007. }
  1008. if !inFunc || name != "arguments" {
  1009. c.scope.bindName(name)
  1010. }
  1011. }
  1012. func (c *compiler) createBindings(target ast.Expression, createIdBinding func(name unistring.String, offset int)) {
  1013. switch target := target.(type) {
  1014. case *ast.Identifier:
  1015. createIdBinding(target.Name, int(target.Idx)-1)
  1016. case *ast.ObjectPattern:
  1017. for _, prop := range target.Properties {
  1018. switch prop := prop.(type) {
  1019. case *ast.PropertyShort:
  1020. createIdBinding(prop.Name.Name, int(prop.Name.Idx)-1)
  1021. case *ast.PropertyKeyed:
  1022. c.createBindings(prop.Value, createIdBinding)
  1023. default:
  1024. c.throwSyntaxError(int(target.Idx0()-1), "unsupported property type in ObjectPattern: %T", prop)
  1025. }
  1026. }
  1027. if target.Rest != nil {
  1028. c.createBindings(target.Rest, createIdBinding)
  1029. }
  1030. case *ast.ArrayPattern:
  1031. for _, elt := range target.Elements {
  1032. if elt != nil {
  1033. c.createBindings(elt, createIdBinding)
  1034. }
  1035. }
  1036. if target.Rest != nil {
  1037. c.createBindings(target.Rest, createIdBinding)
  1038. }
  1039. case *ast.AssignExpression:
  1040. c.createBindings(target.Left, createIdBinding)
  1041. default:
  1042. c.throwSyntaxError(int(target.Idx0()-1), "unsupported binding target: %T", target)
  1043. }
  1044. }
  1045. func (c *compiler) createVarBinding(target ast.Expression, inFunc bool) {
  1046. c.createBindings(target, func(name unistring.String, offset int) {
  1047. c.createVarIdBinding(name, offset, inFunc)
  1048. })
  1049. }
  1050. func (c *compiler) createVarBindings(v *ast.VariableDeclaration, inFunc bool) {
  1051. for _, item := range v.List {
  1052. c.createVarBinding(item.Target, inFunc)
  1053. }
  1054. }
  1055. func (c *compiler) createLexicalIdBinding(name unistring.String, isConst bool, offset int) *binding {
  1056. if name == "let" {
  1057. c.throwSyntaxError(offset, "let is disallowed as a lexically bound name")
  1058. }
  1059. if c.scope.strict {
  1060. c.checkIdentifierLName(name, offset)
  1061. c.checkIdentifierName(name, offset)
  1062. }
  1063. b, _ := c.scope.bindNameLexical(name, true, offset)
  1064. if isConst {
  1065. b.isConst, b.isStrict = true, true
  1066. }
  1067. return b
  1068. }
  1069. func (c *compiler) createLexicalIdBindingFuncBody(name unistring.String, isConst bool, offset int, calleeBinding *binding) *binding {
  1070. if name == "let" {
  1071. c.throwSyntaxError(offset, "let is disallowed as a lexically bound name")
  1072. }
  1073. if c.scope.strict {
  1074. c.checkIdentifierLName(name, offset)
  1075. c.checkIdentifierName(name, offset)
  1076. }
  1077. paramScope := c.scope.outer
  1078. parentBinding := paramScope.boundNames[name]
  1079. if parentBinding != nil {
  1080. if parentBinding != calleeBinding && (name != "arguments" || !paramScope.argsNeeded) {
  1081. c.throwSyntaxError(offset, "Identifier '%s' has already been declared", name)
  1082. }
  1083. }
  1084. b, _ := c.scope.bindNameLexical(name, true, offset)
  1085. if isConst {
  1086. b.isConst, b.isStrict = true, true
  1087. }
  1088. return b
  1089. }
  1090. func (c *compiler) createLexicalBinding(target ast.Expression, isConst bool) {
  1091. c.createBindings(target, func(name unistring.String, offset int) {
  1092. c.createLexicalIdBinding(name, isConst, offset)
  1093. })
  1094. }
  1095. func (c *compiler) createLexicalBindings(lex *ast.LexicalDeclaration) {
  1096. for _, d := range lex.List {
  1097. c.createLexicalBinding(d.Target, lex.Token == token.CONST)
  1098. }
  1099. }
  1100. func (c *compiler) compileLexicalDeclarations(list []ast.Statement, scopeDeclared bool) bool {
  1101. for _, st := range list {
  1102. if lex, ok := st.(*ast.LexicalDeclaration); ok {
  1103. if !scopeDeclared {
  1104. c.newBlockScope()
  1105. scopeDeclared = true
  1106. }
  1107. c.createLexicalBindings(lex)
  1108. } else if cls, ok := st.(*ast.ClassDeclaration); ok {
  1109. if !scopeDeclared {
  1110. c.newBlockScope()
  1111. scopeDeclared = true
  1112. }
  1113. c.createLexicalIdBinding(cls.Class.Name.Name, false, int(cls.Class.Name.Idx)-1)
  1114. }
  1115. }
  1116. return scopeDeclared
  1117. }
  1118. func (c *compiler) compileLexicalDeclarationsFuncBody(list []ast.Statement, calleeBinding *binding) {
  1119. for _, st := range list {
  1120. if lex, ok := st.(*ast.LexicalDeclaration); ok {
  1121. isConst := lex.Token == token.CONST
  1122. for _, d := range lex.List {
  1123. c.createBindings(d.Target, func(name unistring.String, offset int) {
  1124. c.createLexicalIdBindingFuncBody(name, isConst, offset, calleeBinding)
  1125. })
  1126. }
  1127. }
  1128. }
  1129. }
  1130. func (c *compiler) compileFunction(v *ast.FunctionDeclaration) {
  1131. name := v.Function.Name.Name
  1132. b := c.scope.boundNames[name]
  1133. if b == nil || b.isVar {
  1134. e := &compiledIdentifierExpr{
  1135. name: v.Function.Name.Name,
  1136. }
  1137. e.init(c, v.Function.Idx0())
  1138. e.emitSetter(c.compileFunctionLiteral(v.Function, false), false)
  1139. } else {
  1140. c.compileFunctionLiteral(v.Function, false).emitGetter(true)
  1141. b.emitInitP()
  1142. }
  1143. }
  1144. func (c *compiler) compileStandaloneFunctionDecl(v *ast.FunctionDeclaration) {
  1145. if v.Function.Async {
  1146. c.throwSyntaxError(int(v.Idx0())-1, "Async functions can only be declared at top level or inside a block.")
  1147. }
  1148. if c.scope.strict {
  1149. c.throwSyntaxError(int(v.Idx0())-1, "In strict mode code, functions can only be declared at top level or inside a block.")
  1150. }
  1151. c.throwSyntaxError(int(v.Idx0())-1, "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.")
  1152. }
  1153. func (c *compiler) emit(instructions ...instruction) {
  1154. c.p.code = append(c.p.code, instructions...)
  1155. }
  1156. func (c *compiler) throwSyntaxError(offset int, format string, args ...interface{}) {
  1157. panic(&CompilerSyntaxError{
  1158. CompilerError: CompilerError{
  1159. File: c.p.src,
  1160. Offset: offset,
  1161. Message: fmt.Sprintf(format, args...),
  1162. },
  1163. })
  1164. }
  1165. func (c *compiler) isStrict(list []ast.Statement) *ast.StringLiteral {
  1166. for _, st := range list {
  1167. if st, ok := st.(*ast.ExpressionStatement); ok {
  1168. if e, ok := st.Expression.(*ast.StringLiteral); ok {
  1169. if e.Literal == `"use strict"` || e.Literal == `'use strict'` {
  1170. return e
  1171. }
  1172. } else {
  1173. break
  1174. }
  1175. } else {
  1176. break
  1177. }
  1178. }
  1179. return nil
  1180. }
  1181. func (c *compiler) isStrictStatement(s ast.Statement) *ast.StringLiteral {
  1182. if s, ok := s.(*ast.BlockStatement); ok {
  1183. return c.isStrict(s.List)
  1184. }
  1185. return nil
  1186. }
  1187. func (c *compiler) checkIdentifierName(name unistring.String, offset int) {
  1188. switch name {
  1189. case "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield":
  1190. c.throwSyntaxError(offset, "Unexpected strict mode reserved word")
  1191. }
  1192. }
  1193. func (c *compiler) checkIdentifierLName(name unistring.String, offset int) {
  1194. switch name {
  1195. case "eval", "arguments":
  1196. c.throwSyntaxError(offset, "Assignment to eval or arguments is not allowed in strict mode")
  1197. }
  1198. }
  1199. // Enter a 'dummy' compilation mode. Any code produced after this method is called will be discarded after
  1200. // leaveFunc is called with no additional side effects. This is useful for compiling code inside a
  1201. // constant falsy condition 'if' branch or a loop (i.e 'if (false) { ... } or while (false) { ... }).
  1202. // Such code should not be included in the final compilation result as it's never called, but it must
  1203. // still produce compilation errors if there are any.
  1204. // TODO: make sure variable lookups do not de-optimise parent scopes
  1205. func (c *compiler) enterDummyMode() (leaveFunc func()) {
  1206. savedBlock, savedProgram := c.block, c.p
  1207. if savedBlock != nil {
  1208. c.block = &block{
  1209. typ: savedBlock.typ,
  1210. label: savedBlock.label,
  1211. outer: savedBlock.outer,
  1212. breaking: savedBlock.breaking,
  1213. }
  1214. }
  1215. c.p = &Program{}
  1216. c.newScope()
  1217. return func() {
  1218. c.block, c.p = savedBlock, savedProgram
  1219. c.popScope()
  1220. }
  1221. }
  1222. func (c *compiler) compileStatementDummy(statement ast.Statement) {
  1223. leave := c.enterDummyMode()
  1224. c.compileStatement(statement, false)
  1225. leave()
  1226. }
  1227. func (c *compiler) assert(cond bool, offset int, msg string, args ...interface{}) {
  1228. if !cond {
  1229. c.throwSyntaxError(offset, "Compiler bug: "+msg, args...)
  1230. }
  1231. }
  1232. func privateIdString(desc unistring.String) unistring.String {
  1233. return asciiString("#").concat(stringValueFromRaw(desc)).string()
  1234. }
  1235. type privateName struct {
  1236. idx int
  1237. isStatic bool
  1238. isMethod bool
  1239. hasGetter, hasSetter bool
  1240. }
  1241. type resolvedPrivateName struct {
  1242. name unistring.String
  1243. idx uint32
  1244. level uint8
  1245. isStatic bool
  1246. isMethod bool
  1247. }
  1248. func (r *resolvedPrivateName) string() unistring.String {
  1249. return privateIdString(r.name)
  1250. }
  1251. type privateEnvRegistry struct {
  1252. fields, methods []unistring.String
  1253. }
  1254. type classScope struct {
  1255. c *compiler
  1256. privateNames map[unistring.String]*privateName
  1257. instanceEnv, staticEnv privateEnvRegistry
  1258. outer *classScope
  1259. }
  1260. func (r *privateEnvRegistry) createPrivateMethodId(name unistring.String) int {
  1261. r.methods = append(r.methods, name)
  1262. return len(r.methods) - 1
  1263. }
  1264. func (r *privateEnvRegistry) createPrivateFieldId(name unistring.String) int {
  1265. r.fields = append(r.fields, name)
  1266. return len(r.fields) - 1
  1267. }
  1268. func (s *classScope) declarePrivateId(name unistring.String, kind ast.PropertyKind, isStatic bool, offset int) {
  1269. pn := s.privateNames[name]
  1270. if pn != nil {
  1271. if pn.isStatic == isStatic {
  1272. switch kind {
  1273. case ast.PropertyKindGet:
  1274. if pn.hasSetter && !pn.hasGetter {
  1275. pn.hasGetter = true
  1276. return
  1277. }
  1278. case ast.PropertyKindSet:
  1279. if pn.hasGetter && !pn.hasSetter {
  1280. pn.hasSetter = true
  1281. return
  1282. }
  1283. }
  1284. }
  1285. s.c.throwSyntaxError(offset, "Identifier '#%s' has already been declared", name)
  1286. panic("unreachable")
  1287. }
  1288. var env *privateEnvRegistry
  1289. if isStatic {
  1290. env = &s.staticEnv
  1291. } else {
  1292. env = &s.instanceEnv
  1293. }
  1294. pn = &privateName{
  1295. isStatic: isStatic,
  1296. hasGetter: kind == ast.PropertyKindGet,
  1297. hasSetter: kind == ast.PropertyKindSet,
  1298. }
  1299. if kind != ast.PropertyKindValue {
  1300. pn.idx = env.createPrivateMethodId(name)
  1301. pn.isMethod = true
  1302. } else {
  1303. pn.idx = env.createPrivateFieldId(name)
  1304. }
  1305. if s.privateNames == nil {
  1306. s.privateNames = make(map[unistring.String]*privateName)
  1307. }
  1308. s.privateNames[name] = pn
  1309. }
  1310. func (s *classScope) getDeclaredPrivateId(name unistring.String) *privateName {
  1311. if n := s.privateNames[name]; n != nil {
  1312. return n
  1313. }
  1314. s.c.assert(false, 0, "getDeclaredPrivateId() for undeclared id")
  1315. panic("unreachable")
  1316. }
  1317. func (c *compiler) resolvePrivateName(name unistring.String, offset int) (*resolvedPrivateName, *privateId) {
  1318. level := 0
  1319. for s := c.classScope; s != nil; s = s.outer {
  1320. if len(s.privateNames) > 0 {
  1321. if pn := s.privateNames[name]; pn != nil {
  1322. return &resolvedPrivateName{
  1323. name: name,
  1324. idx: uint32(pn.idx),
  1325. level: uint8(level),
  1326. isStatic: pn.isStatic,
  1327. isMethod: pn.isMethod,
  1328. }, nil
  1329. }
  1330. level++
  1331. }
  1332. }
  1333. if c.ctxVM != nil {
  1334. for s := c.ctxVM.privEnv; s != nil; s = s.outer {
  1335. if id := s.names[name]; id != nil {
  1336. return nil, id
  1337. }
  1338. }
  1339. }
  1340. c.throwSyntaxError(offset, "Private field '#%s' must be declared in an enclosing class", name)
  1341. panic("unreachable")
  1342. }