expression.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. // A recursive descent parser operates by defining functions for all
  2. // syntactic elements, and recursively calling those, each function
  3. // advancing the input stream and returning an AST node. Precedence
  4. // of constructs (for example, the fact that `!x[1]` means `!(x[1])`
  5. // instead of `(!x)[1]` is handled by the fact that the parser
  6. // function that parses unary prefix operators is called first, and
  7. // in turn calls the function that parses `[]` subscripts — that
  8. // way, it'll receive the node for `x[1]` already parsed, and wraps
  9. // *that* in the unary operator node.
  10. //
  11. // Acorn uses an [operator precedence parser][opp] to handle binary
  12. // operator precedence, because it is much more compact than using
  13. // the technique outlined above, which uses different, nesting
  14. // functions to specify precedence, for all of the ten binary
  15. // precedence levels that JavaScript defines.
  16. //
  17. // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
  18. import {types as tt} from "./tokentype"
  19. import {Parser} from "./state"
  20. import {DestructuringErrors} from "./parseutil"
  21. const pp = Parser.prototype
  22. // Check if property name clashes with already added.
  23. // Object/class getters and setters are not allowed to clash —
  24. // either with each other or with an init property — and in
  25. // strict mode, init properties are also not allowed to be repeated.
  26. pp.checkPropClash = function(prop, propHash) {
  27. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  28. return
  29. let {key} = prop, name
  30. switch (key.type) {
  31. case "Identifier": name = key.name; break
  32. case "Literal": name = String(key.value); break
  33. default: return
  34. }
  35. let {kind} = prop
  36. if (this.options.ecmaVersion >= 6) {
  37. if (name === "__proto__" && kind === "init") {
  38. if (propHash.proto) this.raiseRecoverable(key.start, "Redefinition of __proto__ property")
  39. propHash.proto = true
  40. }
  41. return
  42. }
  43. name = "$" + name
  44. let other = propHash[name]
  45. if (other) {
  46. let redefinition
  47. if (kind === "init") {
  48. redefinition = this.strict && other.init || other.get || other.set
  49. } else {
  50. redefinition = other.init || other[kind]
  51. }
  52. if (redefinition)
  53. this.raiseRecoverable(key.start, "Redefinition of property")
  54. } else {
  55. other = propHash[name] = {
  56. init: false,
  57. get: false,
  58. set: false
  59. }
  60. }
  61. other[kind] = true
  62. }
  63. // ### Expression parsing
  64. // These nest, from the most general expression type at the top to
  65. // 'atomic', nondivisible expression types at the bottom. Most of
  66. // the functions will simply let the function(s) below them parse,
  67. // and, *if* the syntactic construct they handle is present, wrap
  68. // the AST node that the inner parser gave them in another node.
  69. // Parse a full expression. The optional arguments are used to
  70. // forbid the `in` operator (in for loops initalization expressions)
  71. // and provide reference for storing '=' operator inside shorthand
  72. // property assignment in contexts where both object expression
  73. // and object pattern might appear (so it's possible to raise
  74. // delayed syntax error at correct position).
  75. pp.parseExpression = function(noIn, refDestructuringErrors) {
  76. let startPos = this.start, startLoc = this.startLoc
  77. let expr = this.parseMaybeAssign(noIn, refDestructuringErrors)
  78. if (this.type === tt.comma) {
  79. let node = this.startNodeAt(startPos, startLoc)
  80. node.expressions = [expr]
  81. while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors))
  82. return this.finishNode(node, "SequenceExpression")
  83. }
  84. return expr
  85. }
  86. // Parse an assignment expression. This includes applications of
  87. // operators like `+=`.
  88. pp.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
  89. if (this.inGenerator && this.isContextual("yield")) return this.parseYield()
  90. let ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1
  91. if (refDestructuringErrors) {
  92. oldParenAssign = refDestructuringErrors.parenthesizedAssign
  93. oldTrailingComma = refDestructuringErrors.trailingComma
  94. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1
  95. } else {
  96. refDestructuringErrors = new DestructuringErrors
  97. ownDestructuringErrors = true
  98. }
  99. let startPos = this.start, startLoc = this.startLoc
  100. if (this.type == tt.parenL || this.type == tt.name)
  101. this.potentialArrowAt = this.start
  102. let left = this.parseMaybeConditional(noIn, refDestructuringErrors)
  103. if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc)
  104. if (this.type.isAssign) {
  105. this.checkPatternErrors(refDestructuringErrors, true)
  106. if (!ownDestructuringErrors) DestructuringErrors.call(refDestructuringErrors)
  107. let node = this.startNodeAt(startPos, startLoc)
  108. node.operator = this.value
  109. node.left = this.type === tt.eq ? this.toAssignable(left) : left
  110. refDestructuringErrors.shorthandAssign = -1 // reset because shorthand default was used correctly
  111. this.checkLVal(left)
  112. this.next()
  113. node.right = this.parseMaybeAssign(noIn)
  114. return this.finishNode(node, "AssignmentExpression")
  115. } else {
  116. if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true)
  117. }
  118. if (oldParenAssign > -1) refDestructuringErrors.parenthesizedAssign = oldParenAssign
  119. if (oldTrailingComma > -1) refDestructuringErrors.trailingComma = oldTrailingComma
  120. return left
  121. }
  122. // Parse a ternary conditional (`?:`) operator.
  123. pp.parseMaybeConditional = function(noIn, refDestructuringErrors) {
  124. let startPos = this.start, startLoc = this.startLoc
  125. let expr = this.parseExprOps(noIn, refDestructuringErrors)
  126. if (this.checkExpressionErrors(refDestructuringErrors)) return expr
  127. if (this.eat(tt.question)) {
  128. let node = this.startNodeAt(startPos, startLoc)
  129. node.test = expr
  130. node.consequent = this.parseMaybeAssign()
  131. this.expect(tt.colon)
  132. node.alternate = this.parseMaybeAssign(noIn)
  133. return this.finishNode(node, "ConditionalExpression")
  134. }
  135. return expr
  136. }
  137. // Start the precedence parser.
  138. pp.parseExprOps = function(noIn, refDestructuringErrors) {
  139. let startPos = this.start, startLoc = this.startLoc
  140. let expr = this.parseMaybeUnary(refDestructuringErrors, false)
  141. if (this.checkExpressionErrors(refDestructuringErrors)) return expr
  142. return expr.start == startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
  143. }
  144. // Parse binary operators with the operator precedence parsing
  145. // algorithm. `left` is the left-hand side of the operator.
  146. // `minPrec` provides context that allows the function to stop and
  147. // defer further parser to one of its callers when it encounters an
  148. // operator that has a lower precedence than the set it is parsing.
  149. pp.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  150. let prec = this.type.binop
  151. if (prec != null && (!noIn || this.type !== tt._in)) {
  152. if (prec > minPrec) {
  153. let logical = this.type === tt.logicalOR || this.type === tt.logicalAND
  154. let op = this.value
  155. this.next()
  156. let startPos = this.start, startLoc = this.startLoc
  157. let right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn)
  158. let node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical)
  159. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
  160. }
  161. }
  162. return left
  163. }
  164. pp.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  165. let node = this.startNodeAt(startPos, startLoc)
  166. node.left = left
  167. node.operator = op
  168. node.right = right
  169. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  170. }
  171. // Parse unary operators, both prefix and postfix.
  172. pp.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
  173. let startPos = this.start, startLoc = this.startLoc, expr
  174. if (this.inAsync && this.isContextual("await")) {
  175. expr = this.parseAwait(refDestructuringErrors)
  176. sawUnary = true
  177. } else if (this.type.prefix) {
  178. let node = this.startNode(), update = this.type === tt.incDec
  179. node.operator = this.value
  180. node.prefix = true
  181. this.next()
  182. node.argument = this.parseMaybeUnary(null, true)
  183. this.checkExpressionErrors(refDestructuringErrors, true)
  184. if (update) this.checkLVal(node.argument)
  185. else if (this.strict && node.operator === "delete" &&
  186. node.argument.type === "Identifier")
  187. this.raiseRecoverable(node.start, "Deleting local variable in strict mode")
  188. else sawUnary = true
  189. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression")
  190. } else {
  191. expr = this.parseExprSubscripts(refDestructuringErrors)
  192. if (this.checkExpressionErrors(refDestructuringErrors)) return expr
  193. while (this.type.postfix && !this.canInsertSemicolon()) {
  194. let node = this.startNodeAt(startPos, startLoc)
  195. node.operator = this.value
  196. node.prefix = false
  197. node.argument = expr
  198. this.checkLVal(expr)
  199. this.next()
  200. expr = this.finishNode(node, "UpdateExpression")
  201. }
  202. }
  203. if (!sawUnary && this.eat(tt.starstar))
  204. return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false)
  205. else
  206. return expr
  207. }
  208. // Parse call, dot, and `[]`-subscript expressions.
  209. pp.parseExprSubscripts = function(refDestructuringErrors) {
  210. let startPos = this.start, startLoc = this.startLoc
  211. let expr = this.parseExprAtom(refDestructuringErrors)
  212. let skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")"
  213. if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) return expr
  214. let result = this.parseSubscripts(expr, startPos, startLoc)
  215. if (refDestructuringErrors && result.type === "MemberExpression") {
  216. if (refDestructuringErrors.parenthesizedAssign >= result.start) refDestructuringErrors.parenthesizedAssign = -1
  217. if (refDestructuringErrors.parenthesizedBind >= result.start) refDestructuringErrors.parenthesizedBind = -1
  218. }
  219. return result
  220. }
  221. pp.parseSubscripts = function(base, startPos, startLoc, noCalls) {
  222. let maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  223. this.lastTokEnd == base.end && !this.canInsertSemicolon()
  224. for (let computed;;) {
  225. if ((computed = this.eat(tt.bracketL)) || this.eat(tt.dot)) {
  226. let node = this.startNodeAt(startPos, startLoc)
  227. node.object = base
  228. node.property = computed ? this.parseExpression() : this.parseIdent(true)
  229. node.computed = !!computed
  230. if (computed) this.expect(tt.bracketR)
  231. base = this.finishNode(node, "MemberExpression")
  232. } else if (!noCalls && this.eat(tt.parenL)) {
  233. let refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos
  234. this.yieldPos = 0
  235. this.awaitPos = 0
  236. let exprList = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors)
  237. if (maybeAsyncArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
  238. this.checkPatternErrors(refDestructuringErrors, false)
  239. this.checkYieldAwaitInDefaultParams()
  240. this.yieldPos = oldYieldPos
  241. this.awaitPos = oldAwaitPos
  242. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
  243. }
  244. this.checkExpressionErrors(refDestructuringErrors, true)
  245. this.yieldPos = oldYieldPos || this.yieldPos
  246. this.awaitPos = oldAwaitPos || this.awaitPos
  247. let node = this.startNodeAt(startPos, startLoc)
  248. node.callee = base
  249. node.arguments = exprList
  250. base = this.finishNode(node, "CallExpression")
  251. } else if (this.type === tt.backQuote) {
  252. let node = this.startNodeAt(startPos, startLoc)
  253. node.tag = base
  254. node.quasi = this.parseTemplate()
  255. base = this.finishNode(node, "TaggedTemplateExpression")
  256. } else {
  257. return base
  258. }
  259. }
  260. }
  261. // Parse an atomic expression — either a single token that is an
  262. // expression, an expression started by a keyword like `function` or
  263. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  264. // or `{}`.
  265. pp.parseExprAtom = function(refDestructuringErrors) {
  266. let node, canBeArrow = this.potentialArrowAt == this.start
  267. switch (this.type) {
  268. case tt._super:
  269. if (!this.inFunction)
  270. this.raise(this.start, "'super' outside of function or class")
  271. case tt._this:
  272. let type = this.type === tt._this ? "ThisExpression" : "Super"
  273. node = this.startNode()
  274. this.next()
  275. return this.finishNode(node, type)
  276. case tt.name:
  277. let startPos = this.start, startLoc = this.startLoc
  278. let id = this.parseIdent(this.type !== tt.name)
  279. if (this.options.ecmaVersion >= 8 && id.name === "async" && !this.canInsertSemicolon() && this.eat(tt._function))
  280. return this.parseFunction(this.startNodeAt(startPos, startLoc), false, false, true)
  281. if (canBeArrow && !this.canInsertSemicolon()) {
  282. if (this.eat(tt.arrow))
  283. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false)
  284. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === tt.name) {
  285. id = this.parseIdent()
  286. if (this.canInsertSemicolon() || !this.eat(tt.arrow))
  287. this.unexpected()
  288. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
  289. }
  290. }
  291. return id
  292. case tt.regexp:
  293. let value = this.value
  294. node = this.parseLiteral(value.value)
  295. node.regex = {pattern: value.pattern, flags: value.flags}
  296. return node
  297. case tt.num: case tt.string:
  298. return this.parseLiteral(this.value)
  299. case tt._null: case tt._true: case tt._false:
  300. node = this.startNode()
  301. node.value = this.type === tt._null ? null : this.type === tt._true
  302. node.raw = this.type.keyword
  303. this.next()
  304. return this.finishNode(node, "Literal")
  305. case tt.parenL:
  306. let start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow)
  307. if (refDestructuringErrors) {
  308. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  309. refDestructuringErrors.parenthesizedAssign = start
  310. if (refDestructuringErrors.parenthesizedBind < 0)
  311. refDestructuringErrors.parenthesizedBind = start
  312. }
  313. return expr
  314. case tt.bracketL:
  315. node = this.startNode()
  316. this.next()
  317. node.elements = this.parseExprList(tt.bracketR, true, true, refDestructuringErrors)
  318. return this.finishNode(node, "ArrayExpression")
  319. case tt.braceL:
  320. return this.parseObj(false, refDestructuringErrors)
  321. case tt._function:
  322. node = this.startNode()
  323. this.next()
  324. return this.parseFunction(node, false)
  325. case tt._class:
  326. return this.parseClass(this.startNode(), false)
  327. case tt._new:
  328. return this.parseNew()
  329. case tt.backQuote:
  330. return this.parseTemplate()
  331. default:
  332. this.unexpected()
  333. }
  334. }
  335. pp.parseLiteral = function(value) {
  336. let node = this.startNode()
  337. node.value = value
  338. node.raw = this.input.slice(this.start, this.end)
  339. this.next()
  340. return this.finishNode(node, "Literal")
  341. }
  342. pp.parseParenExpression = function() {
  343. this.expect(tt.parenL)
  344. let val = this.parseExpression()
  345. this.expect(tt.parenR)
  346. return val
  347. }
  348. pp.parseParenAndDistinguishExpression = function(canBeArrow) {
  349. let startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8
  350. if (this.options.ecmaVersion >= 6) {
  351. this.next()
  352. let innerStartPos = this.start, innerStartLoc = this.startLoc
  353. let exprList = [], first = true, lastIsComma = false
  354. let refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart, innerParenStart
  355. this.yieldPos = 0
  356. this.awaitPos = 0
  357. while (this.type !== tt.parenR) {
  358. first ? first = false : this.expect(tt.comma)
  359. if (allowTrailingComma && this.afterTrailingComma(tt.parenR, true)) {
  360. lastIsComma = true
  361. break
  362. } else if (this.type === tt.ellipsis) {
  363. spreadStart = this.start
  364. exprList.push(this.parseParenItem(this.parseRest()))
  365. if (this.type === tt.comma) this.raise(this.start, "Comma is not permitted after the rest element")
  366. break
  367. } else {
  368. if (this.type === tt.parenL && !innerParenStart) {
  369. innerParenStart = this.start
  370. }
  371. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem))
  372. }
  373. }
  374. let innerEndPos = this.start, innerEndLoc = this.startLoc
  375. this.expect(tt.parenR)
  376. if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
  377. this.checkPatternErrors(refDestructuringErrors, false)
  378. this.checkYieldAwaitInDefaultParams()
  379. if (innerParenStart) this.unexpected(innerParenStart)
  380. this.yieldPos = oldYieldPos
  381. this.awaitPos = oldAwaitPos
  382. return this.parseParenArrowList(startPos, startLoc, exprList)
  383. }
  384. if (!exprList.length || lastIsComma) this.unexpected(this.lastTokStart)
  385. if (spreadStart) this.unexpected(spreadStart)
  386. this.checkExpressionErrors(refDestructuringErrors, true)
  387. this.yieldPos = oldYieldPos || this.yieldPos
  388. this.awaitPos = oldAwaitPos || this.awaitPos
  389. if (exprList.length > 1) {
  390. val = this.startNodeAt(innerStartPos, innerStartLoc)
  391. val.expressions = exprList
  392. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc)
  393. } else {
  394. val = exprList[0]
  395. }
  396. } else {
  397. val = this.parseParenExpression()
  398. }
  399. if (this.options.preserveParens) {
  400. let par = this.startNodeAt(startPos, startLoc)
  401. par.expression = val
  402. return this.finishNode(par, "ParenthesizedExpression")
  403. } else {
  404. return val
  405. }
  406. }
  407. pp.parseParenItem = function(item) {
  408. return item
  409. }
  410. pp.parseParenArrowList = function(startPos, startLoc, exprList) {
  411. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
  412. }
  413. // New's precedence is slightly tricky. It must allow its argument to
  414. // be a `[]` or dot subscript expression, but not a call — at least,
  415. // not without wrapping it in parentheses. Thus, it uses the noCalls
  416. // argument to parseSubscripts to prevent it from consuming the
  417. // argument list.
  418. const empty = []
  419. pp.parseNew = function() {
  420. let node = this.startNode()
  421. let meta = this.parseIdent(true)
  422. if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
  423. node.meta = meta
  424. node.property = this.parseIdent(true)
  425. if (node.property.name !== "target")
  426. this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target")
  427. if (!this.inFunction)
  428. this.raiseRecoverable(node.start, "new.target can only be used in functions")
  429. return this.finishNode(node, "MetaProperty")
  430. }
  431. let startPos = this.start, startLoc = this.startLoc
  432. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true)
  433. if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false)
  434. else node.arguments = empty
  435. return this.finishNode(node, "NewExpression")
  436. }
  437. // Parse template expression.
  438. pp.parseTemplateElement = function() {
  439. let elem = this.startNode()
  440. elem.value = {
  441. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  442. cooked: this.value
  443. }
  444. this.next()
  445. elem.tail = this.type === tt.backQuote
  446. return this.finishNode(elem, "TemplateElement")
  447. }
  448. pp.parseTemplate = function() {
  449. let node = this.startNode()
  450. this.next()
  451. node.expressions = []
  452. let curElt = this.parseTemplateElement()
  453. node.quasis = [curElt]
  454. while (!curElt.tail) {
  455. this.expect(tt.dollarBraceL)
  456. node.expressions.push(this.parseExpression())
  457. this.expect(tt.braceR)
  458. node.quasis.push(curElt = this.parseTemplateElement())
  459. }
  460. this.next()
  461. return this.finishNode(node, "TemplateLiteral")
  462. }
  463. // Parse an object literal or binding pattern.
  464. pp.parseObj = function(isPattern, refDestructuringErrors) {
  465. let node = this.startNode(), first = true, propHash = {}
  466. node.properties = []
  467. this.next()
  468. while (!this.eat(tt.braceR)) {
  469. if (!first) {
  470. this.expect(tt.comma)
  471. if (this.afterTrailingComma(tt.braceR)) break
  472. } else first = false
  473. let prop = this.startNode(), isGenerator, isAsync, startPos, startLoc
  474. if (this.options.ecmaVersion >= 6) {
  475. prop.method = false
  476. prop.shorthand = false
  477. if (isPattern || refDestructuringErrors) {
  478. startPos = this.start
  479. startLoc = this.startLoc
  480. }
  481. if (!isPattern)
  482. isGenerator = this.eat(tt.star)
  483. }
  484. this.parsePropertyName(prop)
  485. if (!isPattern && this.options.ecmaVersion >= 8 && !isGenerator && !prop.computed &&
  486. prop.key.type === "Identifier" && prop.key.name === "async" && this.type !== tt.parenL &&
  487. this.type !== tt.colon && !this.canInsertSemicolon()) {
  488. isAsync = true
  489. this.parsePropertyName(prop, refDestructuringErrors)
  490. } else {
  491. isAsync = false
  492. }
  493. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors)
  494. this.checkPropClash(prop, propHash)
  495. node.properties.push(this.finishNode(prop, "Property"))
  496. }
  497. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  498. }
  499. pp.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors) {
  500. if ((isGenerator || isAsync) && this.type === tt.colon)
  501. this.unexpected()
  502. if (this.eat(tt.colon)) {
  503. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors)
  504. prop.kind = "init"
  505. } else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) {
  506. if (isPattern) this.unexpected()
  507. prop.kind = "init"
  508. prop.method = true
  509. prop.value = this.parseMethod(isGenerator, isAsync)
  510. } else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  511. (prop.key.name === "get" || prop.key.name === "set") &&
  512. (this.type != tt.comma && this.type != tt.braceR)) {
  513. if (isGenerator || isAsync || isPattern) this.unexpected()
  514. prop.kind = prop.key.name
  515. this.parsePropertyName(prop)
  516. prop.value = this.parseMethod(false)
  517. let paramCount = prop.kind === "get" ? 0 : 1
  518. if (prop.value.params.length !== paramCount) {
  519. let start = prop.value.start
  520. if (prop.kind === "get")
  521. this.raiseRecoverable(start, "getter should have no params")
  522. else
  523. this.raiseRecoverable(start, "setter should have exactly one param")
  524. } else {
  525. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  526. this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params")
  527. }
  528. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  529. if (this.keywords.test(prop.key.name) ||
  530. (this.strict ? this.reservedWordsStrict : this.reservedWords).test(prop.key.name) ||
  531. (this.inGenerator && prop.key.name == "yield") ||
  532. (this.inAsync && prop.key.name == "await"))
  533. this.raiseRecoverable(prop.key.start, "'" + prop.key.name + "' can not be used as shorthand property")
  534. prop.kind = "init"
  535. if (isPattern) {
  536. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key)
  537. } else if (this.type === tt.eq && refDestructuringErrors) {
  538. if (refDestructuringErrors.shorthandAssign < 0)
  539. refDestructuringErrors.shorthandAssign = this.start
  540. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key)
  541. } else {
  542. prop.value = prop.key
  543. }
  544. prop.shorthand = true
  545. } else this.unexpected()
  546. }
  547. pp.parsePropertyName = function(prop) {
  548. if (this.options.ecmaVersion >= 6) {
  549. if (this.eat(tt.bracketL)) {
  550. prop.computed = true
  551. prop.key = this.parseMaybeAssign()
  552. this.expect(tt.bracketR)
  553. return prop.key
  554. } else {
  555. prop.computed = false
  556. }
  557. }
  558. return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true)
  559. }
  560. // Initialize empty function node.
  561. pp.initFunction = function(node) {
  562. node.id = null
  563. if (this.options.ecmaVersion >= 6) {
  564. node.generator = false
  565. node.expression = false
  566. }
  567. if (this.options.ecmaVersion >= 8)
  568. node.async = false
  569. }
  570. // Parse object or class method.
  571. pp.parseMethod = function(isGenerator, isAsync) {
  572. let node = this.startNode(), oldInGen = this.inGenerator, oldInAsync = this.inAsync,
  573. oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction
  574. this.initFunction(node)
  575. if (this.options.ecmaVersion >= 6)
  576. node.generator = isGenerator
  577. if (this.options.ecmaVersion >= 8)
  578. node.async = !!isAsync
  579. this.inGenerator = node.generator
  580. this.inAsync = node.async
  581. this.yieldPos = 0
  582. this.awaitPos = 0
  583. this.inFunction = true
  584. this.enterFunctionScope()
  585. this.expect(tt.parenL)
  586. node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8)
  587. this.checkYieldAwaitInDefaultParams()
  588. this.parseFunctionBody(node, false)
  589. this.inGenerator = oldInGen
  590. this.inAsync = oldInAsync
  591. this.yieldPos = oldYieldPos
  592. this.awaitPos = oldAwaitPos
  593. this.inFunction = oldInFunc
  594. return this.finishNode(node, "FunctionExpression")
  595. }
  596. // Parse arrow function expression with given parameters.
  597. pp.parseArrowExpression = function(node, params, isAsync) {
  598. let oldInGen = this.inGenerator, oldInAsync = this.inAsync,
  599. oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction
  600. this.enterFunctionScope()
  601. this.initFunction(node)
  602. if (this.options.ecmaVersion >= 8)
  603. node.async = !!isAsync
  604. this.inGenerator = false
  605. this.inAsync = node.async
  606. this.yieldPos = 0
  607. this.awaitPos = 0
  608. this.inFunction = true
  609. node.params = this.toAssignableList(params, true)
  610. this.parseFunctionBody(node, true)
  611. this.inGenerator = oldInGen
  612. this.inAsync = oldInAsync
  613. this.yieldPos = oldYieldPos
  614. this.awaitPos = oldAwaitPos
  615. this.inFunction = oldInFunc
  616. return this.finishNode(node, "ArrowFunctionExpression")
  617. }
  618. // Parse function body and check parameters.
  619. pp.parseFunctionBody = function(node, isArrowFunction) {
  620. let isExpression = isArrowFunction && this.type !== tt.braceL
  621. let oldStrict = this.strict, useStrict = false
  622. if (isExpression) {
  623. node.body = this.parseMaybeAssign()
  624. node.expression = true
  625. this.checkParams(node, false)
  626. } else {
  627. let nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params)
  628. if (!oldStrict || nonSimple) {
  629. useStrict = this.strictDirective(this.end)
  630. // If this is a strict mode function, verify that argument names
  631. // are not repeated, and it does not try to bind the words `eval`
  632. // or `arguments`.
  633. if (useStrict && nonSimple)
  634. this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list")
  635. }
  636. // Start a new scope with regard to labels and the `inFunction`
  637. // flag (restore them to their old value afterwards).
  638. let oldLabels = this.labels
  639. this.labels = []
  640. if (useStrict) this.strict = true
  641. // Add the params to varDeclaredNames to ensure that an error is thrown
  642. // if a let/const declaration in the function clashes with one of the params.
  643. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && this.isSimpleParamList(node.params))
  644. node.body = this.parseBlock(false)
  645. node.expression = false
  646. this.labels = oldLabels
  647. }
  648. this.exitFunctionScope()
  649. if (this.strict && node.id) {
  650. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  651. this.checkLVal(node.id, "none")
  652. }
  653. this.strict = oldStrict
  654. }
  655. pp.isSimpleParamList = function(params) {
  656. for (let i = 0; i < params.length; i++)
  657. if (params[i].type !== "Identifier") return false
  658. return true
  659. }
  660. // Checks function params for various disallowed patterns such as using "eval"
  661. // or "arguments" and duplicate parameters.
  662. pp.checkParams = function(node, allowDuplicates) {
  663. let nameHash = {}
  664. for (let i = 0; i < node.params.length; i++) this.checkLVal(node.params[i], "var", allowDuplicates ? null : nameHash)
  665. }
  666. // Parses a comma-separated list of expressions, and returns them as
  667. // an array. `close` is the token type that ends the list, and
  668. // `allowEmpty` can be turned on to allow subsequent commas with
  669. // nothing in between them to be parsed as `null` (which is needed
  670. // for array literals).
  671. pp.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  672. let elts = [], first = true
  673. while (!this.eat(close)) {
  674. if (!first) {
  675. this.expect(tt.comma)
  676. if (allowTrailingComma && this.afterTrailingComma(close)) break
  677. } else first = false
  678. let elt
  679. if (allowEmpty && this.type === tt.comma)
  680. elt = null
  681. else if (this.type === tt.ellipsis) {
  682. elt = this.parseSpread(refDestructuringErrors)
  683. if (refDestructuringErrors && this.type === tt.comma && refDestructuringErrors.trailingComma < 0)
  684. refDestructuringErrors.trailingComma = this.start
  685. } else {
  686. elt = this.parseMaybeAssign(false, refDestructuringErrors)
  687. }
  688. elts.push(elt)
  689. }
  690. return elts
  691. }
  692. // Parse the next token as an identifier. If `liberal` is true (used
  693. // when parsing properties), it will also convert keywords into
  694. // identifiers.
  695. pp.parseIdent = function(liberal) {
  696. let node = this.startNode()
  697. if (liberal && this.options.allowReserved == "never") liberal = false
  698. if (this.type === tt.name) {
  699. if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).test(this.value) &&
  700. (this.options.ecmaVersion >= 6 ||
  701. this.input.slice(this.start, this.end).indexOf("\\") == -1))
  702. this.raiseRecoverable(this.start, "The keyword '" + this.value + "' is reserved")
  703. if (this.inGenerator && this.value === "yield")
  704. this.raiseRecoverable(this.start, "Can not use 'yield' as identifier inside a generator")
  705. if (this.inAsync && this.value === "await")
  706. this.raiseRecoverable(this.start, "Can not use 'await' as identifier inside an async function")
  707. node.name = this.value
  708. } else if (liberal && this.type.keyword) {
  709. node.name = this.type.keyword
  710. } else {
  711. this.unexpected()
  712. }
  713. this.next()
  714. return this.finishNode(node, "Identifier")
  715. }
  716. // Parses yield expression inside generator.
  717. pp.parseYield = function() {
  718. if (!this.yieldPos) this.yieldPos = this.start
  719. let node = this.startNode()
  720. this.next()
  721. if (this.type == tt.semi || this.canInsertSemicolon() || (this.type != tt.star && !this.type.startsExpr)) {
  722. node.delegate = false
  723. node.argument = null
  724. } else {
  725. node.delegate = this.eat(tt.star)
  726. node.argument = this.parseMaybeAssign()
  727. }
  728. return this.finishNode(node, "YieldExpression")
  729. }
  730. pp.parseAwait = function() {
  731. if (!this.awaitPos) this.awaitPos = this.start
  732. let node = this.startNode()
  733. this.next()
  734. node.argument = this.parseMaybeUnary(null, true)
  735. return this.finishNode(node, "AwaitExpression")
  736. }