compiler.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  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 *newArrowFunc:
  367. prg = f.prg
  368. case *newMethod:
  369. prg = f.prg
  370. case *newDerivedClass:
  371. if f.initFields != nil {
  372. dumpInitFields(f.initFields)
  373. }
  374. prg = f.ctor
  375. case *newClass:
  376. if f.initFields != nil {
  377. dumpInitFields(f.initFields)
  378. }
  379. prg = f.ctor
  380. case *newStaticFieldInit:
  381. if f.initFields != nil {
  382. dumpInitFields(f.initFields)
  383. }
  384. }
  385. if prg != nil {
  386. prg._dumpCode(indent+">", logger)
  387. }
  388. }
  389. }
  390. func (p *Program) sourceOffset(pc int) int {
  391. i := sort.Search(len(p.srcMap), func(idx int) bool {
  392. return p.srcMap[idx].pc > pc
  393. }) - 1
  394. if i >= 0 {
  395. return p.srcMap[i].srcPos
  396. }
  397. return 0
  398. }
  399. func (p *Program) addSrcMap(srcPos int) {
  400. if len(p.srcMap) > 0 && p.srcMap[len(p.srcMap)-1].srcPos == srcPos {
  401. return
  402. }
  403. p.srcMap = append(p.srcMap, srcMapItem{pc: len(p.code), srcPos: srcPos})
  404. }
  405. func (s *scope) lookupName(name unistring.String) (binding *binding, noDynamics bool) {
  406. noDynamics = true
  407. toStash := false
  408. for curScope := s; ; curScope = curScope.outer {
  409. if curScope.outer != nil {
  410. if b, exists := curScope.boundNames[name]; exists {
  411. if toStash && !b.inStash {
  412. b.moveToStash()
  413. }
  414. binding = b
  415. return
  416. }
  417. } else {
  418. noDynamics = false
  419. return
  420. }
  421. if curScope.dynamic {
  422. noDynamics = false
  423. }
  424. if name == "arguments" && curScope.funcType != funcNone && curScope.funcType != funcArrow {
  425. if curScope.funcType == funcClsInit {
  426. s.c.throwSyntaxError(0, "'arguments' is not allowed in class field initializer or static initialization block")
  427. }
  428. curScope.argsNeeded = true
  429. binding, _ = curScope.bindName(name)
  430. return
  431. }
  432. if curScope.isFunction() {
  433. toStash = true
  434. }
  435. }
  436. }
  437. func (s *scope) lookupThis() (*binding, bool) {
  438. toStash := false
  439. for curScope := s; curScope != nil; curScope = curScope.outer {
  440. if curScope.outer == nil {
  441. if curScope.eval {
  442. return nil, true
  443. }
  444. }
  445. if b, exists := curScope.boundNames[thisBindingName]; exists {
  446. if toStash && !b.inStash {
  447. b.moveToStash()
  448. }
  449. return b, false
  450. }
  451. if curScope.isFunction() {
  452. toStash = true
  453. }
  454. }
  455. return nil, false
  456. }
  457. func (s *scope) ensureBoundNamesCreated() {
  458. if s.boundNames == nil {
  459. s.boundNames = make(map[unistring.String]*binding)
  460. }
  461. }
  462. func (s *scope) addBinding(offset int) *binding {
  463. if len(s.bindings) >= (1<<24)-1 {
  464. s.c.throwSyntaxError(offset, "Too many variables")
  465. }
  466. b := &binding{
  467. scope: s,
  468. }
  469. s.bindings = append(s.bindings, b)
  470. return b
  471. }
  472. func (s *scope) bindNameLexical(name unistring.String, unique bool, offset int) (*binding, bool) {
  473. if b := s.boundNames[name]; b != nil {
  474. if unique {
  475. s.c.throwSyntaxError(offset, "Identifier '%s' has already been declared", name)
  476. }
  477. return b, false
  478. }
  479. b := s.addBinding(offset)
  480. b.name = name
  481. s.ensureBoundNamesCreated()
  482. s.boundNames[name] = b
  483. return b, true
  484. }
  485. func (s *scope) createThisBinding() *binding {
  486. thisBinding, _ := s.bindNameLexical(thisBindingName, false, 0)
  487. thisBinding.isVar = true // don't check on load
  488. return thisBinding
  489. }
  490. func (s *scope) bindName(name unistring.String) (*binding, bool) {
  491. if !s.isFunction() && !s.variable && s.outer != nil {
  492. return s.outer.bindName(name)
  493. }
  494. b, created := s.bindNameLexical(name, false, 0)
  495. if created {
  496. b.isVar = true
  497. }
  498. return b, created
  499. }
  500. func (s *scope) bindNameShadow(name unistring.String) (*binding, bool) {
  501. if !s.isFunction() && s.outer != nil {
  502. return s.outer.bindNameShadow(name)
  503. }
  504. _, exists := s.boundNames[name]
  505. b := &binding{
  506. scope: s,
  507. name: name,
  508. }
  509. s.bindings = append(s.bindings, b)
  510. s.ensureBoundNamesCreated()
  511. s.boundNames[name] = b
  512. return b, !exists
  513. }
  514. func (s *scope) nearestFunction() *scope {
  515. for sc := s; sc != nil; sc = sc.outer {
  516. if sc.isFunction() {
  517. return sc
  518. }
  519. }
  520. return nil
  521. }
  522. func (s *scope) nearestThis() *scope {
  523. for sc := s; sc != nil; sc = sc.outer {
  524. if sc.eval || sc.isFunction() && sc.funcType != funcArrow {
  525. return sc
  526. }
  527. }
  528. return nil
  529. }
  530. func (s *scope) finaliseVarAlloc(stackOffset int) (stashSize, stackSize int) {
  531. argsInStash := false
  532. if f := s.nearestFunction(); f != nil {
  533. argsInStash = f.argsInStash
  534. }
  535. stackIdx, stashIdx := 0, 0
  536. allInStash := s.isDynamic()
  537. var derivedCtor bool
  538. if fs := s.nearestThis(); fs != nil && fs.funcType == funcDerivedCtor {
  539. derivedCtor = true
  540. }
  541. for i, b := range s.bindings {
  542. var this bool
  543. if b.name == thisBindingName {
  544. this = true
  545. }
  546. if allInStash || b.inStash {
  547. for scope, aps := range b.accessPoints {
  548. var level uint32
  549. for sc := scope; sc != nil && sc != s; sc = sc.outer {
  550. if sc.needStash || sc.isDynamic() {
  551. level++
  552. }
  553. }
  554. if level > 255 {
  555. s.c.throwSyntaxError(0, "Maximum nesting level (256) exceeded")
  556. }
  557. idx := (level << 24) | uint32(stashIdx)
  558. base := scope.base
  559. code := scope.prg.code
  560. if this {
  561. if derivedCtor {
  562. for _, pc := range *aps {
  563. ap := &code[base+pc]
  564. switch (*ap).(type) {
  565. case loadStack:
  566. *ap = loadThisStash(idx)
  567. case initStack:
  568. *ap = initStash(idx)
  569. case resolveThisStack:
  570. *ap = resolveThisStash(idx)
  571. case _ret:
  572. *ap = cret(idx)
  573. default:
  574. s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for 'this'")
  575. }
  576. }
  577. } else {
  578. for _, pc := range *aps {
  579. ap := &code[base+pc]
  580. switch (*ap).(type) {
  581. case loadStack:
  582. *ap = loadStash(idx)
  583. case initStack:
  584. *ap = initStash(idx)
  585. default:
  586. s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for 'this'")
  587. }
  588. }
  589. }
  590. } else {
  591. for _, pc := range *aps {
  592. ap := &code[base+pc]
  593. switch i := (*ap).(type) {
  594. case loadStack:
  595. *ap = loadStash(idx)
  596. case storeStack:
  597. *ap = storeStash(idx)
  598. case storeStackP:
  599. *ap = storeStashP(idx)
  600. case loadStackLex:
  601. *ap = loadStashLex(idx)
  602. case storeStackLex:
  603. *ap = storeStashLex(idx)
  604. case storeStackLexP:
  605. *ap = storeStashLexP(idx)
  606. case initStackP:
  607. *ap = initStashP(idx)
  608. case initStack:
  609. *ap = initStash(idx)
  610. case *loadMixed:
  611. i.idx = idx
  612. case *loadMixedLex:
  613. i.idx = idx
  614. case *resolveMixed:
  615. i.idx = idx
  616. default:
  617. s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for binding: %T", i)
  618. }
  619. }
  620. }
  621. }
  622. stashIdx++
  623. } else {
  624. var idx int
  625. if !this {
  626. if i < s.numArgs {
  627. idx = -(i + 1)
  628. } else {
  629. stackIdx++
  630. idx = stackIdx + stackOffset
  631. }
  632. }
  633. for scope, aps := range b.accessPoints {
  634. var level int
  635. for sc := scope; sc != nil && sc != s; sc = sc.outer {
  636. if sc.needStash || sc.isDynamic() {
  637. level++
  638. }
  639. }
  640. if level > 255 {
  641. s.c.throwSyntaxError(0, "Maximum nesting level (256) exceeded")
  642. }
  643. code := scope.prg.code
  644. base := scope.base
  645. if this {
  646. if derivedCtor {
  647. for _, pc := range *aps {
  648. ap := &code[base+pc]
  649. switch (*ap).(type) {
  650. case loadStack:
  651. *ap = loadThisStack{}
  652. case initStack:
  653. // no-op
  654. case resolveThisStack:
  655. // no-op
  656. case _ret:
  657. // no-op, already in the right place
  658. default:
  659. s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for 'this'")
  660. }
  661. }
  662. } /*else {
  663. no-op
  664. }*/
  665. } else if argsInStash {
  666. for _, pc := range *aps {
  667. ap := &code[base+pc]
  668. switch i := (*ap).(type) {
  669. case loadStack:
  670. *ap = loadStack1(idx)
  671. case storeStack:
  672. *ap = storeStack1(idx)
  673. case storeStackP:
  674. *ap = storeStack1P(idx)
  675. case loadStackLex:
  676. *ap = loadStack1Lex(idx)
  677. case storeStackLex:
  678. *ap = storeStack1Lex(idx)
  679. case storeStackLexP:
  680. *ap = storeStack1LexP(idx)
  681. case initStackP:
  682. *ap = initStack1P(idx)
  683. case initStack:
  684. *ap = initStack1(idx)
  685. case *loadMixed:
  686. *ap = &loadMixedStack1{name: i.name, idx: idx, level: uint8(level), callee: i.callee}
  687. case *loadMixedLex:
  688. *ap = &loadMixedStack1Lex{name: i.name, idx: idx, level: uint8(level), callee: i.callee}
  689. case *resolveMixed:
  690. *ap = &resolveMixedStack1{typ: i.typ, name: i.name, idx: idx, level: uint8(level), strict: i.strict}
  691. default:
  692. s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for binding: %T", i)
  693. }
  694. }
  695. } else {
  696. for _, pc := range *aps {
  697. ap := &code[base+pc]
  698. switch i := (*ap).(type) {
  699. case loadStack:
  700. *ap = loadStack(idx)
  701. case storeStack:
  702. *ap = storeStack(idx)
  703. case storeStackP:
  704. *ap = storeStackP(idx)
  705. case loadStackLex:
  706. *ap = loadStackLex(idx)
  707. case storeStackLex:
  708. *ap = storeStackLex(idx)
  709. case storeStackLexP:
  710. *ap = storeStackLexP(idx)
  711. case initStack:
  712. *ap = initStack(idx)
  713. case initStackP:
  714. *ap = initStackP(idx)
  715. case *loadMixed:
  716. *ap = &loadMixedStack{name: i.name, idx: idx, level: uint8(level), callee: i.callee}
  717. case *loadMixedLex:
  718. *ap = &loadMixedStackLex{name: i.name, idx: idx, level: uint8(level), callee: i.callee}
  719. case *resolveMixed:
  720. *ap = &resolveMixedStack{typ: i.typ, name: i.name, idx: idx, level: uint8(level), strict: i.strict}
  721. default:
  722. s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for binding: %T", i)
  723. }
  724. }
  725. }
  726. }
  727. }
  728. }
  729. for _, nested := range s.nested {
  730. nested.finaliseVarAlloc(stackIdx + stackOffset)
  731. }
  732. return stashIdx, stackIdx
  733. }
  734. func (s *scope) moveArgsToStash() {
  735. for _, b := range s.bindings {
  736. if !b.isArg {
  737. break
  738. }
  739. b.inStash = true
  740. }
  741. s.argsInStash = true
  742. s.needStash = true
  743. }
  744. func (c *compiler) trimCode(delta int) {
  745. src := c.p.code[delta:]
  746. newCode := make([]instruction, len(src))
  747. copy(newCode, src)
  748. if cap(c.codeScratchpad) < cap(c.p.code) {
  749. c.codeScratchpad = c.p.code[:0]
  750. }
  751. c.p.code = newCode
  752. }
  753. func (s *scope) trimCode(delta int) {
  754. s.c.trimCode(delta)
  755. if delta != 0 {
  756. srcMap := s.c.p.srcMap
  757. for i := range srcMap {
  758. srcMap[i].pc -= delta
  759. }
  760. s.adjustBase(-delta)
  761. }
  762. }
  763. func (s *scope) adjustBase(delta int) {
  764. s.base += delta
  765. for _, nested := range s.nested {
  766. nested.adjustBase(delta)
  767. }
  768. }
  769. func (s *scope) makeNamesMap() map[unistring.String]uint32 {
  770. l := len(s.bindings)
  771. if l == 0 {
  772. return nil
  773. }
  774. names := make(map[unistring.String]uint32, l)
  775. for i, b := range s.bindings {
  776. idx := uint32(i)
  777. if b.isConst {
  778. idx |= maskConst
  779. if b.isStrict {
  780. idx |= maskStrict
  781. }
  782. }
  783. if b.isVar {
  784. idx |= maskVar
  785. }
  786. names[b.name] = idx
  787. }
  788. return names
  789. }
  790. func (s *scope) isDynamic() bool {
  791. return s.dynLookup || s.dynamic
  792. }
  793. func (s *scope) isFunction() bool {
  794. return s.funcType != funcNone && !s.eval
  795. }
  796. func (s *scope) deleteBinding(b *binding) {
  797. idx := 0
  798. for i, bb := range s.bindings {
  799. if bb == b {
  800. idx = i
  801. goto found
  802. }
  803. }
  804. return
  805. found:
  806. delete(s.boundNames, b.name)
  807. copy(s.bindings[idx:], s.bindings[idx+1:])
  808. l := len(s.bindings) - 1
  809. s.bindings[l] = nil
  810. s.bindings = s.bindings[:l]
  811. }
  812. func (c *compiler) compile(in *ast.Program, strict, inGlobal bool, evalVm *vm) {
  813. c.ctxVM = evalVm
  814. eval := evalVm != nil
  815. c.p.src = in.File
  816. c.newScope()
  817. scope := c.scope
  818. scope.dynamic = true
  819. scope.eval = eval
  820. if !strict && len(in.Body) > 0 {
  821. strict = c.isStrict(in.Body) != nil
  822. }
  823. scope.strict = strict
  824. ownVarScope := eval && strict
  825. ownLexScope := !inGlobal || eval
  826. if ownVarScope {
  827. c.newBlockScope()
  828. scope = c.scope
  829. scope.variable = true
  830. }
  831. if eval && !inGlobal {
  832. for s := evalVm.stash; s != nil; s = s.outer {
  833. if ft := s.funcType; ft != funcNone && ft != funcArrow {
  834. scope.funcType = ft
  835. break
  836. }
  837. }
  838. }
  839. funcs := c.extractFunctions(in.Body)
  840. c.createFunctionBindings(funcs)
  841. numFuncs := len(scope.bindings)
  842. if inGlobal && !ownVarScope {
  843. if numFuncs == len(funcs) {
  844. c.compileFunctionsGlobalAllUnique(funcs)
  845. } else {
  846. c.compileFunctionsGlobal(funcs)
  847. }
  848. }
  849. c.compileDeclList(in.DeclarationList, false)
  850. numVars := len(scope.bindings) - numFuncs
  851. vars := make([]unistring.String, len(scope.bindings))
  852. for i, b := range scope.bindings {
  853. vars[i] = b.name
  854. }
  855. if len(vars) > 0 && !ownVarScope && ownLexScope {
  856. if inGlobal {
  857. c.emit(&bindGlobal{
  858. vars: vars[numFuncs:],
  859. funcs: vars[:numFuncs],
  860. deletable: eval,
  861. })
  862. } else {
  863. c.emit(&bindVars{names: vars, deletable: eval})
  864. }
  865. }
  866. var enter *enterBlock
  867. if c.compileLexicalDeclarations(in.Body, ownVarScope || !ownLexScope) {
  868. if ownLexScope {
  869. c.block = &block{
  870. outer: c.block,
  871. typ: blockScope,
  872. needResult: true,
  873. }
  874. enter = &enterBlock{}
  875. c.emit(enter)
  876. }
  877. }
  878. if len(scope.bindings) > 0 && !ownLexScope {
  879. var lets, consts []unistring.String
  880. for _, b := range c.scope.bindings[numFuncs+numVars:] {
  881. if b.isConst {
  882. consts = append(consts, b.name)
  883. } else {
  884. lets = append(lets, b.name)
  885. }
  886. }
  887. c.emit(&bindGlobal{
  888. vars: vars[numFuncs:],
  889. funcs: vars[:numFuncs],
  890. lets: lets,
  891. consts: consts,
  892. })
  893. }
  894. if !inGlobal || ownVarScope {
  895. c.compileFunctions(funcs)
  896. }
  897. c.compileStatements(in.Body, true)
  898. if enter != nil {
  899. c.leaveScopeBlock(enter)
  900. c.popScope()
  901. }
  902. c.p.code = append(c.p.code, halt)
  903. scope.finaliseVarAlloc(0)
  904. }
  905. func (c *compiler) compileDeclList(v []*ast.VariableDeclaration, inFunc bool) {
  906. for _, value := range v {
  907. c.createVarBindings(value, inFunc)
  908. }
  909. }
  910. func (c *compiler) extractLabelled(st ast.Statement) ast.Statement {
  911. if st, ok := st.(*ast.LabelledStatement); ok {
  912. return c.extractLabelled(st.Statement)
  913. }
  914. return st
  915. }
  916. func (c *compiler) extractFunctions(list []ast.Statement) (funcs []*ast.FunctionDeclaration) {
  917. for _, st := range list {
  918. var decl *ast.FunctionDeclaration
  919. switch st := c.extractLabelled(st).(type) {
  920. case *ast.FunctionDeclaration:
  921. decl = st
  922. case *ast.LabelledStatement:
  923. if st1, ok := st.Statement.(*ast.FunctionDeclaration); ok {
  924. decl = st1
  925. } else {
  926. continue
  927. }
  928. default:
  929. continue
  930. }
  931. funcs = append(funcs, decl)
  932. }
  933. return
  934. }
  935. func (c *compiler) createFunctionBindings(funcs []*ast.FunctionDeclaration) {
  936. s := c.scope
  937. if s.outer != nil {
  938. unique := !s.isFunction() && !s.variable && s.strict
  939. for _, decl := range funcs {
  940. s.bindNameLexical(decl.Function.Name.Name, unique, int(decl.Function.Name.Idx1())-1)
  941. }
  942. } else {
  943. for _, decl := range funcs {
  944. s.bindName(decl.Function.Name.Name)
  945. }
  946. }
  947. }
  948. func (c *compiler) compileFunctions(list []*ast.FunctionDeclaration) {
  949. for _, decl := range list {
  950. c.compileFunction(decl)
  951. }
  952. }
  953. func (c *compiler) compileFunctionsGlobalAllUnique(list []*ast.FunctionDeclaration) {
  954. for _, decl := range list {
  955. c.compileFunctionLiteral(decl.Function, false).emitGetter(true)
  956. }
  957. }
  958. func (c *compiler) compileFunctionsGlobal(list []*ast.FunctionDeclaration) {
  959. m := make(map[unistring.String]int, len(list))
  960. for i := len(list) - 1; i >= 0; i-- {
  961. name := list[i].Function.Name.Name
  962. if _, exists := m[name]; !exists {
  963. m[name] = i
  964. }
  965. }
  966. idx := 0
  967. for i, decl := range list {
  968. name := decl.Function.Name.Name
  969. if m[name] == i {
  970. c.compileFunctionLiteral(decl.Function, false).emitGetter(true)
  971. c.scope.bindings[idx] = c.scope.boundNames[name]
  972. idx++
  973. } else {
  974. leave := c.enterDummyMode()
  975. c.compileFunctionLiteral(decl.Function, false).emitGetter(false)
  976. leave()
  977. }
  978. }
  979. }
  980. func (c *compiler) createVarIdBinding(name unistring.String, offset int, inFunc bool) {
  981. if c.scope.strict {
  982. c.checkIdentifierLName(name, offset)
  983. c.checkIdentifierName(name, offset)
  984. }
  985. if !inFunc || name != "arguments" {
  986. c.scope.bindName(name)
  987. }
  988. }
  989. func (c *compiler) createBindings(target ast.Expression, createIdBinding func(name unistring.String, offset int)) {
  990. switch target := target.(type) {
  991. case *ast.Identifier:
  992. createIdBinding(target.Name, int(target.Idx)-1)
  993. case *ast.ObjectPattern:
  994. for _, prop := range target.Properties {
  995. switch prop := prop.(type) {
  996. case *ast.PropertyShort:
  997. createIdBinding(prop.Name.Name, int(prop.Name.Idx)-1)
  998. case *ast.PropertyKeyed:
  999. c.createBindings(prop.Value, createIdBinding)
  1000. default:
  1001. c.throwSyntaxError(int(target.Idx0()-1), "unsupported property type in ObjectPattern: %T", prop)
  1002. }
  1003. }
  1004. if target.Rest != nil {
  1005. c.createBindings(target.Rest, createIdBinding)
  1006. }
  1007. case *ast.ArrayPattern:
  1008. for _, elt := range target.Elements {
  1009. if elt != nil {
  1010. c.createBindings(elt, createIdBinding)
  1011. }
  1012. }
  1013. if target.Rest != nil {
  1014. c.createBindings(target.Rest, createIdBinding)
  1015. }
  1016. case *ast.AssignExpression:
  1017. c.createBindings(target.Left, createIdBinding)
  1018. default:
  1019. c.throwSyntaxError(int(target.Idx0()-1), "unsupported binding target: %T", target)
  1020. }
  1021. }
  1022. func (c *compiler) createVarBinding(target ast.Expression, inFunc bool) {
  1023. c.createBindings(target, func(name unistring.String, offset int) {
  1024. c.createVarIdBinding(name, offset, inFunc)
  1025. })
  1026. }
  1027. func (c *compiler) createVarBindings(v *ast.VariableDeclaration, inFunc bool) {
  1028. for _, item := range v.List {
  1029. c.createVarBinding(item.Target, inFunc)
  1030. }
  1031. }
  1032. func (c *compiler) createLexicalIdBinding(name unistring.String, isConst bool, offset int) *binding {
  1033. if name == "let" {
  1034. c.throwSyntaxError(offset, "let is disallowed as a lexically bound name")
  1035. }
  1036. if c.scope.strict {
  1037. c.checkIdentifierLName(name, offset)
  1038. c.checkIdentifierName(name, offset)
  1039. }
  1040. b, _ := c.scope.bindNameLexical(name, true, offset)
  1041. if isConst {
  1042. b.isConst, b.isStrict = true, true
  1043. }
  1044. return b
  1045. }
  1046. func (c *compiler) createLexicalIdBindingFuncBody(name unistring.String, isConst bool, offset int, calleeBinding *binding) *binding {
  1047. if name == "let" {
  1048. c.throwSyntaxError(offset, "let is disallowed as a lexically bound name")
  1049. }
  1050. if c.scope.strict {
  1051. c.checkIdentifierLName(name, offset)
  1052. c.checkIdentifierName(name, offset)
  1053. }
  1054. paramScope := c.scope.outer
  1055. parentBinding := paramScope.boundNames[name]
  1056. if parentBinding != nil {
  1057. if parentBinding != calleeBinding && (name != "arguments" || !paramScope.argsNeeded) {
  1058. c.throwSyntaxError(offset, "Identifier '%s' has already been declared", name)
  1059. }
  1060. }
  1061. b, _ := c.scope.bindNameLexical(name, true, offset)
  1062. if isConst {
  1063. b.isConst, b.isStrict = true, true
  1064. }
  1065. return b
  1066. }
  1067. func (c *compiler) createLexicalBinding(target ast.Expression, isConst bool) {
  1068. c.createBindings(target, func(name unistring.String, offset int) {
  1069. c.createLexicalIdBinding(name, isConst, offset)
  1070. })
  1071. }
  1072. func (c *compiler) createLexicalBindings(lex *ast.LexicalDeclaration) {
  1073. for _, d := range lex.List {
  1074. c.createLexicalBinding(d.Target, lex.Token == token.CONST)
  1075. }
  1076. }
  1077. func (c *compiler) compileLexicalDeclarations(list []ast.Statement, scopeDeclared bool) bool {
  1078. for _, st := range list {
  1079. if lex, ok := st.(*ast.LexicalDeclaration); ok {
  1080. if !scopeDeclared {
  1081. c.newBlockScope()
  1082. scopeDeclared = true
  1083. }
  1084. c.createLexicalBindings(lex)
  1085. } else if cls, ok := st.(*ast.ClassDeclaration); ok {
  1086. if !scopeDeclared {
  1087. c.newBlockScope()
  1088. scopeDeclared = true
  1089. }
  1090. c.createLexicalIdBinding(cls.Class.Name.Name, false, int(cls.Class.Name.Idx)-1)
  1091. }
  1092. }
  1093. return scopeDeclared
  1094. }
  1095. func (c *compiler) compileLexicalDeclarationsFuncBody(list []ast.Statement, calleeBinding *binding) {
  1096. for _, st := range list {
  1097. if lex, ok := st.(*ast.LexicalDeclaration); ok {
  1098. isConst := lex.Token == token.CONST
  1099. for _, d := range lex.List {
  1100. c.createBindings(d.Target, func(name unistring.String, offset int) {
  1101. c.createLexicalIdBindingFuncBody(name, isConst, offset, calleeBinding)
  1102. })
  1103. }
  1104. }
  1105. }
  1106. }
  1107. func (c *compiler) compileFunction(v *ast.FunctionDeclaration) {
  1108. name := v.Function.Name.Name
  1109. b := c.scope.boundNames[name]
  1110. if b == nil || b.isVar {
  1111. e := &compiledIdentifierExpr{
  1112. name: v.Function.Name.Name,
  1113. }
  1114. e.init(c, v.Function.Idx0())
  1115. e.emitSetter(c.compileFunctionLiteral(v.Function, false), false)
  1116. } else {
  1117. c.compileFunctionLiteral(v.Function, false).emitGetter(true)
  1118. b.emitInitP()
  1119. }
  1120. }
  1121. func (c *compiler) compileStandaloneFunctionDecl(v *ast.FunctionDeclaration) {
  1122. if c.scope.strict {
  1123. c.throwSyntaxError(int(v.Idx0())-1, "In strict mode code, functions can only be declared at top level or inside a block.")
  1124. }
  1125. 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.")
  1126. }
  1127. func (c *compiler) emit(instructions ...instruction) {
  1128. c.p.code = append(c.p.code, instructions...)
  1129. }
  1130. func (c *compiler) throwSyntaxError(offset int, format string, args ...interface{}) {
  1131. panic(&CompilerSyntaxError{
  1132. CompilerError: CompilerError{
  1133. File: c.p.src,
  1134. Offset: offset,
  1135. Message: fmt.Sprintf(format, args...),
  1136. },
  1137. })
  1138. }
  1139. func (c *compiler) isStrict(list []ast.Statement) *ast.StringLiteral {
  1140. for _, st := range list {
  1141. if st, ok := st.(*ast.ExpressionStatement); ok {
  1142. if e, ok := st.Expression.(*ast.StringLiteral); ok {
  1143. if e.Literal == `"use strict"` || e.Literal == `'use strict'` {
  1144. return e
  1145. }
  1146. } else {
  1147. break
  1148. }
  1149. } else {
  1150. break
  1151. }
  1152. }
  1153. return nil
  1154. }
  1155. func (c *compiler) isStrictStatement(s ast.Statement) *ast.StringLiteral {
  1156. if s, ok := s.(*ast.BlockStatement); ok {
  1157. return c.isStrict(s.List)
  1158. }
  1159. return nil
  1160. }
  1161. func (c *compiler) checkIdentifierName(name unistring.String, offset int) {
  1162. switch name {
  1163. case "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield":
  1164. c.throwSyntaxError(offset, "Unexpected strict mode reserved word")
  1165. }
  1166. }
  1167. func (c *compiler) checkIdentifierLName(name unistring.String, offset int) {
  1168. switch name {
  1169. case "eval", "arguments":
  1170. c.throwSyntaxError(offset, "Assignment to eval or arguments is not allowed in strict mode")
  1171. }
  1172. }
  1173. // Enter a 'dummy' compilation mode. Any code produced after this method is called will be discarded after
  1174. // leaveFunc is called with no additional side effects. This is useful for compiling code inside a
  1175. // constant falsy condition 'if' branch or a loop (i.e 'if (false) { ... } or while (false) { ... }).
  1176. // Such code should not be included in the final compilation result as it's never called, but it must
  1177. // still produce compilation errors if there are any.
  1178. // TODO: make sure variable lookups do not de-optimise parent scopes
  1179. func (c *compiler) enterDummyMode() (leaveFunc func()) {
  1180. savedBlock, savedProgram := c.block, c.p
  1181. if savedBlock != nil {
  1182. c.block = &block{
  1183. typ: savedBlock.typ,
  1184. label: savedBlock.label,
  1185. outer: savedBlock.outer,
  1186. breaking: savedBlock.breaking,
  1187. }
  1188. }
  1189. c.p = &Program{}
  1190. c.newScope()
  1191. return func() {
  1192. c.block, c.p = savedBlock, savedProgram
  1193. c.popScope()
  1194. }
  1195. }
  1196. func (c *compiler) compileStatementDummy(statement ast.Statement) {
  1197. leave := c.enterDummyMode()
  1198. c.compileStatement(statement, false)
  1199. leave()
  1200. }
  1201. func (c *compiler) assert(cond bool, offset int, msg string, args ...interface{}) {
  1202. if !cond {
  1203. c.throwSyntaxError(offset, "Compiler bug: "+msg, args...)
  1204. }
  1205. }
  1206. func privateIdString(desc unistring.String) unistring.String {
  1207. return asciiString("#").concat(stringValueFromRaw(desc)).string()
  1208. }
  1209. type privateName struct {
  1210. idx int
  1211. isStatic bool
  1212. isMethod bool
  1213. hasGetter, hasSetter bool
  1214. }
  1215. type resolvedPrivateName struct {
  1216. name unistring.String
  1217. idx uint32
  1218. level uint8
  1219. isStatic bool
  1220. isMethod bool
  1221. }
  1222. func (r *resolvedPrivateName) string() unistring.String {
  1223. return privateIdString(r.name)
  1224. }
  1225. type privateEnvRegistry struct {
  1226. fields, methods []unistring.String
  1227. }
  1228. type classScope struct {
  1229. c *compiler
  1230. privateNames map[unistring.String]*privateName
  1231. instanceEnv, staticEnv privateEnvRegistry
  1232. outer *classScope
  1233. }
  1234. func (r *privateEnvRegistry) createPrivateMethodId(name unistring.String) int {
  1235. r.methods = append(r.methods, name)
  1236. return len(r.methods) - 1
  1237. }
  1238. func (r *privateEnvRegistry) createPrivateFieldId(name unistring.String) int {
  1239. r.fields = append(r.fields, name)
  1240. return len(r.fields) - 1
  1241. }
  1242. func (s *classScope) declarePrivateId(name unistring.String, kind ast.PropertyKind, isStatic bool, offset int) {
  1243. pn := s.privateNames[name]
  1244. if pn != nil {
  1245. if pn.isStatic == isStatic {
  1246. switch kind {
  1247. case ast.PropertyKindGet:
  1248. if pn.hasSetter && !pn.hasGetter {
  1249. pn.hasGetter = true
  1250. return
  1251. }
  1252. case ast.PropertyKindSet:
  1253. if pn.hasGetter && !pn.hasSetter {
  1254. pn.hasSetter = true
  1255. return
  1256. }
  1257. }
  1258. }
  1259. s.c.throwSyntaxError(offset, "Identifier '#%s' has already been declared", name)
  1260. panic("unreachable")
  1261. }
  1262. var env *privateEnvRegistry
  1263. if isStatic {
  1264. env = &s.staticEnv
  1265. } else {
  1266. env = &s.instanceEnv
  1267. }
  1268. pn = &privateName{
  1269. isStatic: isStatic,
  1270. hasGetter: kind == ast.PropertyKindGet,
  1271. hasSetter: kind == ast.PropertyKindSet,
  1272. }
  1273. if kind != ast.PropertyKindValue {
  1274. pn.idx = env.createPrivateMethodId(name)
  1275. pn.isMethod = true
  1276. } else {
  1277. pn.idx = env.createPrivateFieldId(name)
  1278. }
  1279. if s.privateNames == nil {
  1280. s.privateNames = make(map[unistring.String]*privateName)
  1281. }
  1282. s.privateNames[name] = pn
  1283. }
  1284. func (s *classScope) getDeclaredPrivateId(name unistring.String) *privateName {
  1285. if n := s.privateNames[name]; n != nil {
  1286. return n
  1287. }
  1288. s.c.assert(false, 0, "getDeclaredPrivateId() for undeclared id")
  1289. panic("unreachable")
  1290. }
  1291. func (c *compiler) resolvePrivateName(name unistring.String, offset int) (*resolvedPrivateName, *privateId) {
  1292. level := 0
  1293. for s := c.classScope; s != nil; s = s.outer {
  1294. if len(s.privateNames) > 0 {
  1295. if pn := s.privateNames[name]; pn != nil {
  1296. return &resolvedPrivateName{
  1297. name: name,
  1298. idx: uint32(pn.idx),
  1299. level: uint8(level),
  1300. isStatic: pn.isStatic,
  1301. isMethod: pn.isMethod,
  1302. }, nil
  1303. }
  1304. level++
  1305. }
  1306. }
  1307. if c.ctxVM != nil {
  1308. for s := c.ctxVM.privEnv; s != nil; s = s.outer {
  1309. if id := s.names[name]; id != nil {
  1310. return nil, id
  1311. }
  1312. }
  1313. }
  1314. c.throwSyntaxError(offset, "Private field '#%s' must be declared in an enclosing class", name)
  1315. panic("unreachable")
  1316. }