statement.go 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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. self.expect(token.SWITCH)
  450. self.expect(token.LEFT_PARENTHESIS)
  451. node := &ast.SwitchStatement{
  452. Discriminant: self.parseExpression(),
  453. Default: -1,
  454. }
  455. self.expect(token.RIGHT_PARENTHESIS)
  456. self.expect(token.LEFT_BRACE)
  457. inSwitch := self.scope.inSwitch
  458. self.scope.inSwitch = true
  459. defer func() {
  460. self.scope.inSwitch = inSwitch
  461. }()
  462. for index := 0; self.token != token.EOF; index++ {
  463. if self.token == token.RIGHT_BRACE {
  464. self.next()
  465. break
  466. }
  467. clause := self.parseCaseStatement()
  468. if clause.Test == nil {
  469. if node.Default != -1 {
  470. self.error(clause.Case, "Already saw a default in switch")
  471. }
  472. node.Default = index
  473. }
  474. node.Body = append(node.Body, clause)
  475. }
  476. return node
  477. }
  478. func (self *_parser) parseWithStatement() ast.Statement {
  479. self.expect(token.WITH)
  480. self.expect(token.LEFT_PARENTHESIS)
  481. node := &ast.WithStatement{
  482. Object: self.parseExpression(),
  483. }
  484. self.expect(token.RIGHT_PARENTHESIS)
  485. self.scope.allowLet = false
  486. node.Body = self.parseStatement()
  487. return node
  488. }
  489. func (self *_parser) parseCaseStatement() *ast.CaseStatement {
  490. node := &ast.CaseStatement{
  491. Case: self.idx,
  492. }
  493. if self.token == token.DEFAULT {
  494. self.next()
  495. } else {
  496. self.expect(token.CASE)
  497. node.Test = self.parseExpression()
  498. }
  499. self.expect(token.COLON)
  500. for {
  501. if self.token == token.EOF ||
  502. self.token == token.RIGHT_BRACE ||
  503. self.token == token.CASE ||
  504. self.token == token.DEFAULT {
  505. break
  506. }
  507. self.scope.allowLet = true
  508. node.Consequent = append(node.Consequent, self.parseStatement())
  509. }
  510. return node
  511. }
  512. func (self *_parser) parseIterationStatement() ast.Statement {
  513. inIteration := self.scope.inIteration
  514. self.scope.inIteration = true
  515. defer func() {
  516. self.scope.inIteration = inIteration
  517. }()
  518. self.scope.allowLet = false
  519. return self.parseStatement()
  520. }
  521. func (self *_parser) parseForIn(idx file.Idx, into ast.ForInto) *ast.ForInStatement {
  522. // Already have consumed "<into> in"
  523. source := self.parseExpression()
  524. self.expect(token.RIGHT_PARENTHESIS)
  525. return &ast.ForInStatement{
  526. For: idx,
  527. Into: into,
  528. Source: source,
  529. Body: self.parseIterationStatement(),
  530. }
  531. }
  532. func (self *_parser) parseForOf(idx file.Idx, into ast.ForInto) *ast.ForOfStatement {
  533. // Already have consumed "<into> of"
  534. source := self.parseAssignmentExpression()
  535. self.expect(token.RIGHT_PARENTHESIS)
  536. return &ast.ForOfStatement{
  537. For: idx,
  538. Into: into,
  539. Source: source,
  540. Body: self.parseIterationStatement(),
  541. }
  542. }
  543. func (self *_parser) parseFor(idx file.Idx, initializer ast.ForLoopInitializer) *ast.ForStatement {
  544. // Already have consumed "<initializer> ;"
  545. var test, update ast.Expression
  546. if self.token != token.SEMICOLON {
  547. test = self.parseExpression()
  548. }
  549. self.expect(token.SEMICOLON)
  550. if self.token != token.RIGHT_PARENTHESIS {
  551. update = self.parseExpression()
  552. }
  553. self.expect(token.RIGHT_PARENTHESIS)
  554. return &ast.ForStatement{
  555. For: idx,
  556. Initializer: initializer,
  557. Test: test,
  558. Update: update,
  559. Body: self.parseIterationStatement(),
  560. }
  561. }
  562. func (self *_parser) parseForOrForInStatement() ast.Statement {
  563. idx := self.expect(token.FOR)
  564. self.expect(token.LEFT_PARENTHESIS)
  565. var initializer ast.ForLoopInitializer
  566. forIn := false
  567. forOf := false
  568. var into ast.ForInto
  569. if self.token != token.SEMICOLON {
  570. allowIn := self.scope.allowIn
  571. self.scope.allowIn = false
  572. tok := self.token
  573. if tok == token.LET {
  574. switch self.peek() {
  575. case token.IDENTIFIER, token.LEFT_BRACKET, token.LEFT_BRACE:
  576. default:
  577. tok = token.IDENTIFIER
  578. }
  579. }
  580. if tok == token.VAR || tok == token.LET || tok == token.CONST {
  581. idx := self.idx
  582. self.next()
  583. var list []*ast.Binding
  584. if tok == token.VAR {
  585. list = self.parseVarDeclarationList(idx)
  586. } else {
  587. list = self.parseVariableDeclarationList()
  588. }
  589. if len(list) == 1 {
  590. if self.token == token.IN {
  591. self.next() // in
  592. forIn = true
  593. } else if self.token == token.IDENTIFIER && self.literal == "of" {
  594. self.next()
  595. forOf = true
  596. }
  597. }
  598. if forIn || forOf {
  599. if list[0].Initializer != nil {
  600. self.error(list[0].Initializer.Idx0(), "for-in loop variable declaration may not have an initializer")
  601. }
  602. if tok == token.VAR {
  603. into = &ast.ForIntoVar{
  604. Binding: list[0],
  605. }
  606. } else {
  607. into = &ast.ForDeclaration{
  608. Idx: idx,
  609. IsConst: tok == token.CONST,
  610. Target: list[0].Target,
  611. }
  612. }
  613. } else {
  614. self.ensurePatternInit(list)
  615. if tok == token.VAR {
  616. initializer = &ast.ForLoopInitializerVarDeclList{
  617. List: list,
  618. }
  619. } else {
  620. initializer = &ast.ForLoopInitializerLexicalDecl{
  621. LexicalDeclaration: ast.LexicalDeclaration{
  622. Idx: idx,
  623. Token: tok,
  624. List: list,
  625. },
  626. }
  627. }
  628. }
  629. } else {
  630. expr := self.parseExpression()
  631. if self.token == token.IN {
  632. self.next()
  633. forIn = true
  634. } else if self.token == token.IDENTIFIER && self.literal == "of" {
  635. self.next()
  636. forOf = true
  637. }
  638. if forIn || forOf {
  639. switch e := expr.(type) {
  640. case *ast.Identifier, *ast.DotExpression, *ast.PrivateDotExpression, *ast.BracketExpression, *ast.Binding:
  641. // These are all acceptable
  642. case *ast.ObjectLiteral:
  643. expr = self.reinterpretAsObjectAssignmentPattern(e)
  644. case *ast.ArrayLiteral:
  645. expr = self.reinterpretAsArrayAssignmentPattern(e)
  646. default:
  647. self.error(idx, "Invalid left-hand side in for-in or for-of")
  648. self.nextStatement()
  649. return &ast.BadStatement{From: idx, To: self.idx}
  650. }
  651. into = &ast.ForIntoExpression{
  652. Expression: expr,
  653. }
  654. } else {
  655. initializer = &ast.ForLoopInitializerExpression{
  656. Expression: expr,
  657. }
  658. }
  659. }
  660. self.scope.allowIn = allowIn
  661. }
  662. if forIn {
  663. return self.parseForIn(idx, into)
  664. }
  665. if forOf {
  666. return self.parseForOf(idx, into)
  667. }
  668. self.expect(token.SEMICOLON)
  669. return self.parseFor(idx, initializer)
  670. }
  671. func (self *_parser) ensurePatternInit(list []*ast.Binding) {
  672. for _, item := range list {
  673. if _, ok := item.Target.(ast.Pattern); ok {
  674. if item.Initializer == nil {
  675. self.error(item.Idx1(), "Missing initializer in destructuring declaration")
  676. break
  677. }
  678. }
  679. }
  680. }
  681. func (self *_parser) parseVariableStatement() *ast.VariableStatement {
  682. idx := self.expect(token.VAR)
  683. list := self.parseVarDeclarationList(idx)
  684. self.ensurePatternInit(list)
  685. self.semicolon()
  686. return &ast.VariableStatement{
  687. Var: idx,
  688. List: list,
  689. }
  690. }
  691. func (self *_parser) parseLexicalDeclaration(tok token.Token) *ast.LexicalDeclaration {
  692. idx := self.expect(tok)
  693. if !self.scope.allowLet {
  694. self.error(idx, "Lexical declaration cannot appear in a single-statement context")
  695. }
  696. list := self.parseVariableDeclarationList()
  697. self.ensurePatternInit(list)
  698. self.semicolon()
  699. return &ast.LexicalDeclaration{
  700. Idx: idx,
  701. Token: tok,
  702. List: list,
  703. }
  704. }
  705. func (self *_parser) parseDoWhileStatement() ast.Statement {
  706. inIteration := self.scope.inIteration
  707. self.scope.inIteration = true
  708. defer func() {
  709. self.scope.inIteration = inIteration
  710. }()
  711. self.expect(token.DO)
  712. node := &ast.DoWhileStatement{}
  713. if self.token == token.LEFT_BRACE {
  714. node.Body = self.parseBlockStatement()
  715. } else {
  716. self.scope.allowLet = false
  717. node.Body = self.parseStatement()
  718. }
  719. self.expect(token.WHILE)
  720. self.expect(token.LEFT_PARENTHESIS)
  721. node.Test = self.parseExpression()
  722. self.expect(token.RIGHT_PARENTHESIS)
  723. if self.token == token.SEMICOLON {
  724. self.next()
  725. }
  726. return node
  727. }
  728. func (self *_parser) parseWhileStatement() ast.Statement {
  729. self.expect(token.WHILE)
  730. self.expect(token.LEFT_PARENTHESIS)
  731. node := &ast.WhileStatement{
  732. Test: self.parseExpression(),
  733. }
  734. self.expect(token.RIGHT_PARENTHESIS)
  735. node.Body = self.parseIterationStatement()
  736. return node
  737. }
  738. func (self *_parser) parseIfStatement() ast.Statement {
  739. self.expect(token.IF)
  740. self.expect(token.LEFT_PARENTHESIS)
  741. node := &ast.IfStatement{
  742. Test: self.parseExpression(),
  743. }
  744. self.expect(token.RIGHT_PARENTHESIS)
  745. if self.token == token.LEFT_BRACE {
  746. node.Consequent = self.parseBlockStatement()
  747. } else {
  748. self.scope.allowLet = false
  749. node.Consequent = self.parseStatement()
  750. }
  751. if self.token == token.ELSE {
  752. self.next()
  753. self.scope.allowLet = false
  754. node.Alternate = self.parseStatement()
  755. }
  756. return node
  757. }
  758. func (self *_parser) parseSourceElements() (body []ast.Statement) {
  759. for self.token != token.EOF {
  760. self.scope.allowLet = true
  761. body = append(body, self.parseStatement())
  762. }
  763. return body
  764. }
  765. func (self *_parser) parseProgram() *ast.Program {
  766. prg := &ast.Program{
  767. Body: self.parseSourceElements(),
  768. DeclarationList: self.scope.declarationList,
  769. File: self.file,
  770. }
  771. self.file.SetSourceMap(self.parseSourceMap())
  772. return prg
  773. }
  774. func extractSourceMapLine(str string) string {
  775. for {
  776. p := strings.LastIndexByte(str, '\n')
  777. line := str[p+1:]
  778. if line != "" && line != "})" {
  779. if strings.HasPrefix(line, "//# sourceMappingURL=") {
  780. return line
  781. }
  782. break
  783. }
  784. if p >= 0 {
  785. str = str[:p]
  786. } else {
  787. break
  788. }
  789. }
  790. return ""
  791. }
  792. func (self *_parser) parseSourceMap() *sourcemap.Consumer {
  793. if self.opts.disableSourceMaps {
  794. return nil
  795. }
  796. if smLine := extractSourceMapLine(self.str); smLine != "" {
  797. urlIndex := strings.Index(smLine, "=")
  798. urlStr := smLine[urlIndex+1:]
  799. var data []byte
  800. var err error
  801. if strings.HasPrefix(urlStr, "data:application/json") {
  802. b64Index := strings.Index(urlStr, ",")
  803. b64 := urlStr[b64Index+1:]
  804. data, err = base64.StdEncoding.DecodeString(b64)
  805. } else {
  806. if sourceURL := file.ResolveSourcemapURL(self.file.Name(), urlStr); sourceURL != nil {
  807. if self.opts.sourceMapLoader != nil {
  808. data, err = self.opts.sourceMapLoader(sourceURL.String())
  809. } else {
  810. if sourceURL.Scheme == "" || sourceURL.Scheme == "file" {
  811. data, err = os.ReadFile(sourceURL.Path)
  812. } else {
  813. err = fmt.Errorf("unsupported source map URL scheme: %s", sourceURL.Scheme)
  814. }
  815. }
  816. }
  817. }
  818. if err != nil {
  819. self.error(file.Idx(0), "Could not load source map: %v", err)
  820. return nil
  821. }
  822. if data == nil {
  823. return nil
  824. }
  825. if sm, err := sourcemap.Parse(self.file.Name(), data); err == nil {
  826. return sm
  827. } else {
  828. self.error(file.Idx(0), "Could not parse source map: %v", err)
  829. }
  830. }
  831. return nil
  832. }
  833. func (self *_parser) parseBreakStatement() ast.Statement {
  834. idx := self.expect(token.BREAK)
  835. semicolon := self.implicitSemicolon
  836. if self.token == token.SEMICOLON {
  837. semicolon = true
  838. self.next()
  839. }
  840. if semicolon || self.token == token.RIGHT_BRACE {
  841. self.implicitSemicolon = false
  842. if !self.scope.inIteration && !self.scope.inSwitch {
  843. goto illegal
  844. }
  845. return &ast.BranchStatement{
  846. Idx: idx,
  847. Token: token.BREAK,
  848. }
  849. }
  850. self.tokenToBindingId()
  851. if self.token == token.IDENTIFIER {
  852. identifier := self.parseIdentifier()
  853. if !self.scope.hasLabel(identifier.Name) {
  854. self.error(idx, "Undefined label '%s'", identifier.Name)
  855. return &ast.BadStatement{From: idx, To: identifier.Idx1()}
  856. }
  857. self.semicolon()
  858. return &ast.BranchStatement{
  859. Idx: idx,
  860. Token: token.BREAK,
  861. Label: identifier,
  862. }
  863. }
  864. self.expect(token.IDENTIFIER)
  865. illegal:
  866. self.error(idx, "Illegal break statement")
  867. self.nextStatement()
  868. return &ast.BadStatement{From: idx, To: self.idx}
  869. }
  870. func (self *_parser) parseContinueStatement() ast.Statement {
  871. idx := self.expect(token.CONTINUE)
  872. semicolon := self.implicitSemicolon
  873. if self.token == token.SEMICOLON {
  874. semicolon = true
  875. self.next()
  876. }
  877. if semicolon || self.token == token.RIGHT_BRACE {
  878. self.implicitSemicolon = false
  879. if !self.scope.inIteration {
  880. goto illegal
  881. }
  882. return &ast.BranchStatement{
  883. Idx: idx,
  884. Token: token.CONTINUE,
  885. }
  886. }
  887. self.tokenToBindingId()
  888. if self.token == token.IDENTIFIER {
  889. identifier := self.parseIdentifier()
  890. if !self.scope.hasLabel(identifier.Name) {
  891. self.error(idx, "Undefined label '%s'", identifier.Name)
  892. return &ast.BadStatement{From: idx, To: identifier.Idx1()}
  893. }
  894. if !self.scope.inIteration {
  895. goto illegal
  896. }
  897. self.semicolon()
  898. return &ast.BranchStatement{
  899. Idx: idx,
  900. Token: token.CONTINUE,
  901. Label: identifier,
  902. }
  903. }
  904. self.expect(token.IDENTIFIER)
  905. illegal:
  906. self.error(idx, "Illegal continue statement")
  907. self.nextStatement()
  908. return &ast.BadStatement{From: idx, To: self.idx}
  909. }
  910. // Find the next statement after an error (recover)
  911. func (self *_parser) nextStatement() {
  912. for {
  913. switch self.token {
  914. case token.BREAK, token.CONTINUE,
  915. token.FOR, token.IF, token.RETURN, token.SWITCH,
  916. token.VAR, token.DO, token.TRY, token.WITH,
  917. token.WHILE, token.THROW, token.CATCH, token.FINALLY:
  918. // Return only if parser made some progress since last
  919. // sync or if it has not reached 10 next calls without
  920. // progress. Otherwise consume at least one token to
  921. // avoid an endless parser loop
  922. if self.idx == self.recover.idx && self.recover.count < 10 {
  923. self.recover.count++
  924. return
  925. }
  926. if self.idx > self.recover.idx {
  927. self.recover.idx = self.idx
  928. self.recover.count = 0
  929. return
  930. }
  931. // Reaching here indicates a parser bug, likely an
  932. // incorrect token list in this function, but it only
  933. // leads to skipping of possibly correct code if a
  934. // previous error is present, and thus is preferred
  935. // over a non-terminating parse.
  936. case token.EOF:
  937. return
  938. }
  939. self.next()
  940. }
  941. }