statement.go 25 KB

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