statement.go 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  1. package parser
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "os"
  6. "strings"
  7. "github.com/dop251/goja/ast"
  8. "github.com/dop251/goja/file"
  9. "github.com/dop251/goja/token"
  10. "github.com/go-sourcemap/sourcemap"
  11. )
  12. func (self *_parser) parseBlockStatement() *ast.BlockStatement {
  13. node := &ast.BlockStatement{}
  14. node.LeftBrace = self.expect(token.LEFT_BRACE)
  15. node.List = self.parseStatementList()
  16. node.RightBrace = self.expect(token.RIGHT_BRACE)
  17. return node
  18. }
  19. func (self *_parser) parseEmptyStatement() ast.Statement {
  20. idx := self.expect(token.SEMICOLON)
  21. return &ast.EmptyStatement{Semicolon: idx}
  22. }
  23. func (self *_parser) parseStatementList() (list []ast.Statement) {
  24. for self.token != token.RIGHT_BRACE && self.token != token.EOF {
  25. self.scope.allowLet = true
  26. list = append(list, self.parseStatement())
  27. }
  28. return
  29. }
  30. func (self *_parser) parseStatement() ast.Statement {
  31. if self.token == token.EOF {
  32. self.errorUnexpectedToken(self.token)
  33. return &ast.BadStatement{From: self.idx, To: self.idx + 1}
  34. }
  35. switch self.token {
  36. case token.SEMICOLON:
  37. return self.parseEmptyStatement()
  38. case token.LEFT_BRACE:
  39. return self.parseBlockStatement()
  40. case token.IF:
  41. return self.parseIfStatement()
  42. case token.DO:
  43. return self.parseDoWhileStatement()
  44. case token.WHILE:
  45. return self.parseWhileStatement()
  46. case token.FOR:
  47. return self.parseForOrForInStatement()
  48. case token.BREAK:
  49. return self.parseBreakStatement()
  50. case token.CONTINUE:
  51. return self.parseContinueStatement()
  52. case token.DEBUGGER:
  53. return self.parseDebuggerStatement()
  54. case token.WITH:
  55. return self.parseWithStatement()
  56. case token.VAR:
  57. return self.parseVariableStatement()
  58. case token.LET:
  59. tok := self.peek()
  60. if tok == token.LEFT_BRACKET || self.scope.allowLet && (token.IsId(tok) || tok == token.LEFT_BRACE) {
  61. return self.parseLexicalDeclaration(self.token)
  62. }
  63. self.insertSemicolon = true
  64. case token.CONST:
  65. return self.parseLexicalDeclaration(self.token)
  66. case token.ASYNC:
  67. if f := self.parseMaybeAsyncFunction(true); f != nil {
  68. return &ast.FunctionDeclaration{
  69. Function: f,
  70. }
  71. }
  72. case token.FUNCTION:
  73. return &ast.FunctionDeclaration{
  74. Function: self.parseFunction(true, false, self.idx),
  75. }
  76. case token.CLASS:
  77. return &ast.ClassDeclaration{
  78. Class: self.parseClass(true),
  79. }
  80. case token.SWITCH:
  81. return self.parseSwitchStatement()
  82. case token.RETURN:
  83. return self.parseReturnStatement()
  84. case token.THROW:
  85. return self.parseThrowStatement()
  86. case token.TRY:
  87. return self.parseTryStatement()
  88. }
  89. expression := self.parseExpression()
  90. if identifier, isIdentifier := expression.(*ast.Identifier); isIdentifier && self.token == token.COLON {
  91. // LabelledStatement
  92. colon := self.idx
  93. self.next() // :
  94. label := identifier.Name
  95. for _, value := range self.scope.labels {
  96. if label == value {
  97. self.error(identifier.Idx0(), "Label '%s' already exists", label)
  98. }
  99. }
  100. self.scope.labels = append(self.scope.labels, label) // Push the label
  101. self.scope.allowLet = false
  102. statement := self.parseStatement()
  103. self.scope.labels = self.scope.labels[:len(self.scope.labels)-1] // Pop the label
  104. return &ast.LabelledStatement{
  105. Label: identifier,
  106. Colon: colon,
  107. Statement: statement,
  108. }
  109. }
  110. self.optionalSemicolon()
  111. return &ast.ExpressionStatement{
  112. Expression: expression,
  113. }
  114. }
  115. func (self *_parser) parseTryStatement() ast.Statement {
  116. node := &ast.TryStatement{
  117. Try: self.expect(token.TRY),
  118. Body: self.parseBlockStatement(),
  119. }
  120. if self.token == token.CATCH {
  121. catch := self.idx
  122. self.next()
  123. var parameter ast.BindingTarget
  124. if self.token == token.LEFT_PARENTHESIS {
  125. self.next()
  126. parameter = self.parseBindingTarget()
  127. self.expect(token.RIGHT_PARENTHESIS)
  128. }
  129. node.Catch = &ast.CatchStatement{
  130. Catch: catch,
  131. Parameter: parameter,
  132. Body: self.parseBlockStatement(),
  133. }
  134. }
  135. if self.token == token.FINALLY {
  136. self.next()
  137. node.Finally = self.parseBlockStatement()
  138. }
  139. if node.Catch == nil && node.Finally == nil {
  140. self.error(node.Try, "Missing catch or finally after try")
  141. return &ast.BadStatement{From: node.Try, To: node.Body.Idx1()}
  142. }
  143. return node
  144. }
  145. func (self *_parser) parseFunctionParameterList() *ast.ParameterList {
  146. opening := self.expect(token.LEFT_PARENTHESIS)
  147. var list []*ast.Binding
  148. var rest ast.Expression
  149. if !self.scope.inFuncParams {
  150. self.scope.inFuncParams = true
  151. defer func() {
  152. self.scope.inFuncParams = false
  153. }()
  154. }
  155. for self.token != token.RIGHT_PARENTHESIS && self.token != token.EOF {
  156. if self.token == token.ELLIPSIS {
  157. self.next()
  158. rest = self.reinterpretAsDestructBindingTarget(self.parseAssignmentExpression())
  159. break
  160. }
  161. self.parseVariableDeclaration(&list)
  162. if self.token != token.RIGHT_PARENTHESIS {
  163. self.expect(token.COMMA)
  164. }
  165. }
  166. closing := self.expect(token.RIGHT_PARENTHESIS)
  167. return &ast.ParameterList{
  168. Opening: opening,
  169. List: list,
  170. Rest: rest,
  171. Closing: closing,
  172. }
  173. }
  174. func (self *_parser) parseMaybeAsyncFunction(declaration bool) *ast.FunctionLiteral {
  175. if self.peek() == token.FUNCTION {
  176. idx := self.idx
  177. self.next()
  178. return self.parseFunction(declaration, true, idx)
  179. }
  180. return nil
  181. }
  182. func (self *_parser) parseFunction(declaration, async bool, start file.Idx) *ast.FunctionLiteral {
  183. node := &ast.FunctionLiteral{
  184. Function: start,
  185. Async: async,
  186. }
  187. self.expect(token.FUNCTION)
  188. if self.token == token.MULTIPLY {
  189. node.Generator = true
  190. self.next()
  191. }
  192. if !declaration {
  193. if async != self.scope.allowAwait {
  194. self.scope.allowAwait = async
  195. defer func() {
  196. self.scope.allowAwait = !async
  197. }()
  198. }
  199. if node.Generator != self.scope.allowYield {
  200. self.scope.allowYield = node.Generator
  201. defer func() {
  202. self.scope.allowYield = !node.Generator
  203. }()
  204. }
  205. }
  206. self.tokenToBindingId()
  207. var name *ast.Identifier
  208. if self.token == token.IDENTIFIER {
  209. name = self.parseIdentifier()
  210. } else if declaration {
  211. // Use expect error handling
  212. self.expect(token.IDENTIFIER)
  213. }
  214. node.Name = name
  215. if declaration {
  216. if async != self.scope.allowAwait {
  217. self.scope.allowAwait = async
  218. defer func() {
  219. self.scope.allowAwait = !async
  220. }()
  221. }
  222. if node.Generator != self.scope.allowYield {
  223. self.scope.allowYield = node.Generator
  224. defer func() {
  225. self.scope.allowYield = !node.Generator
  226. }()
  227. }
  228. }
  229. node.ParameterList = self.parseFunctionParameterList()
  230. node.Body, node.DeclarationList = self.parseFunctionBlock(async, async, self.scope.allowYield)
  231. node.Source = self.slice(node.Idx0(), node.Idx1())
  232. return node
  233. }
  234. func (self *_parser) parseFunctionBlock(async, allowAwait, allowYield bool) (body *ast.BlockStatement, declarationList []*ast.VariableDeclaration) {
  235. self.openScope()
  236. self.scope.inFunction = true
  237. self.scope.inAsync = async
  238. self.scope.allowAwait = allowAwait
  239. self.scope.allowYield = allowYield
  240. defer self.closeScope()
  241. body = self.parseBlockStatement()
  242. declarationList = self.scope.declarationList
  243. return
  244. }
  245. func (self *_parser) parseArrowFunctionBody(async bool) (ast.ConciseBody, []*ast.VariableDeclaration) {
  246. if self.token == token.LEFT_BRACE {
  247. return self.parseFunctionBlock(async, async, false)
  248. }
  249. if async != self.scope.inAsync || async != self.scope.allowAwait {
  250. inAsync := self.scope.inAsync
  251. allowAwait := self.scope.allowAwait
  252. self.scope.inAsync = async
  253. self.scope.allowAwait = async
  254. allowYield := self.scope.allowYield
  255. self.scope.allowYield = false
  256. defer func() {
  257. self.scope.inAsync = inAsync
  258. self.scope.allowAwait = allowAwait
  259. self.scope.allowYield = allowYield
  260. }()
  261. }
  262. return &ast.ExpressionBody{
  263. Expression: self.parseAssignmentExpression(),
  264. }, nil
  265. }
  266. func (self *_parser) parseClass(declaration bool) *ast.ClassLiteral {
  267. if !self.scope.allowLet && self.token == token.CLASS {
  268. self.errorUnexpectedToken(token.CLASS)
  269. }
  270. node := &ast.ClassLiteral{
  271. Class: self.expect(token.CLASS),
  272. }
  273. self.tokenToBindingId()
  274. var name *ast.Identifier
  275. if self.token == token.IDENTIFIER {
  276. name = self.parseIdentifier()
  277. } else if declaration {
  278. // Use expect error handling
  279. self.expect(token.IDENTIFIER)
  280. }
  281. node.Name = name
  282. if self.token != token.LEFT_BRACE {
  283. self.expect(token.EXTENDS)
  284. node.SuperClass = self.parseLeftHandSideExpressionAllowCall()
  285. }
  286. self.expect(token.LEFT_BRACE)
  287. for self.token != token.RIGHT_BRACE && self.token != token.EOF {
  288. if self.token == token.SEMICOLON {
  289. self.next()
  290. continue
  291. }
  292. start := self.idx
  293. static := false
  294. if self.token == token.STATIC {
  295. switch self.peek() {
  296. case token.ASSIGN, token.SEMICOLON, token.RIGHT_BRACE, token.LEFT_PARENTHESIS:
  297. // treat as identifier
  298. default:
  299. self.next()
  300. if self.token == token.LEFT_BRACE {
  301. b := &ast.ClassStaticBlock{
  302. Static: start,
  303. }
  304. b.Block, b.DeclarationList = self.parseFunctionBlock(false, true, false)
  305. b.Source = self.slice(b.Block.LeftBrace, b.Block.Idx1())
  306. node.Body = append(node.Body, b)
  307. continue
  308. }
  309. static = true
  310. }
  311. }
  312. var kind ast.PropertyKind
  313. var async bool
  314. methodBodyStart := self.idx
  315. if self.literal == "get" || self.literal == "set" {
  316. if tok := self.peek(); tok != token.SEMICOLON && tok != token.LEFT_PARENTHESIS {
  317. if self.literal == "get" {
  318. kind = ast.PropertyKindGet
  319. } else {
  320. kind = ast.PropertyKindSet
  321. }
  322. self.next()
  323. }
  324. } else if self.token == token.ASYNC {
  325. if tok := self.peek(); tok != token.SEMICOLON && tok != token.LEFT_PARENTHESIS {
  326. async = true
  327. kind = ast.PropertyKindMethod
  328. self.next()
  329. }
  330. }
  331. generator := false
  332. if self.token == token.MULTIPLY && (kind == "" || kind == ast.PropertyKindMethod) {
  333. generator = true
  334. kind = ast.PropertyKindMethod
  335. self.next()
  336. }
  337. _, keyName, value, tkn := self.parseObjectPropertyKey()
  338. if value == nil {
  339. continue
  340. }
  341. computed := tkn == token.ILLEGAL
  342. _, private := value.(*ast.PrivateIdentifier)
  343. if static && !private && keyName == "prototype" {
  344. self.error(value.Idx0(), "Classes may not have a static property named 'prototype'")
  345. }
  346. if kind == "" && self.token == token.LEFT_PARENTHESIS {
  347. kind = ast.PropertyKindMethod
  348. }
  349. if kind != "" {
  350. // method
  351. if keyName == "constructor" && !computed {
  352. if !static {
  353. if kind != ast.PropertyKindMethod {
  354. self.error(value.Idx0(), "Class constructor may not be an accessor")
  355. } else if async {
  356. self.error(value.Idx0(), "Class constructor may not be an async method")
  357. } else if generator {
  358. self.error(value.Idx0(), "Class constructor may not be a generator")
  359. }
  360. } else if private {
  361. self.error(value.Idx0(), "Class constructor may not be a private method")
  362. }
  363. }
  364. md := &ast.MethodDefinition{
  365. Idx: start,
  366. Key: value,
  367. Kind: kind,
  368. Body: self.parseMethodDefinition(methodBodyStart, kind, generator, async),
  369. Static: static,
  370. Computed: computed,
  371. }
  372. node.Body = append(node.Body, md)
  373. } else {
  374. // field
  375. isCtor := !computed && keyName == "constructor"
  376. if !isCtor {
  377. if name, ok := value.(*ast.PrivateIdentifier); ok {
  378. isCtor = name.Name == "constructor"
  379. }
  380. }
  381. if isCtor {
  382. self.error(value.Idx0(), "Classes may not have a field named 'constructor'")
  383. }
  384. var initializer ast.Expression
  385. if self.token == token.ASSIGN {
  386. self.next()
  387. initializer = self.parseExpression()
  388. }
  389. if !self.implicitSemicolon && self.token != token.SEMICOLON && self.token != token.RIGHT_BRACE {
  390. self.errorUnexpectedToken(self.token)
  391. break
  392. }
  393. node.Body = append(node.Body, &ast.FieldDefinition{
  394. Idx: start,
  395. Key: value,
  396. Initializer: initializer,
  397. Static: static,
  398. Computed: computed,
  399. })
  400. }
  401. }
  402. node.RightBrace = self.expect(token.RIGHT_BRACE)
  403. node.Source = self.slice(node.Class, node.RightBrace+1)
  404. return node
  405. }
  406. func (self *_parser) parseDebuggerStatement() ast.Statement {
  407. idx := self.expect(token.DEBUGGER)
  408. node := &ast.DebuggerStatement{
  409. Debugger: idx,
  410. }
  411. self.semicolon()
  412. return node
  413. }
  414. func (self *_parser) parseReturnStatement() ast.Statement {
  415. idx := self.expect(token.RETURN)
  416. if !self.scope.inFunction {
  417. self.error(idx, "Illegal return statement")
  418. self.nextStatement()
  419. return &ast.BadStatement{From: idx, To: self.idx}
  420. }
  421. node := &ast.ReturnStatement{
  422. Return: idx,
  423. }
  424. if !self.implicitSemicolon && self.token != token.SEMICOLON && self.token != token.RIGHT_BRACE && self.token != token.EOF {
  425. node.Argument = self.parseExpression()
  426. }
  427. self.semicolon()
  428. return node
  429. }
  430. func (self *_parser) parseThrowStatement() ast.Statement {
  431. idx := self.expect(token.THROW)
  432. if self.implicitSemicolon {
  433. if self.chr == -1 { // Hackish
  434. self.error(idx, "Unexpected end of input")
  435. } else {
  436. self.error(idx, "Illegal newline after throw")
  437. }
  438. self.nextStatement()
  439. return &ast.BadStatement{From: idx, To: self.idx}
  440. }
  441. node := &ast.ThrowStatement{
  442. Throw: idx,
  443. Argument: self.parseExpression(),
  444. }
  445. self.semicolon()
  446. return node
  447. }
  448. func (self *_parser) parseSwitchStatement() ast.Statement {
  449. idx := self.expect(token.SWITCH)
  450. self.expect(token.LEFT_PARENTHESIS)
  451. node := &ast.SwitchStatement{
  452. Switch: idx,
  453. Discriminant: self.parseExpression(),
  454. Default: -1,
  455. }
  456. self.expect(token.RIGHT_PARENTHESIS)
  457. self.expect(token.LEFT_BRACE)
  458. inSwitch := self.scope.inSwitch
  459. self.scope.inSwitch = true
  460. defer func() {
  461. self.scope.inSwitch = inSwitch
  462. }()
  463. for index := 0; self.token != token.EOF; index++ {
  464. if self.token == token.RIGHT_BRACE {
  465. node.RightBrace = self.idx
  466. self.next()
  467. break
  468. }
  469. clause := self.parseCaseStatement()
  470. if clause.Test == nil {
  471. if node.Default != -1 {
  472. self.error(clause.Case, "Already saw a default in switch")
  473. }
  474. node.Default = index
  475. }
  476. node.Body = append(node.Body, clause)
  477. }
  478. return node
  479. }
  480. func (self *_parser) parseWithStatement() ast.Statement {
  481. node := &ast.WithStatement{}
  482. node.With = self.expect(token.WITH)
  483. self.expect(token.LEFT_PARENTHESIS)
  484. node.Object = self.parseExpression()
  485. self.expect(token.RIGHT_PARENTHESIS)
  486. self.scope.allowLet = false
  487. node.Body = self.parseStatement()
  488. return node
  489. }
  490. func (self *_parser) parseCaseStatement() *ast.CaseStatement {
  491. node := &ast.CaseStatement{
  492. Case: self.idx,
  493. }
  494. if self.token == token.DEFAULT {
  495. self.next()
  496. } else {
  497. self.expect(token.CASE)
  498. node.Test = self.parseExpression()
  499. }
  500. self.expect(token.COLON)
  501. for {
  502. if self.token == token.EOF ||
  503. self.token == token.RIGHT_BRACE ||
  504. self.token == token.CASE ||
  505. self.token == token.DEFAULT {
  506. break
  507. }
  508. self.scope.allowLet = true
  509. node.Consequent = append(node.Consequent, self.parseStatement())
  510. }
  511. return node
  512. }
  513. func (self *_parser) parseIterationStatement() ast.Statement {
  514. inIteration := self.scope.inIteration
  515. self.scope.inIteration = true
  516. defer func() {
  517. self.scope.inIteration = inIteration
  518. }()
  519. self.scope.allowLet = false
  520. return self.parseStatement()
  521. }
  522. func (self *_parser) parseForIn(idx file.Idx, into ast.ForInto) *ast.ForInStatement {
  523. // Already have consumed "<into> in"
  524. source := self.parseExpression()
  525. self.expect(token.RIGHT_PARENTHESIS)
  526. return &ast.ForInStatement{
  527. For: idx,
  528. Into: into,
  529. Source: source,
  530. Body: self.parseIterationStatement(),
  531. }
  532. }
  533. func (self *_parser) parseForOf(idx file.Idx, into ast.ForInto) *ast.ForOfStatement {
  534. // Already have consumed "<into> of"
  535. source := self.parseAssignmentExpression()
  536. self.expect(token.RIGHT_PARENTHESIS)
  537. return &ast.ForOfStatement{
  538. For: idx,
  539. Into: into,
  540. Source: source,
  541. Body: self.parseIterationStatement(),
  542. }
  543. }
  544. func (self *_parser) parseFor(idx file.Idx, initializer ast.ForLoopInitializer) *ast.ForStatement {
  545. // Already have consumed "<initializer> ;"
  546. var test, update ast.Expression
  547. if self.token != token.SEMICOLON {
  548. test = self.parseExpression()
  549. }
  550. self.expect(token.SEMICOLON)
  551. if self.token != token.RIGHT_PARENTHESIS {
  552. update = self.parseExpression()
  553. }
  554. self.expect(token.RIGHT_PARENTHESIS)
  555. return &ast.ForStatement{
  556. For: idx,
  557. Initializer: initializer,
  558. Test: test,
  559. Update: update,
  560. Body: self.parseIterationStatement(),
  561. }
  562. }
  563. func (self *_parser) parseForOrForInStatement() ast.Statement {
  564. idx := self.expect(token.FOR)
  565. self.expect(token.LEFT_PARENTHESIS)
  566. var initializer ast.ForLoopInitializer
  567. forIn := false
  568. forOf := false
  569. var into ast.ForInto
  570. if self.token != token.SEMICOLON {
  571. allowIn := self.scope.allowIn
  572. self.scope.allowIn = false
  573. tok := self.token
  574. if tok == token.LET {
  575. switch self.peek() {
  576. case token.IDENTIFIER, token.LEFT_BRACKET, token.LEFT_BRACE:
  577. default:
  578. tok = token.IDENTIFIER
  579. }
  580. }
  581. if tok == token.VAR || tok == token.LET || tok == token.CONST {
  582. idx := self.idx
  583. self.next()
  584. var list []*ast.Binding
  585. if tok == token.VAR {
  586. list = self.parseVarDeclarationList(idx)
  587. } else {
  588. list = self.parseVariableDeclarationList()
  589. }
  590. if len(list) == 1 {
  591. if self.token == token.IN {
  592. self.next() // in
  593. forIn = true
  594. } else if self.token == token.IDENTIFIER && self.literal == "of" {
  595. self.next()
  596. forOf = true
  597. }
  598. }
  599. if forIn || forOf {
  600. if list[0].Initializer != nil {
  601. self.error(list[0].Initializer.Idx0(), "for-in loop variable declaration may not have an initializer")
  602. }
  603. if tok == token.VAR {
  604. into = &ast.ForIntoVar{
  605. Binding: list[0],
  606. }
  607. } else {
  608. into = &ast.ForDeclaration{
  609. Idx: idx,
  610. IsConst: tok == token.CONST,
  611. Target: list[0].Target,
  612. }
  613. }
  614. } else {
  615. self.ensurePatternInit(list)
  616. if tok == token.VAR {
  617. initializer = &ast.ForLoopInitializerVarDeclList{
  618. List: list,
  619. }
  620. } else {
  621. initializer = &ast.ForLoopInitializerLexicalDecl{
  622. LexicalDeclaration: ast.LexicalDeclaration{
  623. Idx: idx,
  624. Token: tok,
  625. List: list,
  626. },
  627. }
  628. }
  629. }
  630. } else {
  631. expr := self.parseExpression()
  632. if self.token == token.IN {
  633. self.next()
  634. forIn = true
  635. } else if self.token == token.IDENTIFIER && self.literal == "of" {
  636. self.next()
  637. forOf = true
  638. }
  639. if forIn || forOf {
  640. switch e := expr.(type) {
  641. case *ast.Identifier, *ast.DotExpression, *ast.PrivateDotExpression, *ast.BracketExpression, *ast.Binding:
  642. // These are all acceptable
  643. case *ast.ObjectLiteral:
  644. expr = self.reinterpretAsObjectAssignmentPattern(e)
  645. case *ast.ArrayLiteral:
  646. expr = self.reinterpretAsArrayAssignmentPattern(e)
  647. default:
  648. self.error(idx, "Invalid left-hand side in for-in or for-of")
  649. self.nextStatement()
  650. return &ast.BadStatement{From: idx, To: self.idx}
  651. }
  652. into = &ast.ForIntoExpression{
  653. Expression: expr,
  654. }
  655. } else {
  656. initializer = &ast.ForLoopInitializerExpression{
  657. Expression: expr,
  658. }
  659. }
  660. }
  661. self.scope.allowIn = allowIn
  662. }
  663. if forIn {
  664. return self.parseForIn(idx, into)
  665. }
  666. if forOf {
  667. return self.parseForOf(idx, into)
  668. }
  669. self.expect(token.SEMICOLON)
  670. return self.parseFor(idx, initializer)
  671. }
  672. func (self *_parser) ensurePatternInit(list []*ast.Binding) {
  673. for _, item := range list {
  674. if _, ok := item.Target.(ast.Pattern); ok {
  675. if item.Initializer == nil {
  676. self.error(item.Idx1(), "Missing initializer in destructuring declaration")
  677. break
  678. }
  679. }
  680. }
  681. }
  682. func (self *_parser) parseVariableStatement() *ast.VariableStatement {
  683. idx := self.expect(token.VAR)
  684. list := self.parseVarDeclarationList(idx)
  685. self.ensurePatternInit(list)
  686. self.semicolon()
  687. return &ast.VariableStatement{
  688. Var: idx,
  689. List: list,
  690. }
  691. }
  692. func (self *_parser) parseLexicalDeclaration(tok token.Token) *ast.LexicalDeclaration {
  693. idx := self.expect(tok)
  694. if !self.scope.allowLet {
  695. self.error(idx, "Lexical declaration cannot appear in a single-statement context")
  696. }
  697. list := self.parseVariableDeclarationList()
  698. self.ensurePatternInit(list)
  699. self.semicolon()
  700. return &ast.LexicalDeclaration{
  701. Idx: idx,
  702. Token: tok,
  703. List: list,
  704. }
  705. }
  706. func (self *_parser) parseDoWhileStatement() ast.Statement {
  707. inIteration := self.scope.inIteration
  708. self.scope.inIteration = true
  709. defer func() {
  710. self.scope.inIteration = inIteration
  711. }()
  712. node := &ast.DoWhileStatement{}
  713. node.Do = self.expect(token.DO)
  714. if self.token == token.LEFT_BRACE {
  715. node.Body = self.parseBlockStatement()
  716. } else {
  717. self.scope.allowLet = false
  718. node.Body = self.parseStatement()
  719. }
  720. self.expect(token.WHILE)
  721. self.expect(token.LEFT_PARENTHESIS)
  722. node.Test = self.parseExpression()
  723. node.RightParenthesis = self.expect(token.RIGHT_PARENTHESIS)
  724. if self.token == token.SEMICOLON {
  725. self.next()
  726. }
  727. return node
  728. }
  729. func (self *_parser) parseWhileStatement() ast.Statement {
  730. idx := self.expect(token.WHILE)
  731. self.expect(token.LEFT_PARENTHESIS)
  732. node := &ast.WhileStatement{
  733. While: idx,
  734. Test: self.parseExpression(),
  735. }
  736. self.expect(token.RIGHT_PARENTHESIS)
  737. node.Body = self.parseIterationStatement()
  738. return node
  739. }
  740. func (self *_parser) parseIfStatement() ast.Statement {
  741. self.expect(token.IF)
  742. self.expect(token.LEFT_PARENTHESIS)
  743. node := &ast.IfStatement{
  744. Test: self.parseExpression(),
  745. }
  746. self.expect(token.RIGHT_PARENTHESIS)
  747. if self.token == token.LEFT_BRACE {
  748. node.Consequent = self.parseBlockStatement()
  749. } else {
  750. self.scope.allowLet = false
  751. node.Consequent = self.parseStatement()
  752. }
  753. if self.token == token.ELSE {
  754. self.next()
  755. self.scope.allowLet = false
  756. node.Alternate = self.parseStatement()
  757. }
  758. return node
  759. }
  760. func (self *_parser) parseSourceElements() (body []ast.Statement) {
  761. for self.token != token.EOF {
  762. self.scope.allowLet = true
  763. body = append(body, self.parseStatement())
  764. }
  765. return body
  766. }
  767. func (self *_parser) parseProgram() *ast.Program {
  768. prg := &ast.Program{
  769. Body: self.parseSourceElements(),
  770. DeclarationList: self.scope.declarationList,
  771. File: self.file,
  772. }
  773. self.file.SetSourceMap(self.parseSourceMap())
  774. return prg
  775. }
  776. func extractSourceMapLine(str string) string {
  777. for {
  778. p := strings.LastIndexByte(str, '\n')
  779. line := str[p+1:]
  780. if line != "" && line != "})" {
  781. if strings.HasPrefix(line, "//# sourceMappingURL=") {
  782. return line
  783. }
  784. break
  785. }
  786. if p >= 0 {
  787. str = str[:p]
  788. } else {
  789. break
  790. }
  791. }
  792. return ""
  793. }
  794. func (self *_parser) parseSourceMap() *sourcemap.Consumer {
  795. if self.opts.disableSourceMaps {
  796. return nil
  797. }
  798. if smLine := extractSourceMapLine(self.str); smLine != "" {
  799. urlIndex := strings.Index(smLine, "=")
  800. urlStr := smLine[urlIndex+1:]
  801. var data []byte
  802. var err error
  803. if strings.HasPrefix(urlStr, "data:application/json") {
  804. b64Index := strings.Index(urlStr, ",")
  805. b64 := urlStr[b64Index+1:]
  806. data, err = base64.StdEncoding.DecodeString(b64)
  807. } else {
  808. if sourceURL := file.ResolveSourcemapURL(self.file.Name(), urlStr); sourceURL != nil {
  809. if self.opts.sourceMapLoader != nil {
  810. data, err = self.opts.sourceMapLoader(sourceURL.String())
  811. } else {
  812. if sourceURL.Scheme == "" || sourceURL.Scheme == "file" {
  813. data, err = os.ReadFile(sourceURL.Path)
  814. } else {
  815. err = fmt.Errorf("unsupported source map URL scheme: %s", sourceURL.Scheme)
  816. }
  817. }
  818. }
  819. }
  820. if err != nil {
  821. self.error(file.Idx(0), "Could not load source map: %v", err)
  822. return nil
  823. }
  824. if data == nil {
  825. return nil
  826. }
  827. if sm, err := sourcemap.Parse(self.file.Name(), data); err == nil {
  828. return sm
  829. } else {
  830. self.error(file.Idx(0), "Could not parse source map: %v", err)
  831. }
  832. }
  833. return nil
  834. }
  835. func (self *_parser) parseBreakStatement() ast.Statement {
  836. idx := self.expect(token.BREAK)
  837. semicolon := self.implicitSemicolon
  838. if self.token == token.SEMICOLON {
  839. semicolon = true
  840. self.next()
  841. }
  842. if semicolon || self.token == token.RIGHT_BRACE {
  843. self.implicitSemicolon = false
  844. if !self.scope.inIteration && !self.scope.inSwitch {
  845. goto illegal
  846. }
  847. return &ast.BranchStatement{
  848. Idx: idx,
  849. Token: token.BREAK,
  850. }
  851. }
  852. self.tokenToBindingId()
  853. if self.token == token.IDENTIFIER {
  854. identifier := self.parseIdentifier()
  855. if !self.scope.hasLabel(identifier.Name) {
  856. self.error(idx, "Undefined label '%s'", identifier.Name)
  857. return &ast.BadStatement{From: idx, To: identifier.Idx1()}
  858. }
  859. self.semicolon()
  860. return &ast.BranchStatement{
  861. Idx: idx,
  862. Token: token.BREAK,
  863. Label: identifier,
  864. }
  865. }
  866. self.expect(token.IDENTIFIER)
  867. illegal:
  868. self.error(idx, "Illegal break statement")
  869. self.nextStatement()
  870. return &ast.BadStatement{From: idx, To: self.idx}
  871. }
  872. func (self *_parser) parseContinueStatement() ast.Statement {
  873. idx := self.expect(token.CONTINUE)
  874. semicolon := self.implicitSemicolon
  875. if self.token == token.SEMICOLON {
  876. semicolon = true
  877. self.next()
  878. }
  879. if semicolon || self.token == token.RIGHT_BRACE {
  880. self.implicitSemicolon = false
  881. if !self.scope.inIteration {
  882. goto illegal
  883. }
  884. return &ast.BranchStatement{
  885. Idx: idx,
  886. Token: token.CONTINUE,
  887. }
  888. }
  889. self.tokenToBindingId()
  890. if self.token == token.IDENTIFIER {
  891. identifier := self.parseIdentifier()
  892. if !self.scope.hasLabel(identifier.Name) {
  893. self.error(idx, "Undefined label '%s'", identifier.Name)
  894. return &ast.BadStatement{From: idx, To: identifier.Idx1()}
  895. }
  896. if !self.scope.inIteration {
  897. goto illegal
  898. }
  899. self.semicolon()
  900. return &ast.BranchStatement{
  901. Idx: idx,
  902. Token: token.CONTINUE,
  903. Label: identifier,
  904. }
  905. }
  906. self.expect(token.IDENTIFIER)
  907. illegal:
  908. self.error(idx, "Illegal continue statement")
  909. self.nextStatement()
  910. return &ast.BadStatement{From: idx, To: self.idx}
  911. }
  912. // Find the next statement after an error (recover)
  913. func (self *_parser) nextStatement() {
  914. for {
  915. switch self.token {
  916. case token.BREAK, token.CONTINUE,
  917. token.FOR, token.IF, token.RETURN, token.SWITCH,
  918. token.VAR, token.DO, token.TRY, token.WITH,
  919. token.WHILE, token.THROW, token.CATCH, token.FINALLY:
  920. // Return only if parser made some progress since last
  921. // sync or if it has not reached 10 next calls without
  922. // progress. Otherwise consume at least one token to
  923. // avoid an endless parser loop
  924. if self.idx == self.recover.idx && self.recover.count < 10 {
  925. self.recover.count++
  926. return
  927. }
  928. if self.idx > self.recover.idx {
  929. self.recover.idx = self.idx
  930. self.recover.count = 0
  931. return
  932. }
  933. // Reaching here indicates a parser bug, likely an
  934. // incorrect token list in this function, but it only
  935. // leads to skipping of possibly correct code if a
  936. // previous error is present, and thus is preferred
  937. // over a non-terminating parse.
  938. case token.EOF:
  939. return
  940. }
  941. self.next()
  942. }
  943. }