compiler_stmt.go 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  1. package goja
  2. import (
  3. "fmt"
  4. "github.com/dop251/goja/ast"
  5. "github.com/dop251/goja/file"
  6. "github.com/dop251/goja/token"
  7. "github.com/dop251/goja/unistring"
  8. )
  9. func (c *compiler) compileStatement(v ast.Statement, needResult bool) {
  10. // log.Printf("compileStatement(): %T", v)
  11. switch v := v.(type) {
  12. case *ast.BlockStatement:
  13. c.compileBlockStatement(v, needResult)
  14. case *ast.ExpressionStatement:
  15. c.compileExpressionStatement(v, needResult)
  16. case *ast.VariableStatement:
  17. c.compileVariableStatement(v)
  18. case *ast.LexicalDeclaration:
  19. c.compileLexicalDeclaration(v)
  20. case *ast.ReturnStatement:
  21. c.compileReturnStatement(v)
  22. case *ast.IfStatement:
  23. c.compileIfStatement(v, needResult)
  24. case *ast.DoWhileStatement:
  25. c.compileDoWhileStatement(v, needResult)
  26. case *ast.ForStatement:
  27. c.compileForStatement(v, needResult)
  28. case *ast.ForInStatement:
  29. c.compileForInStatement(v, needResult)
  30. case *ast.ForOfStatement:
  31. c.compileForOfStatement(v, needResult)
  32. case *ast.WhileStatement:
  33. c.compileWhileStatement(v, needResult)
  34. case *ast.BranchStatement:
  35. c.compileBranchStatement(v)
  36. case *ast.TryStatement:
  37. c.compileTryStatement(v, needResult)
  38. case *ast.ThrowStatement:
  39. c.compileThrowStatement(v)
  40. case *ast.SwitchStatement:
  41. c.compileSwitchStatement(v, needResult)
  42. case *ast.LabelledStatement:
  43. c.compileLabeledStatement(v, needResult)
  44. case *ast.EmptyStatement:
  45. c.compileEmptyStatement(needResult)
  46. case *ast.FunctionDeclaration:
  47. c.compileStandaloneFunctionDecl(v)
  48. // note functions inside blocks are hoisted to the top of the block and are compiled using compileFunctions()
  49. case *ast.WithStatement:
  50. c.compileWithStatement(v, needResult)
  51. case *ast.DebuggerStatement:
  52. default:
  53. panic(fmt.Errorf("Unknown statement type: %T", v))
  54. }
  55. }
  56. func (c *compiler) compileLabeledStatement(v *ast.LabelledStatement, needResult bool) {
  57. label := v.Label.Name
  58. if c.scope.strict {
  59. c.checkIdentifierName(label, int(v.Label.Idx)-1)
  60. }
  61. for b := c.block; b != nil; b = b.outer {
  62. if b.label == label {
  63. c.throwSyntaxError(int(v.Label.Idx-1), "Label '%s' has already been declared", label)
  64. }
  65. }
  66. switch s := v.Statement.(type) {
  67. case *ast.ForInStatement:
  68. c.compileLabeledForInStatement(s, needResult, label)
  69. case *ast.ForOfStatement:
  70. c.compileLabeledForOfStatement(s, needResult, label)
  71. case *ast.ForStatement:
  72. c.compileLabeledForStatement(s, needResult, label)
  73. case *ast.WhileStatement:
  74. c.compileLabeledWhileStatement(s, needResult, label)
  75. case *ast.DoWhileStatement:
  76. c.compileLabeledDoWhileStatement(s, needResult, label)
  77. default:
  78. c.compileGenericLabeledStatement(s, needResult, label)
  79. }
  80. }
  81. func (c *compiler) updateEnterBlock(enter *enterBlock) {
  82. scope := c.scope
  83. stashSize, stackSize := 0, 0
  84. if scope.dynLookup {
  85. stashSize = len(scope.bindings)
  86. enter.names = scope.makeNamesMap()
  87. } else {
  88. for _, b := range scope.bindings {
  89. if b.inStash {
  90. stashSize++
  91. } else {
  92. stackSize++
  93. }
  94. }
  95. }
  96. enter.stashSize, enter.stackSize = uint32(stashSize), uint32(stackSize)
  97. }
  98. func (c *compiler) compileTryStatement(v *ast.TryStatement, needResult bool) {
  99. c.block = &block{
  100. typ: blockTry,
  101. outer: c.block,
  102. }
  103. var lp int
  104. var bodyNeedResult bool
  105. var finallyBreaking *block
  106. if v.Finally != nil {
  107. lp, finallyBreaking = c.scanStatements(v.Finally.List)
  108. }
  109. if finallyBreaking != nil {
  110. c.block.breaking = finallyBreaking
  111. if lp == -1 {
  112. bodyNeedResult = finallyBreaking.needResult
  113. }
  114. } else {
  115. bodyNeedResult = needResult
  116. }
  117. lbl := len(c.p.code)
  118. c.emit(nil)
  119. if needResult {
  120. c.emit(clearResult)
  121. }
  122. c.compileBlockStatement(v.Body, bodyNeedResult)
  123. c.emit(halt)
  124. lbl2 := len(c.p.code)
  125. c.emit(nil)
  126. var catchOffset int
  127. if v.Catch != nil {
  128. catchOffset = len(c.p.code) - lbl
  129. if v.Catch.Parameter != nil {
  130. c.block = &block{
  131. typ: blockScope,
  132. outer: c.block,
  133. }
  134. c.newBlockScope()
  135. list := v.Catch.Body.List
  136. funcs := c.extractFunctions(list)
  137. if _, ok := v.Catch.Parameter.(ast.Pattern); ok {
  138. // add anonymous binding for the catch parameter, note it must be first
  139. c.scope.addBinding(int(v.Catch.Idx0()) - 1)
  140. }
  141. c.createBindings(v.Catch.Parameter, func(name unistring.String, offset int) {
  142. if c.scope.strict {
  143. switch name {
  144. case "arguments", "eval":
  145. c.throwSyntaxError(offset, "Catch variable may not be eval or arguments in strict mode")
  146. }
  147. }
  148. c.scope.bindNameLexical(name, true, offset)
  149. })
  150. enter := &enterBlock{}
  151. c.emit(enter)
  152. if pattern, ok := v.Catch.Parameter.(ast.Pattern); ok {
  153. c.scope.bindings[0].emitGet()
  154. c.emitPattern(pattern, func(target, init compiledExpr) {
  155. c.emitPatternLexicalAssign(target, init, false)
  156. }, false)
  157. }
  158. for _, decl := range funcs {
  159. c.scope.bindNameLexical(decl.Function.Name.Name, true, int(decl.Function.Name.Idx1())-1)
  160. }
  161. c.compileLexicalDeclarations(list, true)
  162. c.compileFunctions(funcs)
  163. c.compileStatements(list, bodyNeedResult)
  164. c.leaveScopeBlock(enter)
  165. if c.scope.dynLookup || c.scope.bindings[0].inStash {
  166. c.p.code[lbl+catchOffset] = &enterCatchBlock{
  167. names: enter.names,
  168. stashSize: enter.stashSize,
  169. stackSize: enter.stackSize,
  170. }
  171. } else {
  172. enter.stackSize--
  173. }
  174. c.popScope()
  175. } else {
  176. c.emit(pop)
  177. c.compileBlockStatement(v.Catch.Body, bodyNeedResult)
  178. }
  179. c.emit(halt)
  180. }
  181. var finallyOffset int
  182. if v.Finally != nil {
  183. lbl1 := len(c.p.code)
  184. c.emit(nil)
  185. finallyOffset = len(c.p.code) - lbl
  186. c.compileBlockStatement(v.Finally, false)
  187. c.emit(halt, retFinally)
  188. c.p.code[lbl1] = jump(len(c.p.code) - lbl1)
  189. }
  190. c.p.code[lbl] = try{catchOffset: int32(catchOffset), finallyOffset: int32(finallyOffset)}
  191. c.p.code[lbl2] = jump(len(c.p.code) - lbl2)
  192. c.leaveBlock()
  193. }
  194. func (c *compiler) compileThrowStatement(v *ast.ThrowStatement) {
  195. //c.p.srcMap = append(c.p.srcMap, srcMapItem{pc: len(c.p.code), srcPos: int(v.Throw) - 1})
  196. c.compileExpression(v.Argument).emitGetter(true)
  197. c.emit(throw)
  198. }
  199. func (c *compiler) compileDoWhileStatement(v *ast.DoWhileStatement, needResult bool) {
  200. c.compileLabeledDoWhileStatement(v, needResult, "")
  201. }
  202. func (c *compiler) compileLabeledDoWhileStatement(v *ast.DoWhileStatement, needResult bool, label unistring.String) {
  203. c.block = &block{
  204. typ: blockLoop,
  205. outer: c.block,
  206. label: label,
  207. needResult: needResult,
  208. }
  209. start := len(c.p.code)
  210. c.compileStatement(v.Body, needResult)
  211. c.block.cont = len(c.p.code)
  212. c.emitExpr(c.compileExpression(v.Test), true)
  213. c.emit(jeq(start - len(c.p.code)))
  214. c.leaveBlock()
  215. }
  216. func (c *compiler) compileForStatement(v *ast.ForStatement, needResult bool) {
  217. c.compileLabeledForStatement(v, needResult, "")
  218. }
  219. func (c *compiler) compileForHeadLexDecl(decl *ast.LexicalDeclaration, needResult bool) *enterBlock {
  220. c.block = &block{
  221. typ: blockIterScope,
  222. outer: c.block,
  223. needResult: needResult,
  224. }
  225. c.newBlockScope()
  226. enterIterBlock := &enterBlock{}
  227. c.emit(enterIterBlock)
  228. c.createLexicalBindings(decl)
  229. c.compileLexicalDeclaration(decl)
  230. return enterIterBlock
  231. }
  232. func (c *compiler) compileLabeledForStatement(v *ast.ForStatement, needResult bool, label unistring.String) {
  233. loopBlock := &block{
  234. typ: blockLoop,
  235. outer: c.block,
  236. label: label,
  237. needResult: needResult,
  238. }
  239. c.block = loopBlock
  240. var enterIterBlock *enterBlock
  241. switch init := v.Initializer.(type) {
  242. case nil:
  243. // no-op
  244. case *ast.ForLoopInitializerLexicalDecl:
  245. enterIterBlock = c.compileForHeadLexDecl(&init.LexicalDeclaration, needResult)
  246. case *ast.ForLoopInitializerVarDeclList:
  247. for _, expr := range init.List {
  248. c.compileVarBinding(expr)
  249. }
  250. case *ast.ForLoopInitializerExpression:
  251. c.compileExpression(init.Expression).emitGetter(false)
  252. default:
  253. panic(fmt.Sprintf("Unsupported for loop initializer: %T", init))
  254. }
  255. if needResult {
  256. c.emit(clearResult) // initial result
  257. }
  258. if enterIterBlock != nil {
  259. c.emit(jump(1))
  260. }
  261. start := len(c.p.code)
  262. var j int
  263. testConst := false
  264. if v.Test != nil {
  265. expr := c.compileExpression(v.Test)
  266. if expr.constant() {
  267. r, ex := c.evalConst(expr)
  268. if ex == nil {
  269. if r.ToBoolean() {
  270. testConst = true
  271. } else {
  272. leave := c.enterDummyMode()
  273. c.compileStatement(v.Body, false)
  274. if v.Update != nil {
  275. c.compileExpression(v.Update).emitGetter(false)
  276. }
  277. leave()
  278. goto end
  279. }
  280. } else {
  281. expr.addSrcMap()
  282. c.emitThrow(ex.val)
  283. goto end
  284. }
  285. } else {
  286. expr.emitGetter(true)
  287. j = len(c.p.code)
  288. c.emit(nil)
  289. }
  290. }
  291. if needResult {
  292. c.emit(clearResult)
  293. }
  294. c.compileStatement(v.Body, needResult)
  295. loopBlock.cont = len(c.p.code)
  296. if enterIterBlock != nil {
  297. c.emit(jump(1))
  298. }
  299. if v.Update != nil {
  300. c.compileExpression(v.Update).emitGetter(false)
  301. }
  302. if enterIterBlock != nil {
  303. if c.scope.needStash || c.scope.isDynamic() {
  304. c.p.code[start-1] = copyStash{}
  305. c.p.code[loopBlock.cont] = copyStash{}
  306. } else {
  307. if l := len(c.p.code); l > loopBlock.cont {
  308. loopBlock.cont++
  309. } else {
  310. c.p.code = c.p.code[:l-1]
  311. }
  312. }
  313. }
  314. c.emit(jump(start - len(c.p.code)))
  315. if v.Test != nil {
  316. if !testConst {
  317. c.p.code[j] = jne(len(c.p.code) - j)
  318. }
  319. }
  320. end:
  321. if enterIterBlock != nil {
  322. c.leaveScopeBlock(enterIterBlock)
  323. c.popScope()
  324. }
  325. c.leaveBlock()
  326. }
  327. func (c *compiler) compileForInStatement(v *ast.ForInStatement, needResult bool) {
  328. c.compileLabeledForInStatement(v, needResult, "")
  329. }
  330. func (c *compiler) compileForInto(into ast.ForInto, needResult bool) (enter *enterBlock) {
  331. switch into := into.(type) {
  332. case *ast.ForIntoExpression:
  333. c.compileExpression(into.Expression).emitSetter(&c.enumGetExpr, false)
  334. case *ast.ForIntoVar:
  335. if c.scope.strict && into.Binding.Initializer != nil {
  336. c.throwSyntaxError(int(into.Binding.Initializer.Idx0())-1, "for-in loop variable declaration may not have an initializer.")
  337. }
  338. switch target := into.Binding.Target.(type) {
  339. case *ast.Identifier:
  340. c.compileIdentifierExpression(target).emitSetter(&c.enumGetExpr, false)
  341. case ast.Pattern:
  342. c.emit(enumGet)
  343. c.emitPattern(target, c.emitPatternVarAssign, false)
  344. default:
  345. c.throwSyntaxError(int(target.Idx0()-1), "unsupported for-in var target: %T", target)
  346. }
  347. case *ast.ForDeclaration:
  348. c.block = &block{
  349. typ: blockIterScope,
  350. outer: c.block,
  351. needResult: needResult,
  352. }
  353. c.newBlockScope()
  354. enter = &enterBlock{}
  355. c.emit(enter)
  356. switch target := into.Target.(type) {
  357. case *ast.Identifier:
  358. b := c.createLexicalIdBinding(target.Name, into.IsConst, int(into.Idx)-1)
  359. c.emit(enumGet)
  360. b.emitInit()
  361. case ast.Pattern:
  362. c.createLexicalBinding(target, into.IsConst)
  363. c.emit(enumGet)
  364. c.emitPattern(target, func(target, init compiledExpr) {
  365. c.emitPatternLexicalAssign(target, init, into.IsConst)
  366. }, false)
  367. default:
  368. c.throwSyntaxError(int(into.Idx)-1, "Unsupported ForBinding: %T", into.Target)
  369. }
  370. default:
  371. panic(fmt.Sprintf("Unsupported for-into: %T", into))
  372. }
  373. return
  374. }
  375. func (c *compiler) compileLabeledForInOfStatement(into ast.ForInto, source ast.Expression, body ast.Statement, iter, needResult bool, label unistring.String) {
  376. c.block = &block{
  377. typ: blockLoopEnum,
  378. outer: c.block,
  379. label: label,
  380. needResult: needResult,
  381. }
  382. enterPos := -1
  383. if forDecl, ok := into.(*ast.ForDeclaration); ok {
  384. c.block = &block{
  385. typ: blockScope,
  386. outer: c.block,
  387. needResult: false,
  388. }
  389. c.newBlockScope()
  390. enterPos = len(c.p.code)
  391. c.emit(jump(1))
  392. c.createLexicalBinding(forDecl.Target, forDecl.IsConst)
  393. }
  394. c.compileExpression(source).emitGetter(true)
  395. if enterPos != -1 {
  396. s := c.scope
  397. used := len(c.block.breaks) > 0 || s.isDynamic()
  398. if !used {
  399. for _, b := range s.bindings {
  400. if b.useCount() > 0 {
  401. used = true
  402. break
  403. }
  404. }
  405. }
  406. if used {
  407. // We need the stack untouched because it contains the source.
  408. // This is not the most optimal way, but it's an edge case, hopefully quite rare.
  409. for _, b := range s.bindings {
  410. b.moveToStash()
  411. }
  412. enter := &enterBlock{}
  413. c.p.code[enterPos] = enter
  414. c.leaveScopeBlock(enter)
  415. } else {
  416. c.block = c.block.outer
  417. }
  418. c.popScope()
  419. }
  420. if iter {
  421. c.emit(iterateP)
  422. } else {
  423. c.emit(enumerate)
  424. }
  425. if needResult {
  426. c.emit(clearResult)
  427. }
  428. start := len(c.p.code)
  429. c.block.cont = start
  430. c.emit(nil)
  431. enterIterBlock := c.compileForInto(into, needResult)
  432. if needResult {
  433. c.emit(clearResult)
  434. }
  435. c.compileStatement(body, needResult)
  436. if enterIterBlock != nil {
  437. c.leaveScopeBlock(enterIterBlock)
  438. c.popScope()
  439. }
  440. c.emit(jump(start - len(c.p.code)))
  441. if iter {
  442. c.p.code[start] = iterNext(len(c.p.code) - start)
  443. } else {
  444. c.p.code[start] = enumNext(len(c.p.code) - start)
  445. }
  446. c.emit(enumPop, jump(2))
  447. c.leaveBlock()
  448. c.emit(enumPopClose)
  449. }
  450. func (c *compiler) compileLabeledForInStatement(v *ast.ForInStatement, needResult bool, label unistring.String) {
  451. c.compileLabeledForInOfStatement(v.Into, v.Source, v.Body, false, needResult, label)
  452. }
  453. func (c *compiler) compileForOfStatement(v *ast.ForOfStatement, needResult bool) {
  454. c.compileLabeledForOfStatement(v, needResult, "")
  455. }
  456. func (c *compiler) compileLabeledForOfStatement(v *ast.ForOfStatement, needResult bool, label unistring.String) {
  457. c.compileLabeledForInOfStatement(v.Into, v.Source, v.Body, true, needResult, label)
  458. }
  459. func (c *compiler) compileWhileStatement(v *ast.WhileStatement, needResult bool) {
  460. c.compileLabeledWhileStatement(v, needResult, "")
  461. }
  462. func (c *compiler) compileLabeledWhileStatement(v *ast.WhileStatement, needResult bool, label unistring.String) {
  463. c.block = &block{
  464. typ: blockLoop,
  465. outer: c.block,
  466. label: label,
  467. needResult: needResult,
  468. }
  469. if needResult {
  470. c.emit(clearResult)
  471. }
  472. start := len(c.p.code)
  473. c.block.cont = start
  474. expr := c.compileExpression(v.Test)
  475. testTrue := false
  476. var j int
  477. if expr.constant() {
  478. if t, ex := c.evalConst(expr); ex == nil {
  479. if t.ToBoolean() {
  480. testTrue = true
  481. } else {
  482. c.compileStatementDummy(v.Body)
  483. goto end
  484. }
  485. } else {
  486. c.emitThrow(ex.val)
  487. goto end
  488. }
  489. } else {
  490. expr.emitGetter(true)
  491. j = len(c.p.code)
  492. c.emit(nil)
  493. }
  494. if needResult {
  495. c.emit(clearResult)
  496. }
  497. c.compileStatement(v.Body, needResult)
  498. c.emit(jump(start - len(c.p.code)))
  499. if !testTrue {
  500. c.p.code[j] = jne(len(c.p.code) - j)
  501. }
  502. end:
  503. c.leaveBlock()
  504. }
  505. func (c *compiler) compileEmptyStatement(needResult bool) {
  506. if needResult {
  507. c.emit(clearResult)
  508. }
  509. }
  510. func (c *compiler) compileBranchStatement(v *ast.BranchStatement) {
  511. switch v.Token {
  512. case token.BREAK:
  513. c.compileBreak(v.Label, v.Idx)
  514. case token.CONTINUE:
  515. c.compileContinue(v.Label, v.Idx)
  516. default:
  517. panic(fmt.Errorf("Unknown branch statement token: %s", v.Token.String()))
  518. }
  519. }
  520. func (c *compiler) findBranchBlock(st *ast.BranchStatement) *block {
  521. switch st.Token {
  522. case token.BREAK:
  523. return c.findBreakBlock(st.Label, true)
  524. case token.CONTINUE:
  525. return c.findBreakBlock(st.Label, false)
  526. }
  527. return nil
  528. }
  529. func (c *compiler) findBreakBlock(label *ast.Identifier, isBreak bool) (res *block) {
  530. if label != nil {
  531. var found *block
  532. for b := c.block; b != nil; b = b.outer {
  533. if res == nil {
  534. if bb := b.breaking; bb != nil {
  535. res = bb
  536. if isBreak {
  537. return
  538. }
  539. }
  540. }
  541. if b.label == label.Name {
  542. found = b
  543. break
  544. }
  545. }
  546. if !isBreak && found != nil && found.typ != blockLoop && found.typ != blockLoopEnum {
  547. c.throwSyntaxError(int(label.Idx)-1, "Illegal continue statement: '%s' does not denote an iteration statement", label.Name)
  548. }
  549. if res == nil {
  550. res = found
  551. }
  552. } else {
  553. // find the nearest loop or switch (if break)
  554. L:
  555. for b := c.block; b != nil; b = b.outer {
  556. if bb := b.breaking; bb != nil {
  557. return bb
  558. }
  559. switch b.typ {
  560. case blockLoop, blockLoopEnum:
  561. res = b
  562. break L
  563. case blockSwitch:
  564. if isBreak {
  565. res = b
  566. break L
  567. }
  568. }
  569. }
  570. }
  571. return
  572. }
  573. func (c *compiler) emitBlockExitCode(label *ast.Identifier, idx file.Idx, isBreak bool) *block {
  574. block := c.findBreakBlock(label, isBreak)
  575. if block == nil {
  576. c.throwSyntaxError(int(idx)-1, "Could not find block")
  577. panic("unreachable")
  578. }
  579. L:
  580. for b := c.block; b != block; b = b.outer {
  581. switch b.typ {
  582. case blockIterScope:
  583. if !isBreak && b.outer == block {
  584. break L
  585. }
  586. fallthrough
  587. case blockScope:
  588. b.breaks = append(b.breaks, len(c.p.code))
  589. c.emit(nil)
  590. case blockTry:
  591. c.emit(halt)
  592. case blockWith:
  593. c.emit(leaveWith)
  594. case blockLoopEnum:
  595. c.emit(enumPopClose)
  596. }
  597. }
  598. return block
  599. }
  600. func (c *compiler) compileBreak(label *ast.Identifier, idx file.Idx) {
  601. block := c.emitBlockExitCode(label, idx, true)
  602. block.breaks = append(block.breaks, len(c.p.code))
  603. c.emit(nil)
  604. }
  605. func (c *compiler) compileContinue(label *ast.Identifier, idx file.Idx) {
  606. block := c.emitBlockExitCode(label, idx, false)
  607. block.conts = append(block.conts, len(c.p.code))
  608. c.emit(nil)
  609. }
  610. func (c *compiler) compileIfBody(s ast.Statement, needResult bool) {
  611. if !c.scope.strict {
  612. if s, ok := s.(*ast.FunctionDeclaration); ok {
  613. c.compileFunction(s)
  614. if needResult {
  615. c.emit(clearResult)
  616. }
  617. return
  618. }
  619. }
  620. c.compileStatement(s, needResult)
  621. }
  622. func (c *compiler) compileIfBodyDummy(s ast.Statement) {
  623. leave := c.enterDummyMode()
  624. defer leave()
  625. c.compileIfBody(s, false)
  626. }
  627. func (c *compiler) compileIfStatement(v *ast.IfStatement, needResult bool) {
  628. test := c.compileExpression(v.Test)
  629. if needResult {
  630. c.emit(clearResult)
  631. }
  632. if test.constant() {
  633. r, ex := c.evalConst(test)
  634. if ex != nil {
  635. test.addSrcMap()
  636. c.emitThrow(ex.val)
  637. return
  638. }
  639. if r.ToBoolean() {
  640. c.compileIfBody(v.Consequent, needResult)
  641. if v.Alternate != nil {
  642. c.compileIfBodyDummy(v.Alternate)
  643. }
  644. } else {
  645. c.compileIfBodyDummy(v.Consequent)
  646. if v.Alternate != nil {
  647. c.compileIfBody(v.Alternate, needResult)
  648. } else {
  649. if needResult {
  650. c.emit(clearResult)
  651. }
  652. }
  653. }
  654. return
  655. }
  656. test.emitGetter(true)
  657. jmp := len(c.p.code)
  658. c.emit(nil)
  659. c.compileIfBody(v.Consequent, needResult)
  660. if v.Alternate != nil {
  661. jmp1 := len(c.p.code)
  662. c.emit(nil)
  663. c.p.code[jmp] = jne(len(c.p.code) - jmp)
  664. c.compileIfBody(v.Alternate, needResult)
  665. c.p.code[jmp1] = jump(len(c.p.code) - jmp1)
  666. } else {
  667. if needResult {
  668. c.emit(jump(2))
  669. c.p.code[jmp] = jne(len(c.p.code) - jmp)
  670. c.emit(clearResult)
  671. } else {
  672. c.p.code[jmp] = jne(len(c.p.code) - jmp)
  673. }
  674. }
  675. }
  676. func (c *compiler) compileReturnStatement(v *ast.ReturnStatement) {
  677. if v.Argument != nil {
  678. c.compileExpression(v.Argument).emitGetter(true)
  679. } else {
  680. c.emit(loadUndef)
  681. }
  682. for b := c.block; b != nil; b = b.outer {
  683. switch b.typ {
  684. case blockTry:
  685. c.emit(halt)
  686. case blockLoopEnum:
  687. c.emit(enumPopClose)
  688. }
  689. }
  690. c.emit(ret)
  691. }
  692. func (c *compiler) checkVarConflict(name unistring.String, offset int) {
  693. for sc := c.scope; sc != nil; sc = sc.outer {
  694. if b, exists := sc.boundNames[name]; exists && !b.isVar && !(b.isArg && sc != c.scope) {
  695. c.throwSyntaxError(offset, "Identifier '%s' has already been declared", name)
  696. }
  697. if sc.function {
  698. break
  699. }
  700. }
  701. }
  702. func (c *compiler) emitVarAssign(name unistring.String, offset int, init compiledExpr) {
  703. c.checkVarConflict(name, offset)
  704. if init != nil {
  705. c.emitVarRef(name, offset)
  706. c.emitNamed(init, name)
  707. c.emit(putValueP)
  708. }
  709. }
  710. func (c *compiler) compileVarBinding(expr *ast.Binding) {
  711. switch target := expr.Target.(type) {
  712. case *ast.Identifier:
  713. c.emitVarAssign(target.Name, int(target.Idx)-1, c.compileExpression(expr.Initializer))
  714. case ast.Pattern:
  715. c.compileExpression(expr.Initializer).emitGetter(true)
  716. c.emitPattern(target, c.emitPatternVarAssign, false)
  717. default:
  718. c.throwSyntaxError(int(target.Idx0()-1), "unsupported variable binding target: %T", target)
  719. }
  720. }
  721. func (c *compiler) emitLexicalAssign(name unistring.String, offset int, init compiledExpr, isConst bool) {
  722. b := c.scope.boundNames[name]
  723. if b == nil {
  724. panic("Lexical declaration for an unbound name")
  725. }
  726. if init != nil {
  727. c.emitNamed(init, name)
  728. } else {
  729. if isConst {
  730. c.throwSyntaxError(offset, "Missing initializer in const declaration")
  731. }
  732. c.emit(loadUndef)
  733. }
  734. if c.scope.outer != nil {
  735. b.emitInit()
  736. } else {
  737. c.emit(initGlobal(name))
  738. }
  739. }
  740. func (c *compiler) emitPatternVarAssign(target, init compiledExpr) {
  741. id := target.(*compiledIdentifierExpr)
  742. c.emitVarAssign(id.name, id.offset, init)
  743. }
  744. func (c *compiler) emitPatternLexicalAssign(target, init compiledExpr, isConst bool) {
  745. id := target.(*compiledIdentifierExpr)
  746. c.emitLexicalAssign(id.name, id.offset, init, isConst)
  747. }
  748. func (c *compiler) emitPatternAssign(target, init compiledExpr) {
  749. target.emitRef()
  750. if id, ok := target.(*compiledIdentifierExpr); ok {
  751. c.emitNamed(init, id.name)
  752. } else {
  753. init.emitGetter(true)
  754. }
  755. c.emit(putValueP)
  756. }
  757. func (c *compiler) compileLexicalBinding(expr *ast.Binding, isConst bool) {
  758. switch target := expr.Target.(type) {
  759. case *ast.Identifier:
  760. c.emitLexicalAssign(target.Name, int(target.Idx)-1, c.compileExpression(expr.Initializer), isConst)
  761. case ast.Pattern:
  762. c.compileExpression(expr.Initializer).emitGetter(true)
  763. c.emitPattern(target, func(target, init compiledExpr) {
  764. c.emitPatternLexicalAssign(target, init, isConst)
  765. }, false)
  766. default:
  767. c.throwSyntaxError(int(target.Idx0()-1), "unsupported lexical binding target: %T", target)
  768. }
  769. }
  770. func (c *compiler) compileVariableStatement(v *ast.VariableStatement) {
  771. for _, expr := range v.List {
  772. c.compileVarBinding(expr)
  773. }
  774. }
  775. func (c *compiler) compileLexicalDeclaration(v *ast.LexicalDeclaration) {
  776. isConst := v.Token == token.CONST
  777. for _, e := range v.List {
  778. c.compileLexicalBinding(e, isConst)
  779. }
  780. }
  781. func (c *compiler) isEmptyResult(st ast.Statement) bool {
  782. switch st := st.(type) {
  783. case *ast.EmptyStatement, *ast.VariableStatement, *ast.LexicalDeclaration, *ast.FunctionDeclaration,
  784. *ast.BranchStatement, *ast.DebuggerStatement:
  785. return true
  786. case *ast.LabelledStatement:
  787. return c.isEmptyResult(st.Statement)
  788. case *ast.BlockStatement:
  789. for _, s := range st.List {
  790. if _, ok := s.(*ast.BranchStatement); ok {
  791. return true
  792. }
  793. if !c.isEmptyResult(s) {
  794. return false
  795. }
  796. }
  797. return true
  798. }
  799. return false
  800. }
  801. func (c *compiler) scanStatements(list []ast.Statement) (lastProducingIdx int, breakingBlock *block) {
  802. lastProducingIdx = -1
  803. for i, st := range list {
  804. if bs, ok := st.(*ast.BranchStatement); ok {
  805. if blk := c.findBranchBlock(bs); blk != nil {
  806. breakingBlock = blk
  807. }
  808. break
  809. }
  810. if !c.isEmptyResult(st) {
  811. lastProducingIdx = i
  812. }
  813. }
  814. return
  815. }
  816. func (c *compiler) compileStatementsNeedResult(list []ast.Statement, lastProducingIdx int) {
  817. if lastProducingIdx >= 0 {
  818. for _, st := range list[:lastProducingIdx] {
  819. if _, ok := st.(*ast.FunctionDeclaration); ok {
  820. continue
  821. }
  822. c.compileStatement(st, false)
  823. }
  824. c.compileStatement(list[lastProducingIdx], true)
  825. }
  826. var leave func()
  827. defer func() {
  828. if leave != nil {
  829. leave()
  830. }
  831. }()
  832. for _, st := range list[lastProducingIdx+1:] {
  833. if _, ok := st.(*ast.FunctionDeclaration); ok {
  834. continue
  835. }
  836. c.compileStatement(st, false)
  837. if leave == nil {
  838. if _, ok := st.(*ast.BranchStatement); ok {
  839. leave = c.enterDummyMode()
  840. }
  841. }
  842. }
  843. }
  844. func (c *compiler) compileStatements(list []ast.Statement, needResult bool) {
  845. lastProducingIdx, blk := c.scanStatements(list)
  846. if blk != nil {
  847. needResult = blk.needResult
  848. }
  849. if needResult {
  850. c.compileStatementsNeedResult(list, lastProducingIdx)
  851. return
  852. }
  853. for _, st := range list {
  854. if _, ok := st.(*ast.FunctionDeclaration); ok {
  855. continue
  856. }
  857. c.compileStatement(st, false)
  858. }
  859. }
  860. func (c *compiler) compileGenericLabeledStatement(v ast.Statement, needResult bool, label unistring.String) {
  861. c.block = &block{
  862. typ: blockLabel,
  863. outer: c.block,
  864. label: label,
  865. needResult: needResult,
  866. }
  867. c.compileStatement(v, needResult)
  868. c.leaveBlock()
  869. }
  870. func (c *compiler) compileBlockStatement(v *ast.BlockStatement, needResult bool) {
  871. var scopeDeclared bool
  872. funcs := c.extractFunctions(v.List)
  873. if len(funcs) > 0 {
  874. c.newBlockScope()
  875. scopeDeclared = true
  876. }
  877. c.createFunctionBindings(funcs)
  878. scopeDeclared = c.compileLexicalDeclarations(v.List, scopeDeclared)
  879. var enter *enterBlock
  880. if scopeDeclared {
  881. c.block = &block{
  882. outer: c.block,
  883. typ: blockScope,
  884. needResult: needResult,
  885. }
  886. enter = &enterBlock{}
  887. c.emit(enter)
  888. }
  889. c.compileFunctions(funcs)
  890. c.compileStatements(v.List, needResult)
  891. if scopeDeclared {
  892. c.leaveScopeBlock(enter)
  893. c.popScope()
  894. }
  895. }
  896. func (c *compiler) compileExpressionStatement(v *ast.ExpressionStatement, needResult bool) {
  897. expr := c.compileExpression(v.Expression)
  898. if expr.constant() {
  899. c.emitConst(expr, needResult)
  900. } else {
  901. expr.emitGetter(needResult)
  902. }
  903. if needResult {
  904. c.emit(saveResult)
  905. }
  906. }
  907. func (c *compiler) compileWithStatement(v *ast.WithStatement, needResult bool) {
  908. if c.scope.strict {
  909. c.throwSyntaxError(int(v.With)-1, "Strict mode code may not include a with statement")
  910. return
  911. }
  912. c.compileExpression(v.Object).emitGetter(true)
  913. c.emit(enterWith)
  914. c.block = &block{
  915. outer: c.block,
  916. typ: blockWith,
  917. needResult: needResult,
  918. }
  919. c.newBlockScope()
  920. c.scope.dynamic = true
  921. c.compileStatement(v.Body, needResult)
  922. c.emit(leaveWith)
  923. c.leaveBlock()
  924. c.popScope()
  925. }
  926. func (c *compiler) compileSwitchStatement(v *ast.SwitchStatement, needResult bool) {
  927. c.block = &block{
  928. typ: blockSwitch,
  929. outer: c.block,
  930. needResult: needResult,
  931. }
  932. c.compileExpression(v.Discriminant).emitGetter(true)
  933. var funcs []*ast.FunctionDeclaration
  934. for _, s := range v.Body {
  935. f := c.extractFunctions(s.Consequent)
  936. funcs = append(funcs, f...)
  937. }
  938. var scopeDeclared bool
  939. if len(funcs) > 0 {
  940. c.newBlockScope()
  941. scopeDeclared = true
  942. c.createFunctionBindings(funcs)
  943. }
  944. for _, s := range v.Body {
  945. scopeDeclared = c.compileLexicalDeclarations(s.Consequent, scopeDeclared)
  946. }
  947. var enter *enterBlock
  948. var db *binding
  949. if scopeDeclared {
  950. c.block = &block{
  951. typ: blockScope,
  952. outer: c.block,
  953. needResult: needResult,
  954. }
  955. enter = &enterBlock{}
  956. c.emit(enter)
  957. // create anonymous variable for the discriminant
  958. bindings := c.scope.bindings
  959. var bb []*binding
  960. if cap(bindings) == len(bindings) {
  961. bb = make([]*binding, len(bindings)+1)
  962. } else {
  963. bb = bindings[:len(bindings)+1]
  964. }
  965. copy(bb[1:], bindings)
  966. db = &binding{
  967. scope: c.scope,
  968. isConst: true,
  969. isStrict: true,
  970. }
  971. bb[0] = db
  972. c.scope.bindings = bb
  973. }
  974. c.compileFunctions(funcs)
  975. if needResult {
  976. c.emit(clearResult)
  977. }
  978. jumps := make([]int, len(v.Body))
  979. for i, s := range v.Body {
  980. if s.Test != nil {
  981. if db != nil {
  982. db.emitGet()
  983. } else {
  984. c.emit(dup)
  985. }
  986. c.compileExpression(s.Test).emitGetter(true)
  987. c.emit(op_strict_eq)
  988. if db != nil {
  989. c.emit(jne(2))
  990. } else {
  991. c.emit(jne(3), pop)
  992. }
  993. jumps[i] = len(c.p.code)
  994. c.emit(nil)
  995. }
  996. }
  997. if db == nil {
  998. c.emit(pop)
  999. }
  1000. jumpNoMatch := -1
  1001. if v.Default != -1 {
  1002. if v.Default != 0 {
  1003. jumps[v.Default] = len(c.p.code)
  1004. c.emit(nil)
  1005. }
  1006. } else {
  1007. jumpNoMatch = len(c.p.code)
  1008. c.emit(nil)
  1009. }
  1010. for i, s := range v.Body {
  1011. if s.Test != nil || i != 0 {
  1012. c.p.code[jumps[i]] = jump(len(c.p.code) - jumps[i])
  1013. }
  1014. c.compileStatements(s.Consequent, needResult)
  1015. }
  1016. if jumpNoMatch != -1 {
  1017. c.p.code[jumpNoMatch] = jump(len(c.p.code) - jumpNoMatch)
  1018. }
  1019. if enter != nil {
  1020. c.leaveScopeBlock(enter)
  1021. enter.stackSize--
  1022. c.popScope()
  1023. }
  1024. c.leaveBlock()
  1025. }