compiler.go 35 KB

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