How to use peek method in Slash

Best Python code snippet using slash

Parser.js

Source:Parser.js Github

copy

Full Screen

1// Copyright 2012 Google Inc.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14traceur.define('syntax', function() {15 'use strict';16 var MutedErrorReporter = traceur.util.MutedErrorReporter;17 var Keywords = traceur.syntax.Keywords;18 var PredefinedName = traceur.syntax.PredefinedName;19 var SourceRange = traceur.util.SourceRange;20 var Token = traceur.syntax.Token;21 var TokenType = traceur.syntax.TokenType;22 var ArgumentList = traceur.syntax.trees.ArgumentList;23 var ArrayComprehension = traceur.syntax.trees.ArrayComprehension;24 var ArrayLiteralExpression = traceur.syntax.trees.ArrayLiteralExpression;25 var ArrayPattern = traceur.syntax.trees.ArrayPattern;26 var ArrowFunctionExpression = traceur.syntax.trees.ArrowFunctionExpression;27 var AwaitStatement = traceur.syntax.trees.AwaitStatement;28 var BinaryOperator = traceur.syntax.trees.BinaryOperator;29 var BindThisParameter = traceur.syntax.trees.BindThisParameter;30 var BindingElement = traceur.syntax.trees.BindingElement;31 var BindingIdentifier = traceur.syntax.trees.BindingIdentifier;32 var Block = traceur.syntax.trees.Block;33 var BreakStatement = traceur.syntax.trees.BreakStatement;34 var CallExpression = traceur.syntax.trees.CallExpression;35 var CaseClause = traceur.syntax.trees.CaseClause;36 var Catch = traceur.syntax.trees.Catch;37 var CascadeExpression = traceur.syntax.trees.CascadeExpression;38 var ClassDeclaration = traceur.syntax.trees.ClassDeclaration;39 var ClassExpression = traceur.syntax.trees.ClassExpression;40 var CommaExpression = traceur.syntax.trees.CommaExpression;41 var ComprehensionFor = traceur.syntax.trees.ComprehensionFor;42 var ConditionalExpression = traceur.syntax.trees.ConditionalExpression;43 var ContinueStatement = traceur.syntax.trees.ContinueStatement;44 var DebuggerStatement = traceur.syntax.trees.DebuggerStatement;45 var DefaultClause = traceur.syntax.trees.DefaultClause;46 var DoWhileStatement = traceur.syntax.trees.DoWhileStatement;47 var EmptyStatement = traceur.syntax.trees.EmptyStatement;48 var ExportDeclaration = traceur.syntax.trees.ExportDeclaration;49 var ExportMapping = traceur.syntax.trees.ExportMapping;50 var ExportMappingList = traceur.syntax.trees.ExportMappingList;51 var ExportSpecifier = traceur.syntax.trees.ExportSpecifier;52 var ExportSpecifierSet = traceur.syntax.trees.ExportSpecifierSet;53 var ExpressionStatement = traceur.syntax.trees.ExpressionStatement;54 var Finally = traceur.syntax.trees.Finally;55 var ForOfStatement = traceur.syntax.trees.ForOfStatement;56 var ForInStatement = traceur.syntax.trees.ForInStatement;57 var ForStatement = traceur.syntax.trees.ForStatement;58 var FormalParameterList = traceur.syntax.trees.FormalParameterList;59 var FunctionDeclaration = traceur.syntax.trees.FunctionDeclaration;60 var GeneratorComprehension = traceur.syntax.trees.GeneratorComprehension;61 var GetAccessor = traceur.syntax.trees.GetAccessor;62 var IdentifierExpression = traceur.syntax.trees.IdentifierExpression;63 var IdentifierToken = traceur.syntax.IdentifierToken;64 var IfStatement = traceur.syntax.trees.IfStatement;65 var ImportDeclaration = traceur.syntax.trees.ImportDeclaration;66 var ImportBinding = traceur.syntax.trees.ImportBinding;67 var ImportSpecifier = traceur.syntax.trees.ImportSpecifier;68 var ImportSpecifierSet = traceur.syntax.trees.ImportSpecifierSet;69 var LabelledStatement = traceur.syntax.trees.LabelledStatement;70 var LiteralExpression = traceur.syntax.trees.LiteralExpression;71 var MemberExpression = traceur.syntax.trees.MemberExpression;72 var MemberLookupExpression = traceur.syntax.trees.MemberLookupExpression;73 var MissingPrimaryExpression = traceur.syntax.trees.MissingPrimaryExpression;74 var ModuleDeclaration = traceur.syntax.trees.ModuleDeclaration;75 var ModuleDefinition = traceur.syntax.trees.ModuleDefinition;76 var ModuleExpression = traceur.syntax.trees.ModuleExpression;77 var ModuleRequire = traceur.syntax.trees.ModuleRequire;78 var ModuleSpecifier = traceur.syntax.trees.ModuleSpecifier;79 var NewExpression = traceur.syntax.trees.NewExpression;80 var NullTree = traceur.syntax.trees.NullTree;81 var ObjectLiteralExpression = traceur.syntax.trees.ObjectLiteralExpression;82 var ObjectPattern = traceur.syntax.trees.ObjectPattern;83 var ObjectPatternField = traceur.syntax.trees.ObjectPatternField;84 var ParenExpression = traceur.syntax.trees.ParenExpression;85 var ParseTreeType = traceur.syntax.trees.ParseTreeType;86 var PostfixExpression = traceur.syntax.trees.PostfixExpression;87 var Program = traceur.syntax.trees.Program;88 var PropertyMethodAssignment = traceur.syntax.trees.PropertyMethodAssignment;89 var PropertyNameAssignment = traceur.syntax.trees.PropertyNameAssignment;90 var PropertyNameShorthand = traceur.syntax.trees.PropertyNameShorthand;91 var QuasiLiteralExpression = traceur.syntax.trees.QuasiLiteralExpression;92 var QuasiLiteralPortion = traceur.syntax.trees.QuasiLiteralPortion;93 var QuasiSubstitution = traceur.syntax.trees.QuasiSubstitution;94 var RestParameter = traceur.syntax.trees.RestParameter;95 var ReturnStatement = traceur.syntax.trees.ReturnStatement;96 var SetAccessor = traceur.syntax.trees.SetAccessor;97 var SpreadExpression = traceur.syntax.trees.SpreadExpression;98 var SpreadPatternElement = traceur.syntax.trees.SpreadPatternElement;99 var SuperExpression = traceur.syntax.trees.SuperExpression;100 var SwitchStatement = traceur.syntax.trees.SwitchStatement;101 var ThisExpression = traceur.syntax.trees.ThisExpression;102 var ThrowStatement = traceur.syntax.trees.ThrowStatement;103 var TryStatement = traceur.syntax.trees.TryStatement;104 var UnaryExpression = traceur.syntax.trees.UnaryExpression;105 var VariableDeclaration = traceur.syntax.trees.VariableDeclaration;106 var VariableDeclarationList = traceur.syntax.trees.VariableDeclarationList;107 var VariableStatement = traceur.syntax.trees.VariableStatement;108 var WhileStatement = traceur.syntax.trees.WhileStatement;109 var WithStatement = traceur.syntax.trees.WithStatement;110 var YieldStatement = traceur.syntax.trees.YieldStatement;111 var createBindingIdentifier = traceur.codegeneration.ParseTreeFactory.createBindingIdentifier;112 var options = traceur.options.parse;113 /**114 * Parses a javascript file.115 *116 * The various this.parseX_() methods never return null - even when parse errors are encountered.117 * Typically this.parseX_() will return a XTree ParseTree. Each ParseTree that is created includes its118 * source location. The typical pattern for a this.parseX_() method is:119 *120 * XTree this.parseX_() {121 * var start = this.getTreeStartLocation_();122 * parse X grammar element and its children123 * return new XTree(this.getTreeLocation_(start), children);124 * }125 *126 * this.parseX_() methods must consume at least 1 token - even in error cases. This prevents infinite127 * loops in the parser.128 *129 * Many this.parseX_() methods are matched by a 'boolean this.peekX_()' method which will return true if130 * the beginning of an X appears at the current location. There are also this.peek_() methods which131 * examine the next token. this.peek_() methods must not consume any tokens.132 *133 * The this.eat_() method consumes a token and reports an error if the consumed token is not of the134 * expected type. The this.eatOpt_() methods consume the next token iff the next token is of the expected135 * type and return the consumed token or null if no token was consumed.136 *137 * When parse errors are encountered, an error should be reported and the parse should return a best138 * guess at the current parse tree.139 *140 * When parsing lists, the preferred pattern is:141 * this.eat_(LIST_START);142 * var elements = [];143 * while (this.peekListElement_()) {144 * elements.push(this.parseListElement_());145 * }146 * this.eat_(LIST_END);147 */148 function Parser(errorReporter, var_args) {149 this.errorReporter_ = errorReporter;150 var scanner;151 if (arguments[1] instanceof traceur.syntax.Scanner) {152 scanner = arguments[1];153 } else {154 scanner = new traceur.syntax.Scanner(errorReporter, arguments[1],155 arguments[2]);156 }157 this.scanner_ = scanner;158 }159 /**160 * Differentiates between parsing for 'In' vs. 'NoIn'161 * Variants of expression grammars.162 */163 var Expression = {164 NO_IN: 'NO_IN',165 NORMAL: 'NORMAL'166 };167 /**168 * Enum for determining if the initializer is needed in a variable declaration169 * with a destructuring pattern.170 * @enum {string}171 */172 var DestructuringInitializer = {173 REQUIRED: 'REQUIRED',174 OPTIONAL: 'OPTIONAL'175 };176 function followedByCommaOrCloseSquare(token) {177 return token.type === TokenType.COMMA ||178 token.type === TokenType.CLOSE_SQUARE;179 }180 function followedByCommaOrCloseCurly(token) {181 return token.type === TokenType.COMMA ||182 token.type === TokenType.CLOSE_CURLY;183 }184 function followedByInOrOf(token) {185 return token.type === TokenType.IN ||186 token.type === TokenType.IDENTIFIER &&187 token.value === PredefinedName.OF;188 }189 /**190 * Enum used to determine if an initializer is allowed or not.191 * @enum {string}192 */193 var Initializer = {194 ALLOWED: 'ALLOWED',195 REQUIRED: 'REQUIRED'196 };197 Parser.prototype = {198 /**199 * Keeps track of whether we currently allow yield expressions.200 * @type {boolean}201 * @private202 */203 allowYield_: false,204 // 14 Program205 /**206 * @return {Program}207 */208 parseProgram: function(opt_load) {209 //var t = new Timer("Parse Program");210 var start = this.getTreeStartLocation_();211 var programElements = this.parseProgramElements_(!!opt_load);212 this.eat_(TokenType.END_OF_FILE);213 //t.end();214 return new Program(this.getTreeLocation_(start), programElements);215 },216 /**217 * @return {Array.<ParseTree>}218 * @private219 */220 parseProgramElements_: function(load) {221 var result = [];222 while (!this.peek_(TokenType.END_OF_FILE)) {223 var programElement = this.parseProgramElement_(load);224 if (!programElement) {225 return null;226 }227 result.push(programElement);228 }229 return result;230 },231 /**232 * @return {boolean}233 * @private234 */235 peekProgramElement_: function() {236 return this.peekFunction_() ||237 this.peekVariableDeclarationList_() ||238 this.peekImportDeclaration_() ||239 this.peekExportDeclaration_() ||240 this.peekModuleDeclaration_() ||241 this.peekClassDeclaration_() ||242 this.peekStatement_();243 },244 /**245 * @return {ParseTree}246 * @private247 */248 parseProgramElement_: function(load) {249 if (this.peekVariableDeclarationList_()) {250 return this.parseVariableStatement_();251 }252 // Function is handled in parseStatement_253 // Class is handled in parseStatement_254 if (this.peekImportDeclaration_(load)) {255 return this.parseImportDeclaration_(load);256 }257 if (this.peekExportDeclaration_(load)) {258 return this.parseExportDeclaration_(load);259 }260 if (this.peekModuleDeclaration_(load)) {261 return this.parseModuleDeclaration_(load);262 }263 return this.parseStatement_();264 },265 // ClassDeclaration266 // ModuleDeclaration267 // TODO: ImportDeclaration268 // TODO: ScriptBlock269 // Statement (other than BlockStatement)270 // FunctionDeclaration271 /*272 peekScriptElement_: function() {273 return this.peekModuleDeclaration_() ||274 this.peekSourceElement_();275 }276 */277 // module identifier { ModuleElement* }278 /**279 * @return {boolean}280 * @private281 */282 peekModuleDefinition_: function() {283 return this.peekPredefinedString_(PredefinedName.MODULE) &&284 this.peek_(TokenType.IDENTIFIER, 1) &&285 this.peek_(TokenType.OPEN_CURLY, 2);286 },287 /**288 * @return {ParseTree}289 * @private290 */291 parseModuleDefinition_: function(load) {292 // ModuleDeclaration ::= "module" ModuleSpecifier(load) ("," ModuleSpecifier(load))* ";"293 // | ModuleDefinition(load)294 // ModuleDefinition(load) ::= "module" Identifier "{" ModuleBody(load) "}"295 // ModuleSpecifier(load) ::= Identifier "from" ModuleExpression(load)296 var start = this.getTreeStartLocation_();297 this.eatId_(); // module298 var name = this.eatId_();299 this.eat_(TokenType.OPEN_CURLY);300 var result = [];301 while (this.peekModuleElement_()) {302 result.push(this.parseModuleElement_(load));303 }304 this.eat_(TokenType.CLOSE_CURLY);305 return new ModuleDefinition(this.getTreeLocation_(start), name, result);306 },307 // ModuleSpecifier(load) ::= Identifier "from" ModuleExpression(load)308 parseModuleSpecifier_: function(load) {309 var start = this.getTreeStartLocation_();310 var identifier = this.eatId_();311 this.eatId_(PredefinedName.FROM);312 var expression = this.parseModuleExpression_(load);313 return new ModuleSpecifier(this.getTreeLocation_(start), identifier,314 expression);315 },316 parseModuleExpression_: function(load) {317 // ModuleExpression(load) ::= ModuleReference(load)318 // | ModuleExpression(load) "." IdentifierName319 var start = this.getTreeStartLocation_();320 var reference = this.parseModuleReference_(load);321 var identifierNames = [];322 while (this.peek_(TokenType.PERIOD) && this.peekIdName_(1)) {323 this.eat_(TokenType.PERIOD);324 identifierNames.push(this.eatIdName_());325 }326 return new ModuleExpression(this.getTreeLocation_(start), reference,327 identifierNames);328 },329 /**330 * @private331 * @return {ModeuleRequireTree|IdentifierExpression}332 */333 parseModuleReference_: function(load) {334 // ModuleReference(load) ::= Identifier335 // | [load = true] StringLiteral336 var start = this.getTreeStartLocation_();337 if (load && this.peek_(TokenType.STRING)) {338 var url = this.eat_(TokenType.STRING);339 return new ModuleRequire(this.getTreeLocation_(start), url);340 }341 return this.parseIdentifierExpression_();342 },343 // ClassDeclaration344 // ImportDeclaration345 // ExportDeclaration346 // ModuleDeclaration347 // TODO: ModuleBlock348 // Statement (other than BlockStatement)349 // FunctionDeclaration350 /**351 * @return {boolean}352 * @private353 */354 peekModuleElement_: function() {355 // ModuleElement is currently same as ProgramElement.356 return this.peekProgramElement_();357 },358 /**359 * @return {ParseTree}360 * @private361 */362 parseModuleElement_: function(load) {363 // ModuleElement is currently same as ProgramElement.364 return this.parseProgramElement_(load);365 },366 // ImportDeclaration ::= 'import' ImportBinding (',' ImportBinding)* ';'367 /**368 * @return {boolean}369 * @private370 */371 peekImportDeclaration_: function() {372 return options.modules && this.peek_(TokenType.IMPORT);373 },374 // ImportDeclaration(load) ::= "import" ImportBinding(load)375 // ("," ImportBinding(load))* ";"376 /**377 * @return {ParseTree}378 * @private379 */380 parseImportDeclaration_: function(load) {381 var start = this.getTreeStartLocation_();382 this.eat_(TokenType.IMPORT);383 var importBindings = [];384 importBindings.push(this.parseImportBinding_(load));385 while (this.peek_(TokenType.COMMA)) {386 this.eat_(TokenType.COMMA);387 importBindings.push(this.parseImportBinding_(load));388 }389 this.eatPossibleImplicitSemiColon_();390 return new ImportDeclaration(this.getTreeLocation_(start),391 importBindings);392 },393 // ImportBinding(load) ::= ImportSpecifierSet "from" ModuleExpression(load)394 /**395 * @return {ParseTree}396 * @private397 */398 parseImportBinding_: function(load) {399 var start = this.getTreeStartLocation_();400 var importSpecifierSet = this.parseImportSpecifierSet_();401 this.eatId_(PredefinedName.FROM);402 var moduleExpression = this.parseModuleExpression_(load);403 return new ImportBinding(this.getTreeLocation_(start),404 moduleExpression, importSpecifierSet);405 },406 //ImportSpecifierSet ::= "*"407 // | IdentifierName408 // | "{" (ImportSpecifier ("," ImportSpecifier)*)? ","? "}"409 /**410 * @param {SourcePosition} start411 * @param {Array.<IdentifierToken>} qualifiedPath412 * @return {ParseTree|Token|Array.<Token>}413 * @private414 */415 parseImportSpecifierSet_: function() {416 if (this.peek_(TokenType.OPEN_CURLY)) {417 var start = this.getTreeStartLocation_();418 this.eat_(TokenType.OPEN_CURLY);419 var specifiers = [this.parseImportSpecifier_()];420 while (this.peek_(TokenType.COMMA)) {421 this.eat_(TokenType.COMMA);422 if (this.peek_(TokenType.CLOSE_CURLY))423 break;424 specifiers.push(this.parseImportSpecifier_());425 }426 this.eat_(TokenType.CLOSE_CURLY);427 return new ImportSpecifierSet(this.getTreeLocation_(start), specifiers);428 }429 if (this.peek_(TokenType.STAR)) {430 var star = this.eat_(TokenType.STAR);431 return new ImportSpecifierSet(this.getTreeLocation_(start), star);432 }433 return this.parseIdentifierNameExpression_();434 },435 // ImportSpecifier ::= IdentifierName (":" Identifier)?436 /**437 * @return {ParseTree}438 * @private439 */440 parseImportSpecifier_: function() {441 var start = this.getTreeStartLocation_();442 var lhs = this.eatIdName_();443 var rhs = null;444 if (this.peek_(TokenType.COLON)) {445 this.eat_(TokenType.COLON);446 rhs = this.eatId_();447 }448 return new ImportSpecifier(this.getTreeLocation_(start),449 lhs, rhs);450 },451 // export VariableStatement452 // export FunctionDeclaration453 // export ConstStatement454 // export ClassDeclaration455 // export module ModuleDefinition456 /**457 * @return {boolean}458 * @private459 */460 peekExportDeclaration_: function(load) {461 return options.modules && this.peek_(TokenType.EXPORT);462 },463 /**464 * @return {ParseTree}465 * @private466 */467 parseExportDeclaration_: function(load) {468 var start = this.getTreeStartLocation_();469 this.eat_(TokenType.EXPORT);470 var exportTree;471 switch (this.peekType_()) {472 case TokenType.CONST:473 case TokenType.LET:474 case TokenType.VAR:475 exportTree = this.parseVariableStatement_();476 break;477 case TokenType.FUNCTION:478 exportTree = this.parseFunctionDeclaration_();479 break;480 case TokenType.CLASS:481 exportTree = this.parseClassDeclaration_();482 break;483 case TokenType.IDENTIFIER:484 if (this.peekModuleDeclaration_(load)) {485 exportTree = this.parseModuleDeclaration_(load);486 } else {487 exportTree = this.parseExportMappingList_();488 }489 break;490 case TokenType.OPEN_CURLY:491 exportTree = this.parseExportMappingList_();492 break;493 default:494 this.reportError_('Unexpected symbol \'' + this.peekToken_() + '\'');495 return null;496 }497 return new ExportDeclaration(this.getTreeLocation_(start), exportTree);498 },499 parseExportMappingList_: function() {500 // This is part of the ExportDeclaration production501 // ExportMapping ("," ExportMapping)*502 var start = this.getTreeStartLocation_();503 var mappings = [this.parseExportMapping_()];504 while (this.peek_(TokenType.COMMA)) {505 this.eat_(TokenType.COMMA);506 mappings.push(this.parseExportMapping_());507 }508 this.eatPossibleImplicitSemiColon_();509 return new ExportMappingList(this.getTreeEndLocation_(start), mappings);510 },511 peekExportMapping_: function() {512 return this.peek_(TokenType.OPEN_CURLY) || this.peekId_();513 },514 parseExportMapping_: function() {515 // ExportMapping ::= ExportSpecifierSet ("from" ModuleExpression(false))?516 var start = this.getTreeStartLocation_();517 var specifierSet = this.parseExportSpecifierSet_();518 var expression = null;519 if (this.peekPredefinedString_(PredefinedName.FROM)) {520 this.eatId_(PredefinedName.FROM);521 expression = this.parseModuleExpression_(false);522 }523 return new ExportMapping(this.getTreeLocation_(start), expression,524 specifierSet);525 },526 peekExportSpecifierSet_: function() {527 return this.peek_(TokenType.OPEN_CURLY) ||528 this.peekIdName_();529 },530 parseExportSpecifierSet_: function() {531 // ExportSpecifierSet ::= Identifier532 // | "{" ExportSpecifier ("," ExportSpecifier)* ","? "}"533 if (!this.peek_(TokenType.OPEN_CURLY))534 return this.parseIdentifierExpression_();535 var start = this.getTreeStartLocation_();536 this.eat_(TokenType.OPEN_CURLY);537 var specifiers = [this.parseExportSpecifier_()];538 while (this.peek_(TokenType.COMMA)) {539 this.eat_(TokenType.COMMA);540 if (this.peek_(TokenType.CLOSE_CURLY))541 break;542 specifiers.push(this.parseExportSpecifier_());543 }544 this.eat_(TokenType.CLOSE_CURLY);545 return new ExportSpecifierSet(this.getTreeLocation_(start),546 specifiers);547 },548 parseExportSpecifier_: function() {549 // ExportSpecifier ::= Identifier550 // | IdentifierName ":" Identifier551 var start = this.getTreeStartLocation_();552 var lhs, rhs = null;553 if (this.peek_(TokenType.COLON, 1)) {554 lhs = this.eatIdName_();555 this.eat_(TokenType.COLON);556 rhs = this.eatId_();557 } else {558 lhs = this.eatId_();559 }560 return new ExportSpecifier(this.getTreeLocation_(start), lhs, rhs);561 },562 peekId_: function(opt_index) {563 return this.peek_(TokenType.IDENTIFIER, opt_index);564 },565 peekIdName_: function(opt_index) {566 var type = this.peekType_(opt_index);567 return type == TokenType.IDENTIFIER || Keywords.isKeyword(type);568 },569 // TODO: ModuleLoadRedeclarationList570 // ModuleDefinition571 /**572 * @return {boolean}573 * @private574 */575 peekModuleDeclaration_: function() {576 // ModuleDeclaration ::= "module" ModuleSpecifier(load) ("," ModuleSpecifier(load))* ";"577 // | ModuleDefinition(load)578 // ModuleDefinition(load) ::= "module" Identifier "{" ModuleBody(load) "}"579 // ModuleSpecifier(load) ::= Identifier "from" ModuleExpression(load)580 return options.modules &&581 this.peekPredefinedString_(PredefinedName.MODULE) &&582 this.peek_(TokenType.IDENTIFIER, 1) &&583 (this.peekPredefinedString_(PredefinedName.FROM, 2) ||584 this.peek_(TokenType.OPEN_CURLY, 2));585 },586 /**587 * @return {ParseTree}588 * @private589 */590 parseModuleDeclaration_: function(load) {591 if (this.peekModuleDefinition_(load))592 return this.parseModuleDefinition_(load);593 var start = this.getTreeStartLocation_();594 this.eatId_(); // module595 var specifiers = [this.parseModuleSpecifier_(load)];596 while (this.peek_(TokenType.COMMA)) {597 this.eat_(TokenType.COMMA);598 specifiers.push(this.parseModuleSpecifier_(load));599 }600 this.eatPossibleImplicitSemiColon_();601 return new ModuleDeclaration(this.getTreeLocation_(start),602 specifiers);603 },604 /**605 * @return {boolean}606 * @private607 */608 peekClassDeclaration_: function() {609 return options.classes && this.peek_(TokenType.CLASS) && this.peekId_(1);610 },611 parseClassShared_: function(constr) {612 var start = this.getTreeStartLocation_();613 this.eat_(TokenType.CLASS);614 var name = null;615 // Name is optional for ClassExpression616 if (constr == ClassDeclaration ||617 !this.peek_(TokenType.EXTENDS) && !this.peek_(TokenType.OPEN_CURLY)) {618 name = this.parseBindingIdentifier_();619 }620 var superClass = null;621 if (this.peek_(TokenType.EXTENDS)) {622 this.eat_(TokenType.EXTENDS);623 superClass = this.parseAssignmentExpression_();624 }625 this.eat_(TokenType.OPEN_CURLY);626 var elements = this.parseClassElements_();627 this.eat_(TokenType.CLOSE_CURLY);628 return new constr(this.getTreeLocation_(start), name, superClass,629 elements);630 },631 /**632 * @return {ParseTree}633 * @private634 */635 parseClassDeclaration_: function() {636 return this.parseClassShared_(ClassDeclaration);637 },638 /**639 * @return {ParseTree}640 * @private641 */642 parseClassExpression_: function() {643 return this.parseClassShared_(ClassExpression);644 },645 /**646 * @return {Array.<ParseTree>}647 * @private648 */649 parseClassElements_: function() {650 var result = [];651 while (this.peekClassElement_()) {652 result.push(this.parseClassElement_());653 }654 return result;655 },656 /**657 * @return {boolean}658 * @private659 */660 peekClassElement_: function() {661 return options.classes && (this.peekPropertyMethodAssignment_() ||662 this.peekGetAccessor_() || this.peekSetAccessor_());663 },664 /**665 * @return {ParseTree}666 * @private667 */668 parseClassElement_: function() {669 if (this.peekGetAccessor_())670 return this.parseGetAccessor_();671 if (this.peekSetAccessor_())672 return this.parseSetAccessor_();673 return this.parsePropertyMethodAssignment_();674 },675 /**676 * @return {ParseTree}677 * @private678 */679 parseSourceElement_: function() {680 if (this.peekFunction_()) {681 return this.parseFunctionDeclaration_();682 }683 if (this.peekClassDeclaration_()) {684 return this.parseClassDeclaration_();685 }686 // Harmony let block scoped bindings. let can only appear in687 // a block, not as a standalone statement: if() let x ... illegal688 if (this.peekLet_()) {689 return this.parseVariableStatement_();690 }691 // const and var are handled inside parseStatement692 return this.parseStatementStandard_();693 },694 peekLet_: function() {695 return options.blockBinding && this.peek_(TokenType.LET);696 },697 peekConst_: function() {698 return options.blockBinding && this.peek_(TokenType.CONST);699 },700 /**701 * @return {boolean}702 * @private703 */704 peekSourceElement_: function() {705 return this.peekFunction_() || this.peekClassDeclaration_() ||706 this.peekStatementStandard_() || this.peekLet_();707 },708 /**709 * @return {boolean}710 * @private711 */712 peekFunction_: function(opt_index) {713 var index = opt_index || 0;714 // TODO: Remove # functions715 return this.peek_(TokenType.FUNCTION, index) || this.peek_(TokenType.POUND, index);716 },717 // 13 Function Definition718 /**719 * @return {ParseTree}720 * @private721 */722 parseFunctionDeclaration_: function() {723 var start = this.getTreeStartLocation_();724 this.nextToken_(); // function or #725 var isGenerator = this.eatOpt_(TokenType.STAR) != null;726 return this.parseFunctionDeclarationTail_(start, isGenerator,727 this.parseBindingIdentifier_());728 },729 /**730 * @param {SourcePosition} start731 * @param {IdentifierToken} name732 * @return {ParseTree}733 * @private734 */735 parseFunctionDeclarationTail_: function(start, isGenerator, name) {736 this.eat_(TokenType.OPEN_PAREN);737 var formalParameterList = this.parseFormalParameterList_();738 this.eat_(TokenType.CLOSE_PAREN);739 var functionBody = this.parseFunctionBody_(isGenerator);740 return new FunctionDeclaration(this.getTreeLocation_(start), name,741 isGenerator, formalParameterList,742 functionBody);743 },744 /**745 * @return {ParseTree}746 * @private747 */748 parseFunctionExpression_: function() {749 var start = this.getTreeStartLocation_();750 this.nextToken_(); // function or #751 var isGenerator = this.eatOpt_(TokenType.STAR) != null;752 var name = null;753 if (this.peekBindingIdentifier_()) {754 name = this.parseBindingIdentifier_();755 }756 this.eat_(TokenType.OPEN_PAREN);757 var formalParameterList = this.parseFormalParameterList_();758 this.eat_(TokenType.CLOSE_PAREN);759 var functionBody = this.parseFunctionBody_(isGenerator);760 return new FunctionDeclaration(this.getTreeLocation_(start), name,761 isGenerator, formalParameterList,762 functionBody);763 },764 /**765 * @return {FormalParameterList}766 * @private767 */768 parseFormalParameterList_: function() {769 // FormalParameterList :770 // ... Identifier771 // FormalsList772 // FormalsList , ... Identifier773 //774 // FormalsList :775 // FormalParameter776 // FormalsList , FormalParameter777 //778 // FormalParameter :779 // BindingIdentifier Initialiser?780 // BindingPattern Initialiser?781 var start = this.getTreeStartLocation_();782 var formals;783 if (this.peekRest_()) {784 formals = [this.parseRestParameter_()];785 } else {786 formals = this.parseFormalsList_();787 if (this.peek_(TokenType.COMMA)) {788 this.eat_(TokenType.COMMA);789 formals.push(this.parseRestParameter_());790 }791 }792 return new FormalParameterList(this.getTreeLocation_(start), formals);793 },794 parseFormalsList_: function() {795 var formals = [];796 var initializerAllowed = Initializer.ALLOWED;797 while (this.peekFormalParameter_()) {798 var parameter = this.parseFormalParameter_(initializerAllowed);799 if (parameter.initializer)800 initializerAllowed = Initializer.REQUIRED;801 formals.push(parameter);802 // Lookahead to distinguish , ... and , ) which must not be consumed.803 if (this.peek_(TokenType.COMMA) && this.peekFormalParameter_(1))804 this.eat_(TokenType.COMMA);805 }806 return formals;807 },808 peekFormalParameter_: function(opt_index) {809 var index = opt_index || 0;810 return this.peekBindingIdentifier_(index) || this.peekPattern_(index);811 },812 parseFormalParameter_: function(opt_initializerAllowed) {813 return this.parseBindingElement_(opt_initializerAllowed);814 },815 parseRestParameter_: function() {816 var start = this.getTreeStartLocation_();817 this.eat_(TokenType.DOT_DOT_DOT);818 return new RestParameter(this.getTreeLocation_(start),819 this.parseBindingIdentifier_());820 },821 /**822 * @return {Block}823 * @private824 */825 parseFunctionBody_: function(isGenerator) {826 var start = this.getTreeStartLocation_();827 this.eat_(TokenType.OPEN_CURLY);828 var allowYield = this.allowYield_;829 this.allowYield_ = isGenerator;830 var result = this.parseSourceElementList_();831 this.allowYield_ = allowYield;832 this.eat_(TokenType.CLOSE_CURLY);833 return new Block(this.getTreeLocation_(start), result);834 },835 /**836 * @return {Array.<ParseTree>}837 * @private838 */839 parseSourceElementList_: function() {840 var result = [];841 while (this.peekSourceElement_()) {842 var sourceElement = this.parseSourceElement_();843 if (!sourceElement) {844 return null;845 }846 result.push(sourceElement);847 }848 return result;849 },850 /**851 * @return {SpreadExpression}852 * @private853 */854 parseSpreadExpression_: function() {855 if (!options.spread) {856 return this.parseMissingPrimaryExpression_();857 }858 var start = this.getTreeStartLocation_();859 this.eat_(TokenType.DOT_DOT_DOT);860 var operand = this.parseAssignmentExpression_();861 return new SpreadExpression(this.getTreeLocation_(start), operand);862 },863 // 12 Statements864 /**865 * In V8, all source elements may appear where statements occur in the grammar.866 *867 * @return {ParseTree}868 * @private869 */870 parseStatement_: function() {871 return this.parseSourceElement_();872 },873 /**874 * This function reflects the ECMA standard. Most places use parseStatement instead.875 *876 * @return {ParseTree}877 * @private878 */879 parseStatementStandard_: function() {880 switch (this.peekType_()) {881 case TokenType.OPEN_CURLY:882 return this.parseBlock_();883 case TokenType.AWAIT:884 return this.parseAwaitStatement_();885 case TokenType.CONST:886 if (!options.blockBinding) {887 this.reportUnexpectedToken_();888 return null;889 }890 // Fall through.891 case TokenType.VAR:892 return this.parseVariableStatement_();893 case TokenType.SEMI_COLON:894 return this.parseEmptyStatement_();895 case TokenType.IF:896 return this.parseIfStatement_();897 case TokenType.DO:898 return this.parseDoWhileStatement_();899 case TokenType.WHILE:900 return this.parseWhileStatement_();901 case TokenType.FOR:902 return this.parseForStatement_();903 case TokenType.CONTINUE:904 return this.parseContinueStatement_();905 case TokenType.BREAK:906 return this.parseBreakStatement_();907 case TokenType.RETURN:908 return this.parseReturnStatement_();909 case TokenType.YIELD:910 return this.parseYieldStatement_();911 case TokenType.WITH:912 return this.parseWithStatement_();913 case TokenType.SWITCH:914 return this.parseSwitchStatement_();915 case TokenType.THROW:916 return this.parseThrowStatement_();917 case TokenType.TRY:918 return this.parseTryStatement_();919 case TokenType.DEBUGGER:920 return this.parseDebuggerStatement_();921 default:922 if (this.peekLabelledStatement_()) {923 return this.parseLabelledStatement_();924 }925 return this.parseExpressionStatement_();926 }927 },928 /**929 * In V8 all source elements may appear where statements appear in the grammar.930 *931 * @return {boolean}932 * @private933 */934 peekStatement_: function() {935 return this.peekSourceElement_();936 },937 /**938 * This function reflects the ECMA standard. Most places use peekStatement instead.939 *940 * @return {boolean}941 * @private942 */943 peekStatementStandard_: function() {944 switch (this.peekType_()) {945 case TokenType.CONST:946 return options.blockBinding;947 case TokenType.YIELD:948 return options.generators;949 case TokenType.AWAIT:950 return options.deferredFunctions;951 case TokenType.OPEN_CURLY:952 case TokenType.VAR:953 case TokenType.SEMI_COLON:954 case TokenType.IF:955 case TokenType.DO:956 case TokenType.WHILE:957 case TokenType.FOR:958 case TokenType.CONTINUE:959 case TokenType.BREAK:960 case TokenType.RETURN:961 case TokenType.WITH:962 case TokenType.SWITCH:963 case TokenType.THROW:964 case TokenType.TRY:965 case TokenType.DEBUGGER:966 case TokenType.IDENTIFIER:967 case TokenType.THIS:968 case TokenType.CLASS:969 case TokenType.SUPER:970 case TokenType.NUMBER:971 case TokenType.STRING:972 case TokenType.NULL:973 case TokenType.TRUE:974 case TokenType.SLASH: // regular expression literal975 case TokenType.SLASH_EQUAL: // regular expression literal976 case TokenType.FALSE:977 case TokenType.OPEN_SQUARE:978 case TokenType.OPEN_PAREN:979 case TokenType.NEW:980 case TokenType.DELETE:981 case TokenType.VOID:982 case TokenType.TYPEOF:983 case TokenType.PLUS_PLUS:984 case TokenType.MINUS_MINUS:985 case TokenType.PLUS:986 case TokenType.MINUS:987 case TokenType.TILDE:988 case TokenType.BANG:989 case TokenType.BACK_QUOTE:990 return true;991 default:992 return false;993 }994 },995 // 12.1 Block996 /**997 * @return {Block}998 * @private999 */1000 parseBlock_: function() {1001 var start = this.getTreeStartLocation_();1002 this.eat_(TokenType.OPEN_CURLY);1003 // Spec says Statement list. However functions are also embedded in the wild.1004 var result = this.parseSourceElementList_();1005 this.eat_(TokenType.CLOSE_CURLY);1006 return new Block(this.getTreeLocation_(start), result);1007 },1008 /**1009 * @return {Array.<ParseTree>}1010 * @private1011 */1012 parseStatementList_: function() {1013 var result = [];1014 while (this.peekStatement_()) {1015 result.push(this.parseStatement_());1016 }1017 return result;1018 },1019 // 12.2 Variable Statement1020 /**1021 * @return {VariableStatement}1022 * @private1023 */1024 parseVariableStatement_: function() {1025 var start = this.getTreeStartLocation_();1026 var declarations = this.parseVariableDeclarationList_();1027 this.checkInitializers_(declarations);1028 this.eatPossibleImplicitSemiColon_();1029 return new VariableStatement(this.getTreeLocation_(start), declarations);1030 },1031 /**1032 * @param {Expression=} opt_expressionIn1033 * @param {DestructuringInitializer} opt_initializer Whether destructuring1034 * requires an initializer1035 * @return {VariableDeclarationList}1036 * @private1037 */1038 parseVariableDeclarationList_: function(opt_expressionIn, opt_initializer) {1039 var expressionIn = opt_expressionIn || Expression.NORMAL;1040 var initializer = opt_initializer || DestructuringInitializer.REQUIRED;1041 var token = this.peekType_();1042 switch (token) {1043 case TokenType.CONST:1044 case TokenType.LET:1045 if (!options.blockBinding)1046 debugger;1047 case TokenType.VAR:1048 this.eat_(token);1049 break;1050 default:1051 throw Error('unreachable');1052 }1053 var start = this.getTreeStartLocation_();1054 var declarations = [];1055 declarations.push(this.parseVariableDeclaration_(token, expressionIn,1056 initializer));1057 while (this.peek_(TokenType.COMMA)) {1058 this.eat_(TokenType.COMMA);1059 declarations.push(this.parseVariableDeclaration_(token, expressionIn,1060 initializer));1061 }1062 return new VariableDeclarationList(1063 this.getTreeLocation_(start), token, declarations);1064 },1065 /**1066 * VariableDeclaration :1067 * BindingIdentifier Initialiseropt1068 * BindingPattern Initialiser1069 *1070 * VariableDeclarationNoIn :1071 * BindingIdentifier InitialiserNoInopt1072 * BindingPattern InitialiserNoIn1073 *1074 * @param {TokenType} binding1075 * @param {Expression} expressionIn1076 * @param {DestructuringInitializer=} opt_initializer1077 * @return {VariableDeclaration}1078 * @private1079 */1080 parseVariableDeclaration_: function(binding, expressionIn,1081 opt_initializer) {1082 var initRequired = opt_initializer !== DestructuringInitializer.OPTIONAL;1083 var start = this.getTreeStartLocation_();1084 var lvalue;1085 if (this.peekPattern_())1086 lvalue = this.parseBindingPattern_();1087 else1088 lvalue = this.parseBindingIdentifier_();1089 var initializer = null;1090 if (this.peek_(TokenType.EQUAL))1091 initializer = this.parseInitializer_(expressionIn);1092 else if (lvalue.isPattern() && initRequired)1093 this.reportError_('destructuring must have an initializer');1094 return new VariableDeclaration(this.getTreeLocation_(start), lvalue, initializer);1095 },1096 /**1097 * @param {Expression} expressionIn1098 * @return {ParseTree}1099 * @private1100 */1101 parseInitializer_: function(expressionIn) {1102 this.eat_(TokenType.EQUAL);1103 return this.parseAssignmentExpression_(expressionIn);1104 },1105 // 12.3 Empty Statement1106 /**1107 * @return {EmptyStatement}1108 * @private1109 */1110 parseEmptyStatement_: function() {1111 var start = this.getTreeStartLocation_();1112 this.eat_(TokenType.SEMI_COLON);1113 return new EmptyStatement(this.getTreeLocation_(start));1114 },1115 // 12.4 Expression Statement1116 /**1117 * @return {ExpressionStatement}1118 * @private1119 */1120 parseExpressionStatement_: function() {1121 var start = this.getTreeStartLocation_();1122 var expression = this.parseExpression_();1123 this.eatPossibleImplicitSemiColon_();1124 return new ExpressionStatement(this.getTreeLocation_(start), expression);1125 },1126 // 12.5 If Statement1127 /**1128 * @return {IfStatement}1129 * @private1130 */1131 parseIfStatement_: function() {1132 var start = this.getTreeStartLocation_();1133 this.eat_(TokenType.IF);1134 this.eat_(TokenType.OPEN_PAREN);1135 var condition = this.parseExpression_();1136 this.eat_(TokenType.CLOSE_PAREN);1137 var ifClause = this.parseStatement_();1138 var elseClause = null;1139 if (this.peek_(TokenType.ELSE)) {1140 this.eat_(TokenType.ELSE);1141 elseClause = this.parseStatement_();1142 }1143 return new IfStatement(this.getTreeLocation_(start), condition, ifClause, elseClause);1144 },1145 // 12.6 Iteration Statements1146 // 12.6.1 The do-while Statement1147 /**1148 * @return {ParseTree}1149 * @private1150 */1151 parseDoWhileStatement_: function() {1152 var start = this.getTreeStartLocation_();1153 this.eat_(TokenType.DO);1154 var body = this.parseStatement_();1155 this.eat_(TokenType.WHILE);1156 this.eat_(TokenType.OPEN_PAREN);1157 var condition = this.parseExpression_();1158 this.eat_(TokenType.CLOSE_PAREN);1159 this.eatPossibleImplicitSemiColon_();1160 return new DoWhileStatement(this.getTreeLocation_(start), body, condition);1161 },1162 // 12.6.2 The while Statement1163 /**1164 * @return {ParseTree}1165 * @private1166 */1167 parseWhileStatement_: function() {1168 var start = this.getTreeStartLocation_();1169 this.eat_(TokenType.WHILE);1170 this.eat_(TokenType.OPEN_PAREN);1171 var condition = this.parseExpression_();1172 this.eat_(TokenType.CLOSE_PAREN);1173 var body = this.parseStatement_();1174 return new WhileStatement(this.getTreeLocation_(start), condition, body);1175 },1176 // 12.6.3 The for Statement1177 // 12.6.4 The for-in Statement1178 /**1179 * @return {ParseTree}1180 * @private1181 */1182 parseForStatement_: function() {1183 var start = this.getTreeStartLocation_();1184 this.eat_(TokenType.FOR);1185 this.eat_(TokenType.OPEN_PAREN);1186 var self = this;1187 function validate(variables, kind) {1188 if (variables.declarations.length > 1) {1189 self.reportError_(kind +1190 ' statement may not have more than one variable declaration');1191 }1192 var declaration = variables.declarations[0];1193 if (declaration.lvalue.isPattern() && declaration.initializer) {1194 self.reportError_(declaration.initializer.location,1195 'initializer is not allowed in ' + kind + ' loop with pattern');1196 }1197 }1198 if (this.peekVariableDeclarationList_()) {1199 var variables =1200 this.parseVariableDeclarationList_(1201 Expression.NO_IN, DestructuringInitializer.OPTIONAL);1202 if (this.peek_(TokenType.IN)) {1203 // for-in: only one declaration allowed1204 validate(variables, 'for-in');1205 var declaration = variables.declarations[0];1206 // for-in: if let/const binding used, initializer is illegal1207 if (options.blockBinding &&1208 (variables.declarationType == TokenType.LET ||1209 variables.declarationType == TokenType.CONST)) {1210 if (declaration.initializer != null) {1211 this.reportError_('let/const in for-in statement may not have initializer');1212 }1213 }1214 return this.parseForInStatement_(start, variables);1215 } else if (this.peekOf_()) {1216 // for-of: only one declaration allowed1217 validate(variables, 'for-of');1218 // for-of: initializer is illegal1219 var declaration = variables.declarations[0];1220 if (declaration.initializer != null) {1221 this.reportError_('for-of statement may not have initializer');1222 }1223 return this.parseForOfStatement_(start, variables);1224 } else {1225 // for statement: let and const must have initializers1226 this.checkInitializers_(variables);1227 return this.parseForStatement2_(start, variables);1228 }1229 }1230 if (this.peek_(TokenType.SEMI_COLON)) {1231 return this.parseForStatement2_(start, null);1232 }1233 var initializer = this.parseExpression_(Expression.NO_IN);1234 if (initializer.isLeftHandSideExpression() &&1235 (this.peek_(TokenType.IN) || this.peekOf_())) {1236 initializer = this.transformLeftHandSideExpression_(initializer);1237 if (this.peekOf_())1238 return this.parseForOfStatement_(start, initializer);1239 return this.parseForInStatement_(start, initializer);1240 }1241 return this.parseForStatement2_(start, initializer);1242 },1243 peekOf_: function() {1244 return options.forOf && this.peekPredefinedString_(PredefinedName.OF);1245 },1246 // The for-each Statement1247 // for ( { let | var } identifier of expression ) statement1248 /**1249 * @param {SourcePosition} start1250 * @param {ParseTree} initializer1251 * @return {ParseTree}1252 * @private1253 */1254 parseForOfStatement_: function(start, initializer) {1255 this.eatId_(); // of1256 var collection = this.parseExpression_();1257 this.eat_(TokenType.CLOSE_PAREN);1258 var body = this.parseStatement_();1259 return new ForOfStatement(this.getTreeLocation_(start), initializer, collection, body);1260 },1261 /**1262 * Checks variable declaration in variable and for statements.1263 *1264 * @param {VariableDeclarationList} variables1265 * @return {void}1266 * @private1267 */1268 checkInitializers_: function(variables) {1269 if (options.blockBinding &&1270 variables.declarationType == TokenType.CONST) {1271 var type = variables.declarationType;1272 for (var i = 0; i < variables.declarations.length; i++) {1273 if (!this.checkInitializer_(type, variables.declarations[i])) {1274 break;1275 }1276 }1277 }1278 },1279 /**1280 * Checks variable declaration1281 *1282 * @param {TokenType} type1283 * @param {VariableDeclaration} declaration1284 * @return {boolan} Whether the initializer is correct.1285 * @private1286 */1287 checkInitializer_: function(type, declaration) {1288 if (options.blockBinding && type == TokenType.CONST &&1289 declaration.initializer == null) {1290 this.reportError_('const variables must have an initializer');1291 return false;1292 }1293 return true;1294 },1295 /**1296 * @return {boolean}1297 * @private1298 */1299 peekVariableDeclarationList_: function() {1300 switch (this.peekType_()) {1301 case TokenType.VAR:1302 return true;1303 case TokenType.CONST:1304 case TokenType.LET:1305 return options.blockBinding;1306 default:1307 return false;1308 }1309 },1310 // 12.6.3 The for Statement1311 /**1312 * @param {SourcePosition} start1313 * @param {ParseTree} initializer1314 * @return {ParseTree}1315 * @private1316 */1317 parseForStatement2_: function(start, initializer) {1318 this.eat_(TokenType.SEMI_COLON);1319 var condition = null;1320 if (!this.peek_(TokenType.SEMI_COLON)) {1321 condition = this.parseExpression_();1322 }1323 this.eat_(TokenType.SEMI_COLON);1324 var increment = null;1325 if (!this.peek_(TokenType.CLOSE_PAREN)) {1326 increment = this.parseExpression_();1327 }1328 this.eat_(TokenType.CLOSE_PAREN);1329 var body = this.parseStatement_();1330 return new ForStatement(this.getTreeLocation_(start), initializer, condition, increment, body);1331 },1332 // 12.6.4 The for-in Statement1333 /**1334 * @param {SourcePosition} start1335 * @param {ParseTree} initializer1336 * @return {ParseTree}1337 * @private1338 */1339 parseForInStatement_: function(start, initializer) {1340 this.eat_(TokenType.IN);1341 var collection = this.parseExpression_();1342 this.eat_(TokenType.CLOSE_PAREN);1343 var body = this.parseStatement_();1344 return new ForInStatement(this.getTreeLocation_(start), initializer, collection, body);1345 },1346 // 12.7 The continue Statement1347 /**1348 * @return {ParseTree}1349 * @private1350 */1351 parseContinueStatement_: function() {1352 var start = this.getTreeStartLocation_();1353 this.eat_(TokenType.CONTINUE);1354 var name = null;1355 if (!this.peekImplicitSemiColon_()) {1356 name = this.eatIdOpt_();1357 }1358 this.eatPossibleImplicitSemiColon_();1359 return new ContinueStatement(this.getTreeLocation_(start), name);1360 },1361 // 12.8 The break Statement1362 /**1363 * @return {ParseTree}1364 * @private1365 */1366 parseBreakStatement_: function() {1367 var start = this.getTreeStartLocation_();1368 this.eat_(TokenType.BREAK);1369 var name = null;1370 if (!this.peekImplicitSemiColon_()) {1371 name = this.eatIdOpt_();1372 }1373 this.eatPossibleImplicitSemiColon_();1374 return new BreakStatement(this.getTreeLocation_(start), name);1375 },1376 //12.9 The return Statement1377 /**1378 * @return {ParseTree}1379 * @private1380 */1381 parseReturnStatement_: function() {1382 var start = this.getTreeStartLocation_();1383 this.eat_(TokenType.RETURN);1384 var expression = null;1385 if (!this.peekImplicitSemiColon_()) {1386 expression = this.parseExpression_();1387 }1388 this.eatPossibleImplicitSemiColon_();1389 return new ReturnStatement(this.getTreeLocation_(start), expression);1390 },1391 // Harmony: The yield Statement1392 // yield [expression];1393 /**1394 * @return {ParseTree}1395 * @private1396 */1397 parseYieldStatement_: function() {1398 if (!this.allowYield_) {1399 return this.parseMissingPrimaryExpression_(1400 "'yield' expressions are only allowed inside 'function*'");1401 }1402 var start = this.getTreeStartLocation_();1403 this.eat_(TokenType.YIELD);1404 var expression = null;1405 var isYieldFor = this.eatOpt_(TokenType.STAR) != null;1406 if (isYieldFor || !this.peekImplicitSemiColon_()) {1407 expression = this.parseExpression_();1408 }1409 this.eatPossibleImplicitSemiColon_();1410 return new YieldStatement(1411 this.getTreeLocation_(start), expression, isYieldFor);1412 },1413 // Harmony?: The await Statement1414 // TODO: await should be an expression, not a statement1415 // await[ identifier = ] expression;1416 /**1417 * @return {ParseTree}1418 * @private1419 */1420 parseAwaitStatement_: function() {1421 var start = this.getTreeStartLocation_();1422 this.eat_(TokenType.AWAIT);1423 var identifier = null;1424 if (this.peek_(TokenType.IDENTIFIER) && this.peek_(TokenType.EQUAL, 1)) {1425 identifier = this.eatId_();1426 this.eat_(TokenType.EQUAL);1427 }1428 var expression = this.parseExpression_();1429 this.eatPossibleImplicitSemiColon_();1430 return new AwaitStatement(this.getTreeLocation_(start), identifier, expression);1431 },1432 // 12.10 The with Statement1433 /**1434 * @return {ParseTree}1435 * @private1436 */1437 parseWithStatement_: function() {1438 var start = this.getTreeStartLocation_();1439 this.eat_(TokenType.WITH);1440 this.eat_(TokenType.OPEN_PAREN);1441 var expression = this.parseExpression_();1442 this.eat_(TokenType.CLOSE_PAREN);1443 var body = this.parseStatement_();1444 return new WithStatement(this.getTreeLocation_(start), expression, body);1445 },1446 // 12.11 The switch Statement1447 /**1448 * @return {ParseTree}1449 * @private1450 */1451 parseSwitchStatement_: function() {1452 var start = this.getTreeStartLocation_();1453 this.eat_(TokenType.SWITCH);1454 this.eat_(TokenType.OPEN_PAREN);1455 var expression = this.parseExpression_();1456 this.eat_(TokenType.CLOSE_PAREN);1457 this.eat_(TokenType.OPEN_CURLY);1458 var caseClauses = this.parseCaseClauses_();1459 this.eat_(TokenType.CLOSE_CURLY);1460 return new SwitchStatement(this.getTreeLocation_(start), expression, caseClauses);1461 },1462 /**1463 * @return {Array.<ParseTree>}1464 * @private1465 */1466 parseCaseClauses_: function() {1467 var foundDefaultClause = false;1468 var result = [];1469 while (true) {1470 var start = this.getTreeStartLocation_();1471 switch (this.peekType_()) {1472 case TokenType.CASE:1473 this.eat_(TokenType.CASE);1474 var expression = this.parseExpression_();1475 this.eat_(TokenType.COLON);1476 var statements = this.parseCaseStatementsOpt_();1477 result.push(new CaseClause(this.getTreeLocation_(start), expression, statements));1478 break;1479 case TokenType.DEFAULT:1480 if (foundDefaultClause) {1481 this.reportError_('Switch statements may have at most one default clause');1482 } else {1483 foundDefaultClause = true;1484 }1485 this.eat_(TokenType.DEFAULT);1486 this.eat_(TokenType.COLON);1487 result.push(new DefaultClause(this.getTreeLocation_(start), this.parseCaseStatementsOpt_()));1488 break;1489 default:1490 return result;1491 }1492 }1493 },1494 /**1495 * @return {Array.<ParseTree>}1496 * @private1497 */1498 parseCaseStatementsOpt_: function() {1499 return this.parseStatementList_();1500 },1501 // 12.12 Labelled Statement1502 /**1503 * @return {ParseTree}1504 * @private1505 */1506 parseLabelledStatement_: function() {1507 var start = this.getTreeStartLocation_();1508 var name = this.eatId_();1509 this.eat_(TokenType.COLON);1510 return new LabelledStatement(this.getTreeLocation_(start), name,1511 this.parseStatement_());1512 },1513 /**1514 * @return {boolean}1515 * @private1516 */1517 peekLabelledStatement_: function() {1518 return this.peek_(TokenType.IDENTIFIER) &&1519 this.peek_(TokenType.COLON, 1);1520 },1521 // 12.13 Throw Statement1522 /**1523 * @return {ParseTree}1524 * @private1525 */1526 parseThrowStatement_: function() {1527 var start = this.getTreeStartLocation_();1528 this.eat_(TokenType.THROW);1529 var value = null;1530 if (!this.peekImplicitSemiColon_()) {1531 value = this.parseExpression_();1532 }1533 this.eatPossibleImplicitSemiColon_();1534 return new ThrowStatement(this.getTreeLocation_(start), value);1535 },1536 // 12.14 Try Statement1537 /**1538 * @return {ParseTree}1539 * @private1540 */1541 parseTryStatement_: function() {1542 var start = this.getTreeStartLocation_();1543 this.eat_(TokenType.TRY);1544 var body = this.parseBlock_();1545 var catchBlock = null;1546 if (this.peek_(TokenType.CATCH)) {1547 catchBlock = this.parseCatch_();1548 }1549 var finallyBlock = null;1550 if (this.peek_(TokenType.FINALLY)) {1551 finallyBlock = this.parseFinallyBlock_();1552 }1553 if (catchBlock == null && finallyBlock == null) {1554 this.reportError_("'catch' or 'finally' expected.");1555 }1556 return new TryStatement(this.getTreeLocation_(start), body, catchBlock, finallyBlock);1557 },1558 /**1559 * Catch :1560 * catch ( CatchParameter ) Block1561 *1562 * CatchParameter :1563 * BindingIdentifier1564 * BindingPattern1565 *1566 * @return {ParseTree}1567 * @private1568 */1569 parseCatch_: function() {1570 var start = this.getTreeStartLocation_();1571 var catchBlock;1572 this.eat_(TokenType.CATCH);1573 this.eat_(TokenType.OPEN_PAREN);1574 var binding;1575 if (this.peekPattern_())1576 binding = this.parseBindingPattern_();1577 else1578 binding = this.parseBindingIdentifier_();1579 this.eat_(TokenType.CLOSE_PAREN);1580 var catchBody = this.parseBlock_();1581 catchBlock = new Catch(this.getTreeLocation_(start), binding,1582 catchBody);1583 return catchBlock;1584 },1585 /**1586 * @return {ParseTree}1587 * @private1588 */1589 parseFinallyBlock_: function() {1590 var start = this.getTreeStartLocation_();1591 this.eat_(TokenType.FINALLY);1592 var finallyBlock = this.parseBlock_();1593 return new Finally(this.getTreeLocation_(start), finallyBlock);1594 },1595 // 12.15 The Debugger Statement1596 /**1597 * @return {ParseTree}1598 * @private1599 */1600 parseDebuggerStatement_: function() {1601 var start = this.getTreeStartLocation_();1602 this.eat_(TokenType.DEBUGGER);1603 this.eatPossibleImplicitSemiColon_();1604 return new DebuggerStatement(this.getTreeLocation_(start));1605 },1606 // 11.1 Primary Expressions1607 /**1608 * @return {ParseTree}1609 * @private1610 */1611 parsePrimaryExpression_: function() {1612 switch (this.peekType_()) {1613 case TokenType.CLASS:1614 return options.classes ?1615 this.parseClassExpression_() :1616 this.parseMissingPrimaryExpression_();1617 case TokenType.SUPER:1618 return this.parseSuperExpression_();1619 case TokenType.THIS:1620 return this.parseThisExpression_();1621 case TokenType.IDENTIFIER:1622 return this.parseIdentifierExpression_();1623 case TokenType.NUMBER:1624 case TokenType.STRING:1625 case TokenType.TRUE:1626 case TokenType.FALSE:1627 case TokenType.NULL:1628 return this.parseLiteralExpression_();1629 case TokenType.OPEN_SQUARE:1630 return this.parseArrayLiteral_();1631 case TokenType.OPEN_CURLY:1632 return this.parseObjectLiteral_();1633 case TokenType.OPEN_PAREN:1634 return this.parseParenExpression_();1635 case TokenType.SLASH:1636 case TokenType.SLASH_EQUAL:1637 return this.parseRegularExpressionLiteral_();1638 case TokenType.BACK_QUOTE:1639 return this.parseQuasiLiteral_(null);1640 default:1641 return this.parseMissingPrimaryExpression_();1642 }1643 },1644 /**1645 * @return {SuperExpression}1646 * @private1647 */1648 parseSuperExpression_: function() {1649 var start = this.getTreeStartLocation_();1650 this.eat_(TokenType.SUPER);1651 return new SuperExpression(this.getTreeLocation_(start));1652 },1653 /**1654 * @return {ThisExpression}1655 * @private1656 */1657 parseThisExpression_: function() {1658 var start = this.getTreeStartLocation_();1659 this.eat_(TokenType.THIS);1660 return new ThisExpression(this.getTreeLocation_(start));1661 },1662 peekBindingIdentifier_: function(opt_index) {1663 return this.peekId_(opt_index || 0);1664 },1665 parseBindingIdentifier_: function() {1666 var start = this.getTreeStartLocation_();1667 var identifier = this.eatId_();1668 return new BindingIdentifier(this.getTreeLocation_(start), identifier);1669 },1670 /**1671 * @return {IdentifierExpression}1672 * @private1673 */1674 parseIdentifierExpression_: function() {1675 var start = this.getTreeStartLocation_();1676 var identifier = this.eatId_();1677 return new IdentifierExpression(this.getTreeLocation_(start), identifier);1678 },1679 /**1680 * Special case of parseIdentifierExpression_ which allows keywords.1681 * @return {IdentifierExpression}1682 * @private1683 */1684 parseIdentifierNameExpression_: function() {1685 var start = this.getTreeStartLocation_();1686 var identifier = this.eatIdName_();1687 return new IdentifierExpression(this.getTreeLocation_(start), identifier);1688 },1689 /**1690 * @return {LiteralExpression}1691 * @private1692 */1693 parseLiteralExpression_: function() {1694 var start = this.getTreeStartLocation_();1695 var literal = this.nextLiteralToken_();1696 return new LiteralExpression(this.getTreeLocation_(start), literal);1697 },1698 /**1699 * @return {Token}1700 * @private1701 */1702 nextLiteralToken_: function() {1703 return this.nextToken_();1704 },1705 /**1706 * @return {ParseTree}1707 * @private1708 */1709 parseRegularExpressionLiteral_: function() {1710 var start = this.getTreeStartLocation_();1711 var literal = this.nextRegularExpressionLiteralToken_();1712 return new LiteralExpression(this.getTreeLocation_(start), literal);1713 },1714 peekSpread_: function() {1715 return this.peek_(TokenType.DOT_DOT_DOT);1716 },1717 // 11.1.4 Array Literal Expression1718 /**1719 * Parse array literal and delegates to {@code parseArrayComprehension_} as1720 * needed.1721 *1722 * ArrayLiteral :1723 * [ Elisionopt ]1724 * [ ElementList ]1725 * [ ElementList , Elisionopt ]1726 *1727 * ElementList :1728 * Elisionopt AssignmentExpression1729 * Elisionopt ... AssignmentExpression1730 * ElementList , Elisionopt AssignmentExpression1731 * ElementList , Elisionopt SpreadElement1732 *1733 * Elision :1734 * ,1735 * Elision ,1736 *1737 * SpreadElement :1738 * ... AssignmentExpression1739 *1740 * @return {ParseTree}1741 * @private1742 */1743 parseArrayLiteral_: function() {1744 var start = this.getTreeStartLocation_();1745 var expression;1746 var elements = [];1747 var allowFor = options.arrayComprehension;1748 this.eat_(TokenType.OPEN_SQUARE);1749 while (this.peek_(TokenType.COMMA) ||1750 this.peekSpread_() ||1751 this.peekAssignmentExpression_()) {1752 if (this.peek_(TokenType.COMMA)) {1753 expression = new NullTree();1754 allowFor = false;1755 } else {1756 expression = this.parseAssignmentOrSpread_();1757 }1758 if (allowFor && this.peek_(TokenType.FOR))1759 return this.parseArrayComprehension_(start, expression);1760 allowFor = false;1761 elements.push(expression);1762 if (!this.peek_(TokenType.CLOSE_SQUARE)) {1763 this.eat_(TokenType.COMMA);1764 }1765 }1766 this.eat_(TokenType.CLOSE_SQUARE);1767 return new ArrayLiteralExpression(1768 this.getTreeLocation_(start), elements);1769 },1770 /**1771 * Continues parsing array comprehension.1772 *1773 * ArrayComprehension :1774 * [ Assignment  ComprehensionForList ]1775 * [ AssignmentExpression ComprehensionForList if1776 *1777 * ComprehensionForList :1778 * ComprehensionFor1779 * ComprehensionForList ComprehensionFor1780 *1781 * ComprehensionFor :1782 * for ForBinding of Expression1783 *1784 * ForBinding :1785 * BindingIdentifier1786 * BindingPattern1787 *1788 * @param {Location} start1789 * @param {[ParseTree} expression1790 * @return {ParseTree}1791 */1792 parseArrayComprehension_: function(start, expression) {1793 var comprehensionForList = this.parseComprehensionForList_();1794 var ifExpression = this.parseComprehensionIf_();1795 this.eat_(TokenType.CLOSE_SQUARE);1796 return new ArrayComprehension(this.getTreeLocation_(start),1797 expression,1798 comprehensionForList,1799 ifExpression);1800 },1801 // 11.1.4 Object Literal Expression1802 /**1803 * @return {ParseTree}1804 * @private1805 */1806 parseObjectLiteral_: function() {1807 var start = this.getTreeStartLocation_();1808 var result = [];1809 this.eat_(TokenType.OPEN_CURLY);1810 while (this.peekPropertyAssignment_()) {1811 if (this.peekGetAccessor_()) {1812 result.push(this.parseGetAccessor_());1813 this.eatPropertyOptionalComma_();1814 } else if (this.peekSetAccessor_()) {1815 result.push(this.parseSetAccessor_());1816 this.eatPropertyOptionalComma_();1817 // http://wiki.ecmascript.org/doku.php?id=harmony:concise_object_literal_extensions#methods1818 } else if (this.peekPropertyMethodAssignment_()) {1819 result.push(this.parsePropertyMethodAssignment_());1820 this.eatPropertyOptionalComma_();1821 } else {1822 result.push(this.parsePropertyNameAssignment_());1823 // Comma is required after name assignment.1824 if (this.eatOpt_(TokenType.COMMA) == null) {1825 break;1826 }1827 }1828 }1829 this.eat_(TokenType.CLOSE_CURLY);1830 return new ObjectLiteralExpression(this.getTreeLocation_(start), result);1831 },1832 eatPropertyOptionalComma_: function() {1833 if (options.propertyOptionalComma) {1834 this.eatOpt_(TokenType.COMMA);1835 } else {1836 this.eat_(TokenType.COMMA);1837 }1838 },1839 /**1840 * @return {boolean}1841 * @private1842 */1843 peekPropertyAssignment_: function() {1844 var index = +this.peek_(TokenType.STAR);1845 return this.peekPropertyName_(index);1846 },1847 /**1848 * @return {boolean}1849 * @private1850 */1851 peekPropertyName_: function(tokenIndex) {1852 var type = this.peekType_(tokenIndex);1853 switch (type) {1854 case TokenType.IDENTIFIER:1855 case TokenType.STRING:1856 case TokenType.NUMBER:1857 return true;1858 default:1859 return Keywords.isKeyword(type);1860 }1861 },1862 /**1863 * @return {boolean}1864 * @private1865 */1866 peekGetAccessor_: function() {1867 return this.peekPredefinedString_(PredefinedName.GET) &&1868 this.peekPropertyName_(1);1869 },1870 /**1871 * @return {boolean}1872 * @private1873 */1874 peekPredefinedString_: function(string, opt_index) {1875 var index = opt_index || 0;1876 return this.peek_(TokenType.IDENTIFIER, index) && this.peekToken_(index).value === string;1877 },1878 /**1879 * @return {ParseTree}1880 * @private1881 */1882 parseGetAccessor_: function() {1883 var start = this.getTreeStartLocation_();1884 this.eatId_(); // get1885 var propertyName = this.nextToken_();1886 this.eat_(TokenType.OPEN_PAREN);1887 this.eat_(TokenType.CLOSE_PAREN);1888 var body = this.parseFunctionBody_(false);1889 return new GetAccessor(this.getTreeLocation_(start), propertyName, body);1890 },1891 /**1892 * @return {boolean}1893 * @private1894 */1895 peekSetAccessor_: function() {1896 return this.peekPredefinedString_(PredefinedName.SET) &&1897 this.peekPropertyName_(1);1898 },1899 /**1900 * @return {ParseTree}1901 * @private1902 */1903 parseSetAccessor_: function() {1904 var start = this.getTreeStartLocation_();1905 this.eatId_(); // set1906 var propertyName = this.nextToken_();1907 this.eat_(TokenType.OPEN_PAREN);1908 var parameter = this.parsePropertySetParameterList_();1909 this.eat_(TokenType.CLOSE_PAREN);1910 var body = this.parseFunctionBody_(false);1911 return new SetAccessor(this.getTreeLocation_(start), propertyName,1912 parameter, body);1913 },1914 /**1915 * PropertySetParameterList :1916 * BindingIdentifier1917 * BindingPattern1918 */1919 parsePropertySetParameterList_: function() {1920 var start = this.getTreeStartLocation_();1921 var binding;1922 if (this.peekPattern_())1923 binding = this.parseBindingPattern_();1924 else1925 binding = this.parseBindingIdentifier_();1926 return new BindingElement(this.getTreeLocation_(start), binding, null);1927 },1928 /**1929 * @return {ParseTree}1930 * @private1931 */1932 parsePropertyNameAssignment_: function() {1933 var start = this.getTreeStartLocation_();1934 // http://wiki.ecmascript.org/doku.php?id=strawman:object_initialiser_shorthand1935 if (this.peek_(TokenType.COLON, 1)) {1936 var name = this.nextToken_();1937 this.eat_(TokenType.COLON);1938 var value = this.parseAssignmentExpression_();1939 return new PropertyNameAssignment(this.getTreeLocation_(start), name,1940 value);1941 } else {1942 return this.parsePropertyNameShorthand_();1943 }1944 },1945 peekPropertyMethodAssignment_: function() {1946 var index = +this.peek_(TokenType.STAR);1947 return options.propertyMethods &&1948 this.peekPropertyName_(index) &&1949 this.peek_(TokenType.OPEN_PAREN, index + 1);1950 },1951 /**1952 * @return {ParseTree}1953 * @private1954 */1955 parsePropertyMethodAssignment_: function() {1956 var start = this.getTreeStartLocation_();1957 // Note that parsePropertyAssignment_ already limits name to String,1958 // Number & IdentfierName.1959 var isGenerator = this.eatOpt_(TokenType.STAR) != null;1960 var name = this.nextToken_();1961 this.eat_(TokenType.OPEN_PAREN);1962 var formalParameterList = this.parseFormalParameterList_();1963 this.eat_(TokenType.CLOSE_PAREN);1964 var functionBody = this.parseFunctionBody_(isGenerator);1965 return new PropertyMethodAssignment(this.getTreeLocation_(start),1966 name, isGenerator, formalParameterList, functionBody);1967 },1968 /**1969 * @return {ParseTree}1970 * @private1971 */1972 parsePropertyNameShorthand_: function() {1973 var start = this.getTreeStartLocation_();1974 var name = this.eatId_();1975 if (!options.propertyNameShorthand) {1976 this.eat_(TokenType.COLON);1977 return null;1978 }1979 return new PropertyNameShorthand(this.getTreeLocation_(start), name);1980 },1981 /**1982 * @return {ParseTree}1983 * @private1984 */1985 parseParenExpression_: function() {1986 // Parse arrow function will return a ParenExpression if there isn't an1987 // arrow after the ( CoverFormals ).1988 return this.parseArrowFunction_();1989 },1990 /**1991 * @param {string=} opt_message Error message to report.1992 * @return {ParseTree}1993 * @private1994 */1995 parseMissingPrimaryExpression_: function(opt_message) {1996 var start = this.getTreeStartLocation_();1997 this.reportError_(opt_message || 'primary expression expected');1998 var token = this.nextToken_();1999 return new MissingPrimaryExpression(this.getTreeLocation_(start), token);2000 },2001 // 11.14 Expressions2002 /**2003 * @return {boolean}2004 * @private2005 */2006 peekExpression_: function(opt_index) {2007 switch (this.peekType_(opt_index || 0)) {2008 case TokenType.BACK_QUOTE:2009 return options.quasi;2010 case TokenType.BANG:2011 case TokenType.CLASS:2012 case TokenType.DELETE:2013 case TokenType.FALSE:2014 case TokenType.FUNCTION:2015 case TokenType.IDENTIFIER:2016 case TokenType.MINUS:2017 case TokenType.MINUS_MINUS:2018 case TokenType.NEW:2019 case TokenType.NULL:2020 case TokenType.NUMBER:2021 case TokenType.OPEN_CURLY:2022 case TokenType.OPEN_PAREN:2023 case TokenType.OPEN_SQUARE:2024 case TokenType.PLUS:2025 case TokenType.PLUS_PLUS:2026 case TokenType.SLASH: // regular expression literal2027 case TokenType.SLASH_EQUAL:2028 case TokenType.STRING:2029 case TokenType.SUPER:2030 case TokenType.THIS:2031 case TokenType.TILDE:2032 case TokenType.TRUE:2033 case TokenType.TYPEOF:2034 case TokenType.VOID:2035 return true;2036 default:2037 return false;2038 }2039 },2040 /**2041 * Expression :2042 * AssignmentExpression2043 * Expression , AssignmentExpression2044 *2045 * ExpressionNoIn :2046 * AssignmentExpressionNoIn2047 * ExpressionNoIn , AssignmentExpressionNoIn2048 *2049 * @return {ParseTree}2050 * @private2051 */2052 parseExpression_: function(opt_expressionIn) {2053 var expressionIn = opt_expressionIn || Expression.IN;2054 var start = this.getTreeStartLocation_();2055 var result = this.parseAssignmentExpression_(expressionIn);2056 if (this.peek_(TokenType.COMMA)) {2057 var exprs = [];2058 exprs.push(result);2059 // Lookahead to prevent comma expression from consuming , ...2060 while (this.peek_(TokenType.COMMA) &&2061 this.peekAssignmentExpression_(1)) {2062 this.eat_(TokenType.COMMA);2063 exprs.push(this.parseAssignmentExpression_(expressionIn));2064 }2065 return new CommaExpression(this.getTreeLocation_(start), exprs);2066 }2067 return result;2068 },2069 // 11.13 Assignment expressions2070 /**2071 * @return {boolean}2072 * @private2073 */2074 peekAssignmentExpression_: function(opt_index) {2075 return this.peekExpression_(opt_index || 0);2076 },2077 /**2078 * AssignmentExpression :2079 * ConditionalExpression2080 * YieldExpression2081 * ArrowFunction2082 * LeftHandSideExpression = AssignmentExpression2083 * LeftHandSideExpression AssignmentOperator AssignmentExpression2084 *2085 * AssignmentExpressionNoIn :2086 * ConditionalExpressionNoIn2087 * YieldExpression2088 * ArrowFunction2089 * LeftHandSideExpression = AssignmentExpressionNoIn2090 * LeftHandSideExpression AssignmentOperator AssignmentExpressionNoIn2091 *2092 * @param {Expression} expressionIn2093 * @return {ParseTree}2094 * @private2095 */2096 parseAssignmentExpression_: function(opt_expressionIn) {2097 if (this.peekBindingIdentifier_() && this.peekArrow_(1))2098 return this.parseArrowFunction_();2099 // The remaining arrow function cases are handled in2100 // parseParenExpression_.2101 var expressionIn = opt_expressionIn || Expression.NORMAL;2102 var start = this.getTreeStartLocation_();2103 var left = this.parseConditional_(expressionIn);2104 if (this.peekAssignmentOperator_()) {2105 if (this.peek_(TokenType.EQUAL))2106 left = this.transformLeftHandSideExpression_(left);2107 if (!left.isLeftHandSideExpression() && !left.isPattern()) {2108 this.reportError_('Left hand side of assignment must be new, call, member, function, primary expressions or destructuring pattern');2109 }2110 var operator = this.nextToken_();2111 var right = this.parseAssignmentExpression_(expressionIn);2112 return new BinaryOperator(this.getTreeLocation_(start), left, operator, right);2113 }2114 return left;2115 },2116 /**2117 * Transforms a LeftHandSideExpression into a AssignmentPattern if possible.2118 * This returns the transformed tree if it parses as an AssignmentPattern,2119 * otherwise it returns the original tree.2120 * @param {ParseTree} tree2121 * @return {ParseTree}2122 */2123 transformLeftHandSideExpression_: function(tree) {2124 switch (tree.type) {2125 case ParseTreeType.ARRAY_LITERAL_EXPRESSION:2126 case ParseTreeType.OBJECT_LITERAL_EXPRESSION:2127 var errorReporter = new MutedErrorReporter();2128 var p = new Parser(errorReporter,2129 this.scanner_.getFile(),2130 tree.location.start.offset);2131 var transformedTree = p.parseAssignmentPattern_();2132 if (!errorReporter.hadError())2133 return transformedTree;2134 break;2135 case ParseTreeType.PAREN_EXPRESSION:2136 var expression =2137 this.transformLeftHandSideExpression_(tree.expression);2138 if (expression !== tree.expression)2139 return new ParenExpression(tree.location, expression);2140 }2141 return tree;2142 },2143 /**2144 * @return {boolean}2145 * @private2146 */2147 peekAssignmentOperator_: function() {2148 var token = this.peekToken_();2149 return !!token && token.isAssignmentOperator();2150 },2151 // 11.12 Conditional Expression2152 /**2153 * @param {Expression} expressionIn2154 * @return {ParseTree}2155 * @private2156 */2157 parseConditional_: function(expressionIn) {2158 var start = this.getTreeStartLocation_();2159 var condition = this.parseLogicalOR_(expressionIn);2160 if (this.peek_(TokenType.QUESTION)) {2161 this.eat_(TokenType.QUESTION);2162 var left = this.parseAssignmentExpression_();2163 this.eat_(TokenType.COLON);2164 var right = this.parseAssignmentExpression_(expressionIn);2165 return new ConditionalExpression(this.getTreeLocation_(start), condition, left, right);2166 }2167 return condition;2168 },2169 // 11.11 Logical OR2170 /**2171 * @param {Expression} expressionIn2172 * @return {ParseTree}2173 * @private2174 */2175 parseLogicalOR_: function(expressionIn) {2176 var start = this.getTreeStartLocation_();2177 var left = this.parseLogicalAND_(expressionIn);2178 while (this.peek_(TokenType.OR)) {2179 var operator = this.eat_(TokenType.OR);2180 var right = this.parseLogicalAND_(expressionIn);2181 left = new BinaryOperator(this.getTreeLocation_(start), left, operator, right);2182 }2183 return left;2184 },2185 // 11.11 Logical AND2186 /**2187 * @param {Expression} expressionIn2188 * @return {ParseTree}2189 * @private2190 */2191 parseLogicalAND_: function(expressionIn) {2192 var start = this.getTreeStartLocation_();2193 var left = this.parseBitwiseOR_(expressionIn);2194 while (this.peek_(TokenType.AND)) {2195 var operator = this.eat_(TokenType.AND);2196 var right = this.parseBitwiseOR_(expressionIn);2197 left = new BinaryOperator(this.getTreeLocation_(start), left, operator, right);2198 }2199 return left;2200 },2201 // 11.10 Bitwise OR2202 /**2203 * @param {Expression} expressionIn2204 * @return {ParseTree}2205 * @private2206 */2207 parseBitwiseOR_: function(expressionIn) {2208 var start = this.getTreeStartLocation_();2209 var left = this.parseBitwiseXOR_(expressionIn);2210 while (this.peek_(TokenType.BAR)) {2211 var operator = this.eat_(TokenType.BAR);2212 var right = this.parseBitwiseXOR_(expressionIn);2213 left = new BinaryOperator(this.getTreeLocation_(start), left, operator, right);2214 }2215 return left;2216 },2217 // 11.10 Bitwise XOR2218 /**2219 * @param {Expression} expressionIn2220 * @return {ParseTree}2221 * @private2222 */2223 parseBitwiseXOR_: function(expressionIn) {2224 var start = this.getTreeStartLocation_();2225 var left = this.parseBitwiseAND_(expressionIn);2226 while (this.peek_(TokenType.CARET)) {2227 var operator = this.eat_(TokenType.CARET);2228 var right = this.parseBitwiseAND_(expressionIn);2229 left = new BinaryOperator(this.getTreeLocation_(start), left, operator, right);2230 }2231 return left;2232 },2233 // 11.10 Bitwise AND2234 /**2235 * @param {Expression} expressionIn2236 * @return {ParseTree}2237 * @private2238 */2239 parseBitwiseAND_: function(expressionIn) {2240 var start = this.getTreeStartLocation_();2241 var left = this.parseEquality_(expressionIn);2242 while (this.peek_(TokenType.AMPERSAND)) {2243 var operator = this.eat_(TokenType.AMPERSAND);2244 var right = this.parseEquality_(expressionIn);2245 left = new BinaryOperator(this.getTreeLocation_(start), left, operator, right);2246 }2247 return left;2248 },2249 // 11.9 Equality Expression2250 /**2251 * @param {Expression} expressionIn2252 * @return {ParseTree}2253 * @private2254 */2255 parseEquality_: function(expressionIn) {2256 var start = this.getTreeStartLocation_();2257 var left = this.parseRelational_(expressionIn);2258 while (this.peekEqualityOperator_()) {2259 var operator = this.nextToken_();2260 var right = this.parseRelational_(expressionIn);2261 left = new BinaryOperator(this.getTreeLocation_(start), left, operator, right);2262 }2263 return left;2264 },2265 /**2266 * @return {boolean}2267 * @private2268 */2269 peekEqualityOperator_: function() {2270 switch (this.peekType_()) {2271 case TokenType.EQUAL_EQUAL:2272 case TokenType.NOT_EQUAL:2273 case TokenType.EQUAL_EQUAL_EQUAL:2274 case TokenType.NOT_EQUAL_EQUAL:2275 return true;2276 default:2277 if (!options.isExpression)2278 return false;2279 var token = this.peekTokenNoLineTerminator_();2280 return token && token.type === TokenType.IDENTIFIER &&2281 (token.value === PredefinedName.IS ||2282 token.value === PredefinedName.ISNT);2283 }2284 },2285 // 11.8 Relational2286 /**2287 * @param {Expression} expressionIn2288 * @return {ParseTree}2289 * @private2290 */2291 parseRelational_: function(expressionIn) {2292 var start = this.getTreeStartLocation_();2293 var left = this.parseShiftExpression_();2294 while (this.peekRelationalOperator_(expressionIn)) {2295 var operator = this.nextToken_();2296 var right = this.parseShiftExpression_();2297 left = new BinaryOperator(this.getTreeLocation_(start), left, operator, right);2298 }2299 return left;2300 },2301 /**2302 * @param {Expression} expressionIn2303 * @return {boolean}2304 * @private2305 */2306 peekRelationalOperator_: function(expressionIn) {2307 switch (this.peekType_()) {2308 case TokenType.OPEN_ANGLE:2309 case TokenType.CLOSE_ANGLE:2310 case TokenType.GREATER_EQUAL:2311 case TokenType.LESS_EQUAL:2312 case TokenType.INSTANCEOF:2313 return true;2314 case TokenType.IN:2315 return expressionIn == Expression.NORMAL;2316 default:2317 return false;2318 }2319 },2320 // 11.7 Shift Expression2321 /**2322 * @return {ParseTree}2323 * @private2324 */2325 parseShiftExpression_: function() {2326 var start = this.getTreeStartLocation_();2327 var left = this.parseAdditiveExpression_();2328 while (this.peekShiftOperator_()) {2329 var operator = this.nextToken_();2330 var right = this.parseAdditiveExpression_();2331 left = new BinaryOperator(this.getTreeLocation_(start), left, operator, right);2332 }2333 return left;2334 },2335 /**2336 * @return {boolean}2337 * @private2338 */2339 peekShiftOperator_: function() {2340 switch (this.peekType_()) {2341 case TokenType.LEFT_SHIFT:2342 case TokenType.RIGHT_SHIFT:2343 case TokenType.UNSIGNED_RIGHT_SHIFT:2344 return true;2345 default:2346 return false;2347 }2348 },2349 // 11.6 Additive Expression2350 /**2351 * @return {ParseTree}2352 * @private2353 */2354 parseAdditiveExpression_: function() {2355 var start = this.getTreeStartLocation_();2356 var left = this.parseMultiplicativeExpression_();2357 while (this.peekAdditiveOperator_()) {2358 var operator = this.nextToken_();2359 var right = this.parseMultiplicativeExpression_();2360 left = new BinaryOperator(this.getTreeLocation_(start), left, operator, right);2361 }2362 return left;2363 },2364 /**2365 * @return {boolean}2366 * @private2367 */2368 peekAdditiveOperator_: function() {2369 switch (this.peekType_()) {2370 case TokenType.PLUS:2371 case TokenType.MINUS:2372 return true;2373 default:2374 return false;2375 }2376 },2377 // 11.5 Multiplicative Expression2378 /**2379 * @return {ParseTree}2380 * @private2381 */2382 parseMultiplicativeExpression_: function() {2383 var start = this.getTreeStartLocation_();2384 var left = this.parseUnaryExpression_();2385 while (this.peekMultiplicativeOperator_()) {2386 var operator = this.nextToken_();2387 var right = this.parseUnaryExpression_();2388 left = new BinaryOperator(this.getTreeLocation_(start), left, operator, right);2389 }2390 return left;2391 },2392 /**2393 * @return {boolean}2394 * @private2395 */2396 peekMultiplicativeOperator_: function() {2397 switch (this.peekType_()) {2398 case TokenType.STAR:2399 case TokenType.SLASH:2400 case TokenType.PERCENT:2401 return true;2402 default:2403 return false;2404 }2405 },2406 // 11.4 Unary Operator2407 /**2408 * @return {ParseTree}2409 * @private2410 */2411 parseUnaryExpression_: function() {2412 var start = this.getTreeStartLocation_();2413 if (this.peekUnaryOperator_()) {2414 var operator = this.nextToken_();2415 var operand = this.parseUnaryExpression_();2416 return new UnaryExpression(this.getTreeLocation_(start), operator, operand);2417 }2418 return this.parsePostfixExpression_();2419 },2420 /**2421 * @return {boolean}2422 * @private2423 */2424 peekUnaryOperator_: function() {2425 switch (this.peekType_()) {2426 case TokenType.DELETE:2427 case TokenType.VOID:2428 case TokenType.TYPEOF:2429 case TokenType.PLUS_PLUS:2430 case TokenType.MINUS_MINUS:2431 case TokenType.PLUS:2432 case TokenType.MINUS:2433 case TokenType.TILDE:2434 case TokenType.BANG:2435 return true;2436 default:2437 return false;2438 }2439 },2440 // 11.3 Postfix Expression2441 /**2442 * @return {ParseTree}2443 * @private2444 */2445 parsePostfixExpression_: function() {2446 var start = this.getTreeStartLocation_();2447 var operand = this.parseLeftHandSideExpression_();2448 while (this.peekPostfixOperator_()) {2449 var operator = this.nextToken_();2450 operand = new PostfixExpression(this.getTreeLocation_(start), operand, operator);2451 }2452 return operand;2453 },2454 /**2455 * @return {boolean}2456 * @private2457 */2458 peekPostfixOperator_: function() {2459 if (this.peekImplicitSemiColon_()) {2460 return false;2461 }2462 switch (this.peekType_()) {2463 case TokenType.PLUS_PLUS:2464 case TokenType.MINUS_MINUS:2465 return true;2466 default:2467 return false;2468 }2469 },2470 // 11.2 Left hand side expression2471 //2472 // Also inlines the call expression productions2473 /**2474 * LeftHandSideExpression :2475 * NewExpression2476 * CallExpression2477 *2478 * @return {ParseTree}2479 * @private2480 */2481 parseLeftHandSideExpression_: function() {2482 var start = this.getTreeStartLocation_();2483 var operand = this.parseNewExpression_();2484 // this test is equivalent to is member expression2485 if (!(operand instanceof NewExpression) || operand.args != null) {2486 // The Call expression productions2487 while (this.peekCallSuffix_()) {2488 switch (this.peekType_()) {2489 case TokenType.OPEN_PAREN:2490 var args = this.parseArguments_();2491 operand = new CallExpression(this.getTreeLocation_(start),2492 operand, args);2493 break;2494 case TokenType.OPEN_SQUARE:2495 this.eat_(TokenType.OPEN_SQUARE);2496 var member = this.parseExpression_();2497 this.eat_(TokenType.CLOSE_SQUARE);2498 operand = new MemberLookupExpression(this.getTreeLocation_(start),2499 operand, member);2500 break;2501 case TokenType.PERIOD:2502 this.eat_(TokenType.PERIOD);2503 operand = new MemberExpression(this.getTreeLocation_(start),2504 operand, this.eatIdName_());2505 break;2506 case TokenType.PERIOD_OPEN_CURLY:2507 var expressions = this.parseCascadeExpressions_();2508 operand = new CascadeExpression(this.getTreeLocation_(start),2509 operand, expressions);2510 break;2511 case TokenType.BACK_QUOTE:2512 operand = this.parseQuasiLiteral_(operand);2513 break;2514 }2515 }2516 }2517 return operand;2518 },2519 /**2520 * @return {boolean}2521 * @private2522 */2523 peekCallSuffix_: function() {2524 return this.peek_(TokenType.OPEN_PAREN) ||2525 this.peek_(TokenType.OPEN_SQUARE) ||2526 this.peek_(TokenType.PERIOD) ||2527 options.quasi && this.peek_(TokenType.BACK_QUOTE) ||2528 options.cascadeExpression && this.peek_(TokenType.PERIOD_OPEN_CURLY);2529 },2530 // 11.2 Member Expression without the new production2531 /**2532 * @return {ParseTree}2533 * @private2534 */2535 parseMemberExpressionNoNew_: function() {2536 var start = this.getTreeStartLocation_();2537 var operand;2538 if (this.peekFunction_()) {2539 operand = this.parseFunctionExpression_();2540 } else {2541 operand = this.parsePrimaryExpression_();2542 }2543 while (this.peekMemberExpressionSuffix_()) {2544 switch (this.peekType_()) {2545 case TokenType.OPEN_SQUARE:2546 this.eat_(TokenType.OPEN_SQUARE);2547 var member = this.parseExpression_();2548 this.eat_(TokenType.CLOSE_SQUARE);2549 operand = new MemberLookupExpression(this.getTreeLocation_(start),2550 operand, member);2551 break;2552 case TokenType.PERIOD:2553 this.eat_(TokenType.PERIOD);2554 operand = new MemberExpression(this.getTreeLocation_(start),2555 operand, this.eatIdName_());2556 break;2557 case TokenType.PERIOD_OPEN_CURLY:2558 var expressions = this.parseCascadeExpressions_();2559 operand = new CascadeExpression(this.getTreeLocation_(start),2560 operand, expressions);2561 break;2562 case TokenType.BACK_QUOTE:2563 operand = this.parseQuasiLiteral_(operand);2564 break;2565 }2566 }2567 return operand;2568 },2569 parseCascadeExpressions_: function() {2570 this.eat_(TokenType.PERIOD_OPEN_CURLY);2571 var expressions = [];2572 while (this.peekId_() && this.peekAssignmentExpression_()) {2573 expressions.push(this.parseCascadeExpression_());2574 this.eatPossibleImplicitSemiColon_();2575 }2576 this.eat_(TokenType.CLOSE_CURLY);2577 return expressions;2578 },2579 parseCascadeExpression_: function() {2580 var expr = this.parseAssignmentExpression_();2581 var operand;2582 switch (expr.type) {2583 case ParseTreeType.CALL_EXPRESSION:2584 case ParseTreeType.MEMBER_EXPRESSION:2585 case ParseTreeType.MEMBER_LOOKUP_EXPRESSION:2586 case ParseTreeType.CASCADE_EXPRESSION:2587 operand = expr.operand;2588 break;2589 case ParseTreeType.BINARY_OPERATOR:2590 operand = expr.left;2591 break;2592 default:2593 this.reportError_(expr.location,2594 'Invalid expression. Type: ' + expr.type);2595 }2596 if (operand) {2597 switch (operand.type) {2598 case ParseTreeType.MEMBER_EXPRESSION:2599 case ParseTreeType.MEMBER_LOOKUP_EXPRESSION:2600 case ParseTreeType.CALL_EXPRESSION:2601 case ParseTreeType.CASCADE_EXPRESSION:2602 case ParseTreeType.IDENTIFIER_EXPRESSION:2603 break;2604 default:2605 this.reportError_(operand.location,2606 'Invalid expression: ' + operand.type);2607 }2608 }2609 if (expr.type == ParseTreeType.BINARY_OPERATOR &&2610 !expr.operator.isAssignmentOperator()) {2611 this.reportError_(expr.operator, 'Invalid operator: ' + expr.operator);2612 }2613 return expr;2614 },2615 /**2616 * @return {boolean}2617 * @private2618 */2619 peekMemberExpressionSuffix_: function() {2620 return this.peek_(TokenType.OPEN_SQUARE) ||2621 this.peek_(TokenType.PERIOD) ||2622 options.quasi && this.peek_(TokenType.BACK_QUOTE) ||2623 options.cascadeExpression && this.peek_(TokenType.PERIOD_OPEN_CURLY);2624 },2625 // 11.2 New Expression2626 /**2627 * @return {ParseTree}2628 * @private2629 */2630 parseNewExpression_: function() {2631 if (this.peek_(TokenType.NEW)) {2632 var start = this.getTreeStartLocation_();2633 this.eat_(TokenType.NEW);2634 var operand = this.parseNewExpression_();2635 var args = null;2636 if (this.peek_(TokenType.OPEN_PAREN)) {2637 args = this.parseArguments_();2638 }2639 return new NewExpression(this.getTreeLocation_(start), operand, args);2640 } else {2641 return this.parseMemberExpressionNoNew_();2642 }2643 },2644 /**2645 * @return {ArgumentList}2646 * @private2647 */2648 parseArguments_: function() {2649 // ArgumentList :2650 // AssignmentOrSpreadExpression2651 // ArgumentList , AssignmentOrSpreadExpression2652 //2653 // AssignmentOrSpreadExpression :2654 // ... AssignmentExpression2655 // AssignmentExpression2656 var start = this.getTreeStartLocation_();2657 var args = [];2658 this.eat_(TokenType.OPEN_PAREN);2659 while (this.peekAssignmentOrRest_()) {2660 args.push(this.parseAssignmentOrSpread_());2661 if (!this.peek_(TokenType.CLOSE_PAREN)) {2662 this.eat_(TokenType.COMMA);2663 }2664 }2665 this.eat_(TokenType.CLOSE_PAREN);2666 return new ArgumentList(this.getTreeLocation_(start), args);2667 },2668 peekRest_: function(opt_index) {2669 return options.restParameters &&2670 this.peek_(TokenType.DOT_DOT_DOT, opt_index || 0);2671 },2672 /**2673 * Whether we have a spread expression or an assignment next.2674 *2675 * This does not peek the operand for the spread expression. This means that2676 * {@code parseAssignmentOrSpred} might still fail when this returns true.2677 *2678 * @return {boolean}2679 * @private2680 */2681 peekAssignmentOrRest_: function() {2682 return this.peekRest_() || this.peekAssignmentExpression_();2683 },2684 /**2685 * @return {ParseTree}2686 * @private2687 */2688 parseAssignmentOrSpread_: function() {2689 if (this.peekSpread_()) {2690 return this.parseSpreadExpression_();2691 }2692 return this.parseAssignmentExpression_();2693 },2694 /**2695 * Parses arrow functions and paren expressions as well as delegates to2696 * {@code parseGeneratorComprehension_} if this begins a generator2697 * comprehension.2698 *2699 * Arrow function support, see:2700 * http://wiki.ecmascript.org/doku.php?id=strawman:arrow_function_syntax2701 *2702 * Generator comprehensions syntax is in the ES6 draft,2703 * 11.1.7 Generator Comprehensions2704 *2705 * ArrowFunction :2706 * ArrowParameters => ConciseBody2707 *2708 * ArrowParameters :2709 * BindingIdentifer2710 * ( ArrowFormalParameterList )2711 *2712 * ArrowFormalParameterList :2713 * [empty]2714 * FunctionRestParameter2715 * CoverFormalsList2716 * CoverFormalsList, FunctionRestParameter2717 *2718 * ConciseBody :2719 * [lookahead not {] AssignmentExpression2720 * { FunctionBody }2721 *2722 * CoverFormalsList :2723 * Expression2724 *2725 * @param {Expression=} expressionIn2726 * @return {ParseTree}2727 * @private2728 */2729 parseArrowFunction_: function(expressionIn) {2730 var start = this.getTreeStartLocation_();2731 var formals, coverFormals;2732 // BindingIdentifier =>2733 if (this.peekBindingIdentifier_() && this.peekArrow_(1)) {2734 var id = this.parseBindingIdentifier_();2735 formals = [new BindingElement(id.location, id, null)];2736 // We got here through a ParenExpression.2737 } else {2738 this.eat_(TokenType.OPEN_PAREN);2739 // () =>2740 if (this.peek_(TokenType.CLOSE_PAREN)) {2741 this.eat_(TokenType.CLOSE_PAREN);2742 formals = [];2743 // (...2744 } else if (this.peekRest_()) {2745 formals = [this.parseRestParameter_()];2746 this.eat_(TokenType.CLOSE_PAREN);2747 } else {2748 coverFormals = this.parseExpression_();2749 if (coverFormals.type === ParseTreeType.MISSING_PRIMARY_EXPRESSION)2750 return coverFormals;2751 // ( CoverFormals , ...2752 if (this.peek_(TokenType.COMMA) && this.peekRest_(1)) {2753 this.eat_(TokenType.COMMA);2754 formals = this.reparseAsFormalsList_(coverFormals);2755 if (formals)2756 formals.push(this.parseRestParameter_());2757 this.eat_(TokenType.CLOSE_PAREN);2758 // Generator comprehension2759 // ( CoverFormals for2760 } else if (this.peek_(TokenType.FOR) &&2761 options.generatorComprehension) {2762 return this.parseGeneratorComprehension_(start, coverFormals);2763 // ( CoverFormals )2764 } else {2765 this.eat_(TokenType.CLOSE_PAREN);2766 // ( CoverFormals ) =>2767 if (this.peek_(TokenType.ARROW))2768 formals = this.reparseAsFormalsList_(coverFormals);2769 }2770 }2771 }2772 // The cover grammar could not be parsed as FormalsList.2773 if (!formals)2774 return new ParenExpression(this.getTreeLocation_(start), coverFormals);2775 this.eat_(TokenType.ARROW);2776 var body = this.parseConciseBody_();2777 var startLoc = this.getTreeLocation_(start);2778 return new ArrowFunctionExpression(startLoc,2779 new FormalParameterList(startLoc, formals),2780 body);2781 },2782 /**2783 * Reparses the {@code coverFormals} as a FormalsList. This returns null if2784 * {@code coverFormals} cannot be parsed or fully consumed as a FormalsList.2785 * @param {ParseTree} coverFormals The expression that started after the2786 * opening paren in an arrow function.2787 * @return {Array.<ParseTree>} An aray with the items to use in a2788 * FormalsList or {@code null} if there was an error.2789 */2790 reparseAsFormalsList_: function(coverFormals) {2791 var errorReporter = new MutedErrorReporter();2792 var p = new Parser(errorReporter,2793 this.scanner_.getFile(),2794 coverFormals.location.start.offset);2795 var formals = p.parseFormalsList_();2796 // We need to consume the whole coverFormals.2797 if (errorReporter.hadError() || !formals.length ||2798 formals[formals.length - 1].location.end.offset !==2799 coverFormals.location.end.offset) {2800 return null;2801 }2802 return formals;2803 },2804 /** @returns {TokenType} */2805 peekArrow_: function(opt_index) {2806 return options.arrowFunctions && this.peek_(TokenType.ARROW, opt_index);2807 },2808 /**2809 * ConciseBody :2810 * [lookahead not {] AssignmentExpression2811 * { FunctionBody }2812 *2813 * @param {boolean} isGenerator2814 * @return {ParseTree}2815 *2816 * @return {ParseTree} */2817 parseConciseBody_: function() {2818 // The body can be a block or an expression. A '{' is always treated as2819 // the beginning of a block.2820 if (this.peek_(TokenType.OPEN_CURLY))2821 return this.parseBlock_();2822 return this.parseAssignmentExpression_();2823 },2824 /**2825 * Continues parsing generator exressions. The opening paren and the2826 * expression is parsed by parseArrowFunction_.2827 *2828 * https://bugs.ecmascript.org/show_bug.cgi?id=3812829 *2830 * GeneratorComprehension :2831 * ( Expression ComprehensionForList )2832 * ( Expression ComprehensionForList if Expression )2833 *2834 * ComprehensionForList :2835 * ComprehensionFor2836 * ComprehensionForList ComprehensionFor2837 *2838 * ComprehensionFor :2839 * for ForBinding of Expression2840 */2841 parseGeneratorComprehension_: function(start, expression) {2842 var comprehensionForList = this.parseComprehensionForList_();2843 var ifExpression = this.parseComprehensionIf_();2844 this.eat_(TokenType.CLOSE_PAREN);2845 return new GeneratorComprehension(this.getTreeLocation_(start),2846 expression,2847 comprehensionForList,2848 ifExpression);2849 },2850 parseComprehensionForList_: function() {2851 var comprehensionForList = [];2852 while (this.peek_(TokenType.FOR)) {2853 this.eat_(TokenType.FOR);2854 var innerStart = this.getTreeStartLocation_();2855 var left = this.parseForBinding_();2856 this.eatId_(PredefinedName.OF);2857 var iterator = this.parseExpression_();2858 comprehensionForList.push(2859 new ComprehensionFor(this.getTreeLocation_(innerStart),2860 left, iterator));2861 }2862 return comprehensionForList;2863 },2864 parseComprehensionIf_: function() {2865 if (this.peek_(TokenType.IF)) {2866 this.eat_(TokenType.IF);2867 return this.parseExpression_();2868 }2869 return null;2870 },2871 /**2872 * ForBinding :2873 * BindingIdentifier2874 * BindingPattern2875 */2876 parseForBinding_: function() {2877 if (this.peekPattern_())2878 return this.parseBindingPattern_();2879 return this.parseBindingIdentifier_();2880 },2881 // Destructuring; see2882 // http://wiki.ecmascript.org/doku.php?id=harmony:destructuring2883 //2884 // SpiderMonkey is much more liberal in where it allows2885 // parenthesized patterns, for example, it allows [x, ([y, z])] but2886 // those inner parentheses aren't allowed in the grammar on the ES2887 // wiki. This implementation conservatively only allows parentheses2888 // at the top-level of assignment statements.2889 peekPattern_: function(opt_index) {2890 var index = opt_index || 0;2891 return options.destructuring && (this.peekObjectPattern_(index) ||2892 this.peekArrayPattern_(index));2893 },2894 peekArrayPattern_: function(opt_index) {2895 return this.peek_(TokenType.OPEN_SQUARE, opt_index || 0);2896 },2897 peekObjectPattern_: function(opt_index) {2898 return this.peek_(TokenType.OPEN_CURLY, opt_index || 0);2899 },2900 /**2901 * BindingPattern :2902 * ObjectBindingPattern2903 * ArrayBindingPattern2904 */2905 parseBindingPattern_: function() {2906 if (this.peekArrayPattern_())2907 return this.parseArrayBindingPattern_();2908 return this.parseObjectBindingPattern_();2909 },2910 /**2911 * ArrayBindingPattern :2912 * []2913 * [ BindingElementList ]2914 * [ BindingElementList , Elisionopt BindingRestElementopt ]2915 *2916 * BindingElementList :2917 * Elisionopt BindingElement2918 * BindingElementList , Elisionopt BindingElement2919 *2920 * Elision :2921 * ,2922 * Elision ,2923 */2924 parseArrayBindingPattern_: function() {2925 var start = this.getTreeStartLocation_();2926 var elements = [];2927 this.eat_(TokenType.OPEN_SQUARE);2928 while (this.peekBindingElement_() ||2929 this.peek_(TokenType.COMMA) ||2930 this.peekRest_()) {2931 this.parseElisionOpt_(elements);2932 if (this.peekRest_()) {2933 elements.push(this.parseBindingRestElement_());2934 break;2935 } else {2936 elements.push(this.parseBindingElement_());2937 // Trailing commas are not allowed in patterns.2938 if (this.peek_(TokenType.COMMA) &&2939 !this.peek_(TokenType.CLOSE_SQUARE, 1)) {2940 this.eat_(TokenType.COMMA);2941 }2942 }2943 }2944 this.eat_(TokenType.CLOSE_SQUARE);2945 return new ArrayPattern(this.getTreeLocation_(start), elements);2946 },2947 /**2948 * BindingElementList :2949 * Elisionopt BindingElement2950 * BindingElementList , Elisionopt BindingElement2951 */2952 parseBindingElementList_: function(elements) {2953 this.parseElisionOpt_(elements);2954 elements.push(this.parseBindingElement_());2955 while (this.peek_(TokenType.COMMA)) {2956 this.eat_(TokenType.COMMA);2957 this.parseElisionOpt_(elements);2958 elements.push(this.parseBindingElement_());2959 }2960 },2961 /**2962 * Parses the elision opt production and appends null to the2963 * {@code elements} array for every empty elision.2964 *2965 * @param {Array} elements The array to append to.2966 */2967 parseElisionOpt_: function(elements) {2968 while (this.peek_(TokenType.COMMA)) {2969 this.eat_(TokenType.COMMA);2970 elements.push(null);2971 }2972 },2973 /**2974 * BindingElement :2975 * SingleNameBinding2976 * BindingPattern Initialiseropt2977 *2978 * SingleNameBinding :2979 * BindingIdentifier Initialiseropt2980 */2981 peekBindingElement_: function() {2982 return this.peekBindingIdentifier_() || this.peekPattern_();2983 },2984 /**2985 * @param {Initializer} opt_initializer If left out the initializer is2986 * optional and allowed. If set to Initializer.REQUIRED there must be an2987 * initializer.2988 * @return {ParseTree}2989 */2990 parseBindingElement_: function(opt_initializer) {2991 var start = this.getTreeStartLocation_();2992 var binding;2993 if (this.peekPattern_())2994 binding = this.parseBindingPattern_();2995 else2996 binding = this.parseBindingIdentifier_();2997 var initializer = null;2998 if (this.peek_(TokenType.EQUAL) ||2999 opt_initializer === Initializer.REQUIRED) {3000 initializer = this.parseInitializer_();3001 }3002 return new BindingElement(this.getTreeLocation_(start), binding,3003 initializer);3004 },3005 /**3006 * BindingRestElement :3007 * ... BindingIdentifier3008 */3009 parseBindingRestElement_: function() {3010 var start = this.getTreeStartLocation_();3011 this.eat_(TokenType.DOT_DOT_DOT);3012 var identifier = this.parseBindingIdentifier_();3013 return new SpreadPatternElement(this.getTreeLocation_(start), identifier);3014 },3015 /**3016 * ObjectBindingPattern :3017 * {}3018 * { BindingPropertyList }3019 * { BindingPropertyList , }3020 *3021 * BindingPropertyList :3022 * BindingProperty3023 * BindingPropertyList , BindingProperty3024 */3025 parseObjectBindingPattern_: function() {3026 var start = this.getTreeStartLocation_();3027 var elements = [];3028 this.eat_(TokenType.OPEN_CURLY);3029 while (this.peekBindingProperty_()) {3030 elements.push(this.parseBindingProperty_());3031 if (!this.peek_(TokenType.COMMA))3032 break;3033 this.eat_(TokenType.COMMA);3034 }3035 this.eat_(TokenType.CLOSE_CURLY);3036 return new ObjectPattern(this.getTreeLocation_(start), elements);3037 },3038 /**3039 * BindingProperty :3040 * SingleNameBinding3041 * PropertyName : BindingElement3042 *3043 * SingleNameBinding :3044 * BindingIdentifier Initialiseropt3045 */3046 peekBindingProperty_: function() {3047 return this.peekBindingIdentifier_() || this.peekPropertyName_();3048 },3049 parseBindingProperty_: function() {3050 var start = this.getTreeStartLocation_();3051 if (this.peek_(TokenType.COLON, 1)) {3052 var propertyName = this.nextToken_();3053 this.eat_(TokenType.COLON);3054 var binding = this.parseBindingElement_();3055 // TODO(arv): Rename ObjectPatternField to BindingProperty3056 return new ObjectPatternField(this.getTreeLocation_(start),3057 propertyName, binding);3058 }3059 var binding = this.parseBindingIdentifier_();3060 var initializer = null;3061 if (this.peek_(TokenType.EQUAL))3062 initializer = this.parseInitializer_();3063 return new BindingElement(this.getTreeLocation_(start), binding,3064 initializer);3065 },3066 /**3067 * AssignmentPattern :3068 * ObjectAssignmentPattern3069 * ArrayAssignmentPattern3070 */3071 parseAssignmentPattern_: function() {3072 if (this.peekObjectPattern_())3073 return this.parseObjectAssignmentPattern_();3074 return this.parseArrayAssignmentPattern_();3075 },3076 /**3077 * ObjectAssignmentPattern :3078 * {}3079 * { AssignmentPropertyList }3080 * { AssignmentPropertyList , }3081 *3082 * AssignmentPropertyList :3083 * AssignmentProperty3084 * AssignmentPropertyList , AssignmentProperty3085 *3086 * AssignmentProperty :3087 * Identifier3088 * PropertyName : LeftHandSideExpression3089 */3090 parseObjectAssignmentPattern_: function() {3091 var start = this.getTreeStartLocation_();3092 this.eat_(TokenType.OPEN_CURLY);3093 var fields = [];3094 var field;3095 while (this.peekId_() || this.peekPropertyName_()) {3096 if (this.peek_(TokenType.COLON, 1)) {3097 var fieldStart = this.getTreeStartLocation_();3098 var name = this.nextToken_();3099 this.eat_(TokenType.COLON);3100 var left = this.parseLeftHandSideExpression_();3101 left = this.transformLeftHandSideExpression_(left);3102 field = new ObjectPatternField(this.getTreeLocation_(start),3103 name, left);3104 } else {3105 field = this.parseIdentifierExpression_();3106 }3107 fields.push(field);3108 if (this.peek_(TokenType.COMMA))3109 this.eat_(TokenType.COMMA);3110 else3111 break;3112 }3113 this.eat_(TokenType.CLOSE_CURLY);3114 return new ObjectPattern(this.getTreeLocation_(start), fields);3115 },3116 /**3117 * ArrayAssignmentPattern :3118 * [ Elisionopt AssignmentRestElementopt ]3119 * [ AssignmentElementList ]3120 * [ AssignmentElementList , Elisionopt AssignmentRestElementopt ]3121 *3122 * AssignmentElementList :3123 * Elisionopt AssignmentElement3124 * AssignmentElementList , Elisionopt AssignmentElement3125 *3126 * AssignmentElement :3127 * LeftHandSideExpression3128 *3129 * AssignmentRestElement :3130 * ... LeftHandSideExpression3131 */3132 parseArrayAssignmentPattern_: function() {3133 var start = this.getTreeStartLocation_();3134 var elements = [];3135 this.eat_(TokenType.OPEN_SQUARE);3136 while (this.peek_(TokenType.COMMA) ||3137 this.peekRest_() ||3138 this.peekAssignmentExpression_()) {3139 this.parseElisionOpt_(elements);3140 if (this.peekRest_()) {3141 elements.push(this.parseAssignmentRestElement_());3142 break;3143 } else {3144 elements.push(this.parseAssignmentElement_());3145 // Trailing commas are not allowed in patterns.3146 if (this.peek_(TokenType.COMMA) &&3147 !this.peek_(TokenType.CLOSE_SQUARE, 1)) {3148 this.eat_(TokenType.COMMA);3149 }3150 }3151 }3152 this.eat_(TokenType.CLOSE_SQUARE);3153 return new ArrayPattern(this.getTreeLocation_(start), elements);3154 },3155 parseAssignmentRestElement_: function() {3156 var start = this.getTreeStartLocation_();3157 this.eat_(TokenType.DOT_DOT_DOT);3158 var left = this.parseLeftHandSideExpression_();3159 left = this.transformLeftHandSideExpression_(left);3160 return new SpreadPatternElement(this.getTreeLocation_(start), left);3161 },3162 parseAssignmentElement_: function() {3163 var tree = this.parseLeftHandSideExpression_();3164 return this.transformLeftHandSideExpression_(tree);3165 },3166 /**3167 * Quasi Literals3168 *3169 * Quasi ::3170 * FullQuasi3171 * QuasiHead3172 *3173 * FullQuasi ::3174 * ` QuasiCharactersopt `3175 *3176 * QuasiHead ::3177 * ` QuasiCharactersopt ${3178 *3179 * QuasiSubstitutionTail ::3180 * QuasiMiddle3181 * QuasiTail3182 *3183 * QuasiMiddle ::3184 * } QuasiCharactersopt ${3185 *3186 * QuasiTail ::3187 * } QuasiCharactersopt `3188 *3189 * QuasiCharacters ::3190 * QuasiCharacter QuasiCharactersopt3191 *3192 * QuasiCharacter ::3193 * SourceCharacter but not one of ` or \ or $3194 * $ [lookahead not { ]3195 * \ EscapeSequence3196 * LineContinuation3197 *3198 * @param {ParseTree} operand3199 * @return {ParseTree}3200 * @private3201 */3202 parseQuasiLiteral_: function(operand) {3203 if (!options.quasi) {3204 return this.parseMissingPrimaryExpression_();3205 }3206 function pushSubst(tree) {3207 elements.push(new QuasiSubstitution(tree.location, tree));3208 }3209 var start = operand ?3210 operand.location.start : this.getTreeStartLocation_();3211 this.eat_(TokenType.BACK_QUOTE);3212 var elements = [];3213 while (!this.peekEndOfQuasiLiteral_()) {3214 var token = this.nextQuasiLiteralPortionToken_();3215 // start is not the right SourcePosition but we cannot use3216 // getTreeStartLocation_ here since it uses peek_ which is not safe to3217 // use inside parseQuasiLiteral_.3218 elements.push(new QuasiLiteralPortion(this.getTreeLocation_(start),3219 token));3220 if (!this.peekQuasiToken_(TokenType.DOLLAR))3221 break;3222 token = this.nextQuasiSubstitutionToken_();3223 traceur.assert(token.type == TokenType.DOLLAR);3224 this.eat_(TokenType.OPEN_CURLY);3225 var expression = this.parseExpression_();3226 if (!expression)3227 return this.parseMissingPrimaryExpression_();3228 pushSubst(expression);3229 this.eat_(TokenType.CLOSE_CURLY);3230 }3231 this.eat_(TokenType.BACK_QUOTE);3232 return new QuasiLiteralExpression(this.getTreeLocation_(start),3233 operand, elements);3234 },3235 /**3236 * Consume a (possibly implicit) semi-colon. Reports an error if a semi-colon is not present.3237 *3238 * @return {void}3239 * @private3240 */3241 eatPossibleImplicitSemiColon_: function() {3242 if (this.peek_(TokenType.SEMI_COLON) && this.peekToken_().location.start.line == this.getLastLine_()) {3243 this.eat_(TokenType.SEMI_COLON);3244 return;3245 }3246 if (this.peekImplicitSemiColon_()) {3247 return;3248 }3249 this.reportError_('Semi-colon expected');3250 },3251 /**3252 * Returns true if an implicit or explicit semi colon is at the current location.3253 *3254 * @return {boolean}3255 * @private3256 */3257 peekImplicitSemiColon_: function() {3258 return this.getNextLine_() > this.getLastLine_() ||3259 this.peek_(TokenType.SEMI_COLON) ||3260 this.peek_(TokenType.CLOSE_CURLY) ||3261 this.peek_(TokenType.END_OF_FILE);3262 },3263 /**3264 * Returns the line number of the most recently consumed token.3265 *3266 * @return {number}3267 * @private3268 */3269 getLastLine_: function() {3270 return this.scanner_.lastToken.location.end.line;3271 },3272 /**3273 * Returns the line number of the next token.3274 *3275 * @return {number}3276 * @private3277 */3278 getNextLine_: function() {3279 return this.peekToken_().location.start.line;3280 },3281 /**3282 * Consumes the next token if it is of the expected type. Otherwise returns null.3283 * Never reports errors.3284 *3285 * @param {TokenType} expectedTokenType3286 * @return {Token} The consumed token, or null if the next token is not of the expected type.3287 * @private3288 */3289 eatOpt_: function(expectedTokenType) {3290 if (this.peek_(expectedTokenType)) {3291 return this.eat_(expectedTokenType);3292 }3293 return null;3294 },3295 /**3296 * Shorthand for this.eatOpt_(TokenType.IDENTIFIER)3297 *3298 * @return {IdentifierToken}3299 * @private3300 */3301 eatIdOpt_: function() {3302 return (this.peek_(TokenType.IDENTIFIER)) ? this.eatId_() : null;3303 },3304 /**3305 * Shorthand for this.eat_(TokenType.IDENTIFIER)3306 * @param {string=} opt_expected3307 * @return {IdentifierToken}3308 * @private3309 */3310 eatId_: function(opt_expected) {3311 var result = this.eat_(TokenType.IDENTIFIER);3312 if (opt_expected) {3313 if (!result || result.value !== opt_expected) {3314 if (!result)3315 result = this.peekToken_();3316 this.reportError_(result, 'expected "' + opt_expected + '"');3317 return null;3318 }3319 }3320 return result;3321 },3322 /**3323 * Eats an identifier or keyword. Equivalent to IdentifierName in the spec.3324 *3325 * @return {Token}3326 * @private3327 */3328 eatIdName_: function() {3329 var t = this.nextToken_();3330 if (t.type != TokenType.IDENTIFIER) {3331 if (!Keywords.isKeyword(t.type)) {3332 this.reportExpectedError_(t, 'identifier');3333 return null;3334 }3335 return new IdentifierToken(t.location, t.type);3336 }3337 return t;3338 },3339 /**3340 * Consumes the next token. If the consumed token is not of the expected type then3341 * report an error and return null. Otherwise return the consumed token.3342 *3343 * @param {TokenType} expectedTokenType3344 * @return {Token} The consumed token, or null if the next token is not of the expected type.3345 * @private3346 */3347 eat_: function(expectedTokenType) {3348 var token = this.nextToken_();3349 if (token.type != expectedTokenType) {3350 this.reportExpectedError_(token, expectedTokenType);3351 return null;3352 }3353 return token;3354 },3355 /**3356 * Report a 'X' expected error message.3357 * @param {Token} token The location to report the message at.3358 * @param {Object} expected The thing that was expected.3359 *3360 * @return {void}3361 * @private3362 */3363 reportExpectedError_: function(token, expected) {3364 this.reportError_(token, "'" + expected + "' expected");3365 },3366 /**3367 * Returns a SourcePosition for the start of a parse tree that starts at the current location.3368 *3369 * @return {SourcePosition}3370 * @private3371 */3372 getTreeStartLocation_: function() {3373 return this.peekToken_().location.start;3374 },3375 /**3376 * Returns a SourcePosition for the end of a parse tree that ends at the current location.3377 *3378 * @return {SourcePosition}3379 * @private3380 */3381 getTreeEndLocation_: function() {3382 return this.scanner_.lastToken.location.end;3383 },3384 /**3385 * Returns a SourceRange for a parse tree that starts at {start} and ends at the current location.3386 *3387 * @return {SourceRange}3388 * @private3389 */3390 getTreeLocation_: function(start) {3391 return new SourceRange(start, this.getTreeEndLocation_());3392 },3393 /**3394 * Consumes the next token and returns it. Will return a never ending stream of3395 * TokenType.END_OF_FILE at the end of the file so callers don't have to check for EOF explicitly.3396 *3397 * Tokenizing is contextual. this.nextToken_() will never return a regular expression literal.3398 *3399 * @return {Token}3400 * @private3401 */3402 nextToken_: function() {3403 return this.scanner_.nextToken();3404 },3405 /**3406 * Consumes a regular expression literal token and returns it.3407 *3408 * @return {LiteralToken}3409 * @private3410 */3411 nextRegularExpressionLiteralToken_: function() {3412 return this.scanner_.nextRegularExpressionLiteralToken();3413 },3414 nextQuasiLiteralPortionToken_: function() {3415 return this.scanner_.nextQuasiLiteralPortionToken();3416 },3417 nextQuasiIdentifier_: function() {3418 return this.scanner_.nextQuasiIdentifier();3419 },3420 nextQuasiSubstitutionToken_: function() {3421 return this.scanner_.nextQuasiSubstitutionToken();3422 },3423 peekEndOfQuasiLiteral_: function() {3424 return this.peekQuasiToken_(TokenType.BACK_QUOTE) ||3425 this.peekQuasiToken_(TokenType.END_OF_FILE);3426 },3427 peekQuasiToken_: function(type) {3428 return this.scanner_.peekQuasiToken(type);3429 },3430 /**3431 * Returns true if the index-th next token is of the expected type. Does not consume any tokens.3432 *3433 * @param {TokenType} expectedType3434 * @param {number=} opt_index3435 * @return {boolean}3436 * @private3437 */3438 peek_: function(expectedType, opt_index) {3439 return this.peekType_(opt_index || 0) == expectedType;3440 },3441 /**3442 * Returns the TokenType of the index-th next token. Does not consume any tokens.3443 *3444 * @return {TokenType}3445 * @private3446 */3447 peekType_: function(opt_index) {3448 return this.peekToken_(opt_index || 0).type;3449 },3450 /**3451 * Returns the index-th next token. Does not consume any tokens.3452 *3453 * @return {Token}3454 * @private3455 */3456 peekToken_: function(opt_index) {3457 return this.scanner_.peekToken(opt_index || 0);3458 },3459 /**3460 * Returns the index-th next token. Does not allow any line terminator3461 * before the next token. Does not consume any tokens. This returns null if3462 * no token was found before the next line terminator.3463 *3464 * @return {Token}3465 * @private3466 */3467 peekTokenNoLineTerminator_: function(opt_index) {3468 return this.scanner_.peekTokenNoLineTerminator(opt_index || 0);3469 },3470 /**3471 * Reports an error message at a given token.3472 * @param {traceur.util.SourcePostion|Token} token The location to report3473 * the message at.3474 * @param {string} message The message to report in String.format style.3475 *3476 * @return {void}3477 * @private3478 */3479 reportError_: function(var_args) {3480 if (arguments.length == 1) {3481 this.errorReporter_.reportError(this.scanner_.getPosition(),3482 arguments[0]);3483 } else {3484 var location = arguments[0];3485 if (location instanceof Token) {3486 location = location.location;3487 }3488 this.errorReporter_.reportError(location.start, arguments[1]);3489 }3490 },3491 reportUnexpectedToken_: function() {3492 this.reportError_(this.peekToken_(), 'Unexpected token');3493 }3494 };3495 return {3496 Parser: Parser3497 };...

Full Screen

Full Screen

cssLexer.js

Source:cssLexer.js Github

copy

Full Screen

1"use strict";2Object.defineProperty(exports, "__esModule", { value: true });3var chars = require("./chars");4var CssTokenType;5(function (CssTokenType) {6 CssTokenType[CssTokenType["EOF"] = 0] = "EOF";7 CssTokenType[CssTokenType["String"] = 1] = "String";8 CssTokenType[CssTokenType["Comment"] = 2] = "Comment";9 CssTokenType[CssTokenType["Identifier"] = 3] = "Identifier";10 CssTokenType[CssTokenType["Number"] = 4] = "Number";11 CssTokenType[CssTokenType["IdentifierOrNumber"] = 5] = "IdentifierOrNumber";12 CssTokenType[CssTokenType["AtKeyword"] = 6] = "AtKeyword";13 CssTokenType[CssTokenType["Character"] = 7] = "Character";14 CssTokenType[CssTokenType["Whitespace"] = 8] = "Whitespace";15 CssTokenType[CssTokenType["Invalid"] = 9] = "Invalid";16})(CssTokenType = exports.CssTokenType || (exports.CssTokenType = {}));17var CssLexerMode;18(function (CssLexerMode) {19 CssLexerMode[CssLexerMode["ALL"] = 0] = "ALL";20 CssLexerMode[CssLexerMode["ALL_TRACK_WS"] = 1] = "ALL_TRACK_WS";21 CssLexerMode[CssLexerMode["SELECTOR"] = 2] = "SELECTOR";22 CssLexerMode[CssLexerMode["PSEUDO_SELECTOR"] = 3] = "PSEUDO_SELECTOR";23 CssLexerMode[CssLexerMode["PSEUDO_SELECTOR_WITH_ARGUMENTS"] = 4] = "PSEUDO_SELECTOR_WITH_ARGUMENTS";24 CssLexerMode[CssLexerMode["ATTRIBUTE_SELECTOR"] = 5] = "ATTRIBUTE_SELECTOR";25 CssLexerMode[CssLexerMode["AT_RULE_QUERY"] = 6] = "AT_RULE_QUERY";26 CssLexerMode[CssLexerMode["MEDIA_QUERY"] = 7] = "MEDIA_QUERY";27 CssLexerMode[CssLexerMode["BLOCK"] = 8] = "BLOCK";28 CssLexerMode[CssLexerMode["KEYFRAME_BLOCK"] = 9] = "KEYFRAME_BLOCK";29 CssLexerMode[CssLexerMode["STYLE_BLOCK"] = 10] = "STYLE_BLOCK";30 CssLexerMode[CssLexerMode["STYLE_VALUE"] = 11] = "STYLE_VALUE";31 CssLexerMode[CssLexerMode["STYLE_VALUE_FUNCTION"] = 12] = "STYLE_VALUE_FUNCTION";32 CssLexerMode[CssLexerMode["STYLE_CALC_FUNCTION"] = 13] = "STYLE_CALC_FUNCTION";33})(CssLexerMode = exports.CssLexerMode || (exports.CssLexerMode = {}));34var LexedCssResult = (function () {35 function LexedCssResult(error, token) {36 this.error = error;37 this.token = token;38 }39 return LexedCssResult;40}());41exports.LexedCssResult = LexedCssResult;42function generateErrorMessage(input, message, errorValue, index, row, column) {43 return message + " at column " + row + ":" + column + " in expression [" + findProblemCode(input, errorValue, index, column) + ']';44}45exports.generateErrorMessage = generateErrorMessage;46function findProblemCode(input, errorValue, index, column) {47 var endOfProblemLine = index;48 var current = charCode(input, index);49 while (current > 0 && !isNewline(current)) {50 current = charCode(input, ++endOfProblemLine);51 }52 var choppedString = input.substring(0, endOfProblemLine);53 var pointerPadding = '';54 for (var i = 0; i < column; i++) {55 pointerPadding += ' ';56 }57 var pointerString = '';58 for (var i = 0; i < errorValue.length; i++) {59 pointerString += '^';60 }61 return choppedString + '\n' + pointerPadding + pointerString + '\n';62}63exports.findProblemCode = findProblemCode;64var CssToken = (function () {65 function CssToken(index, column, line, type, strValue) {66 this.index = index;67 this.column = column;68 this.line = line;69 this.type = type;70 this.strValue = strValue;71 this.numValue = charCode(strValue, 0);72 }73 return CssToken;74}());75exports.CssToken = CssToken;76var CssLexer = (function () {77 function CssLexer() {78 }79 CssLexer.prototype.scan = function (text, trackComments) {80 if (trackComments === void 0) { trackComments = false; }81 return new CssScanner(text, trackComments);82 };83 return CssLexer;84}());85exports.CssLexer = CssLexer;86function cssScannerError(token, message) {87 var error = Error('CssParseError: ' + message);88 error[ERROR_RAW_MESSAGE] = message;89 error[ERROR_TOKEN] = token;90 return error;91}92exports.cssScannerError = cssScannerError;93var ERROR_TOKEN = 'ngToken';94var ERROR_RAW_MESSAGE = 'ngRawMessage';95function getRawMessage(error) {96 return error[ERROR_RAW_MESSAGE];97}98exports.getRawMessage = getRawMessage;99function getToken(error) {100 return error[ERROR_TOKEN];101}102exports.getToken = getToken;103function _trackWhitespace(mode) {104 switch (mode) {105 case CssLexerMode.SELECTOR:106 case CssLexerMode.PSEUDO_SELECTOR:107 case CssLexerMode.ALL_TRACK_WS:108 case CssLexerMode.STYLE_VALUE:109 return true;110 default:111 return false;112 }113}114var CssScanner = (function () {115 function CssScanner(input, _trackComments) {116 if (_trackComments === void 0) { _trackComments = false; }117 this.input = input;118 this._trackComments = _trackComments;119 this.length = 0;120 this.index = -1;121 this.column = -1;122 this.line = 0;123 this._currentMode = CssLexerMode.BLOCK;124 this._currentError = null;125 this.length = this.input.length;126 this.peekPeek = this.peekAt(0);127 this.advance();128 }129 CssScanner.prototype.getMode = function () {130 return this._currentMode;131 };132 CssScanner.prototype.setMode = function (mode) {133 if (this._currentMode != mode) {134 if (_trackWhitespace(this._currentMode) && !_trackWhitespace(mode)) {135 this.consumeWhitespace();136 }137 this._currentMode = mode;138 }139 };140 CssScanner.prototype.advance = function () {141 if (isNewline(this.peek)) {142 this.column = 0;143 this.line++;144 }145 else {146 this.column++;147 }148 this.index++;149 this.peek = this.peekPeek;150 this.peekPeek = this.peekAt(this.index + 1);151 };152 CssScanner.prototype.peekAt = function (index) {153 return index >= this.length ? chars.$EOF : this.input.charCodeAt(index);154 };155 CssScanner.prototype.consumeEmptyStatements = function () {156 this.consumeWhitespace();157 while (this.peek == chars.$SEMICOLON) {158 this.advance();159 this.consumeWhitespace();160 }161 };162 CssScanner.prototype.consumeWhitespace = function () {163 while (chars.isWhitespace(this.peek) || isNewline(this.peek)) {164 this.advance();165 if (!this._trackComments && isCommentStart(this.peek, this.peekPeek)) {166 this.advance();167 this.advance();168 while (!isCommentEnd(this.peek, this.peekPeek)) {169 if (this.peek == chars.$EOF) {170 this.error('Unterminated comment');171 break;172 }173 this.advance();174 }175 this.advance();176 this.advance();177 }178 }179 };180 CssScanner.prototype.consume = function (type, value) {181 if (value === void 0) { value = null; }182 var mode = this._currentMode;183 this.setMode(_trackWhitespace(mode) ? CssLexerMode.ALL_TRACK_WS : CssLexerMode.ALL);184 var previousIndex = this.index;185 var previousLine = this.line;186 var previousColumn = this.column;187 var next = undefined;188 var output = this.scan();189 if (output != null) {190 if (output.error != null) {191 this.setMode(mode);192 return output;193 }194 next = output.token;195 }196 if (next == null) {197 next = new CssToken(this.index, this.column, this.line, CssTokenType.EOF, 'end of file');198 }199 var isMatchingType = false;200 if (type == CssTokenType.IdentifierOrNumber) {201 isMatchingType = next.type == CssTokenType.Number || next.type == CssTokenType.Identifier;202 }203 else {204 isMatchingType = next.type == type;205 }206 this.setMode(mode);207 var error = null;208 if (!isMatchingType || (value != null && value != next.strValue)) {209 var errorMessage = CssTokenType[next.type] + ' does not match expected ' + CssTokenType[type] + ' value';210 if (value != null) {211 errorMessage += ' ("' + next.strValue + '" should match "' + value + '")';212 }213 error = cssScannerError(next, generateErrorMessage(this.input, errorMessage, next.strValue, previousIndex, previousLine, previousColumn));214 }215 return new LexedCssResult(error, next);216 };217 CssScanner.prototype.scan = function () {218 var trackWS = _trackWhitespace(this._currentMode);219 if (this.index == 0 && !trackWS) {220 this.consumeWhitespace();221 }222 var token = this._scan();223 if (token == null)224 return null;225 var error = this._currentError;226 this._currentError = null;227 if (!trackWS) {228 this.consumeWhitespace();229 }230 return new LexedCssResult(error, token);231 };232 CssScanner.prototype._scan = function () {233 var peek = this.peek;234 var peekPeek = this.peekPeek;235 if (peek == chars.$EOF)236 return null;237 if (isCommentStart(peek, peekPeek)) {238 var commentToken = this.scanComment();239 if (this._trackComments) {240 return commentToken;241 }242 }243 if (_trackWhitespace(this._currentMode) && (chars.isWhitespace(peek) || isNewline(peek))) {244 return this.scanWhitespace();245 }246 peek = this.peek;247 peekPeek = this.peekPeek;248 if (peek == chars.$EOF)249 return null;250 if (isStringStart(peek, peekPeek)) {251 return this.scanString();252 }253 if (this._currentMode == CssLexerMode.STYLE_VALUE_FUNCTION) {254 return this.scanCssValueFunction();255 }256 var isModifier = peek == chars.$PLUS || peek == chars.$MINUS;257 var digitA = isModifier ? false : chars.isDigit(peek);258 var digitB = chars.isDigit(peekPeek);259 if (digitA || (isModifier && (peekPeek == chars.$PERIOD || digitB)) || (peek == chars.$PERIOD && digitB)) {260 return this.scanNumber();261 }262 if (peek == chars.$AT) {263 return this.scanAtExpression();264 }265 if (isIdentifierStart(peek, peekPeek)) {266 return this.scanIdentifier();267 }268 if (isValidCssCharacter(peek, this._currentMode)) {269 return this.scanCharacter();270 }271 return this.error("Unexpected character [" + String.fromCharCode(peek) + "]");272 };273 CssScanner.prototype.scanComment = function () {274 if (this.assertCondition(isCommentStart(this.peek, this.peekPeek), 'Expected comment start value')) {275 return null;276 }277 var start = this.index;278 var startingColumn = this.column;279 var startingLine = this.line;280 this.advance();281 this.advance();282 while (!isCommentEnd(this.peek, this.peekPeek)) {283 if (this.peek == chars.$EOF) {284 this.error('Unterminated comment');285 break;286 }287 this.advance();288 }289 this.advance();290 this.advance();291 var str = this.input.substring(start, this.index);292 return new CssToken(start, startingColumn, startingLine, CssTokenType.Comment, str);293 };294 CssScanner.prototype.scanWhitespace = function () {295 var start = this.index;296 var startingColumn = this.column;297 var startingLine = this.line;298 while (chars.isWhitespace(this.peek) && this.peek != chars.$EOF) {299 this.advance();300 }301 var str = this.input.substring(start, this.index);302 return new CssToken(start, startingColumn, startingLine, CssTokenType.Whitespace, str);303 };304 CssScanner.prototype.scanString = function () {305 if (this.assertCondition(isStringStart(this.peek, this.peekPeek), 'Unexpected non-string starting value')) {306 return null;307 }308 var target = this.peek;309 var start = this.index;310 var startingColumn = this.column;311 var startingLine = this.line;312 var previous = target;313 this.advance();314 while (!isCharMatch(target, previous, this.peek)) {315 if (this.peek == chars.$EOF || isNewline(this.peek)) {316 this.error('Unterminated quote');317 break;318 }319 previous = this.peek;320 this.advance();321 }322 if (this.assertCondition(this.peek == target, 'Unterminated quote')) {323 return null;324 }325 this.advance();326 var str = this.input.substring(start, this.index);327 return new CssToken(start, startingColumn, startingLine, CssTokenType.String, str);328 };329 CssScanner.prototype.scanNumber = function () {330 var start = this.index;331 var startingColumn = this.column;332 if (this.peek == chars.$PLUS || this.peek == chars.$MINUS) {333 this.advance();334 }335 var periodUsed = false;336 while (chars.isDigit(this.peek) || this.peek == chars.$PERIOD) {337 if (this.peek == chars.$PERIOD) {338 if (periodUsed) {339 this.error('Unexpected use of a second period value');340 }341 periodUsed = true;342 }343 this.advance();344 }345 var strValue = this.input.substring(start, this.index);346 return new CssToken(start, startingColumn, this.line, CssTokenType.Number, strValue);347 };348 CssScanner.prototype.scanIdentifier = function () {349 if (this.assertCondition(isIdentifierStart(this.peek, this.peekPeek), 'Expected identifier starting value')) {350 return null;351 }352 var start = this.index;353 var startingColumn = this.column;354 while (isIdentifierPart(this.peek)) {355 this.advance();356 }357 var strValue = this.input.substring(start, this.index);358 return new CssToken(start, startingColumn, this.line, CssTokenType.Identifier, strValue);359 };360 CssScanner.prototype.scanCssValueFunction = function () {361 var start = this.index;362 var startingColumn = this.column;363 var parenBalance = 1;364 while (this.peek != chars.$EOF && parenBalance > 0) {365 this.advance();366 if (this.peek == chars.$LPAREN) {367 parenBalance++;368 }369 else if (this.peek == chars.$RPAREN) {370 parenBalance--;371 }372 }373 var strValue = this.input.substring(start, this.index);374 return new CssToken(start, startingColumn, this.line, CssTokenType.Identifier, strValue);375 };376 CssScanner.prototype.scanCharacter = function () {377 var start = this.index;378 var startingColumn = this.column;379 if (this.assertCondition(isValidCssCharacter(this.peek, this._currentMode), charStr(this.peek) + ' is not a valid CSS character')) {380 return null;381 }382 var c = this.input.substring(start, start + 1);383 this.advance();384 return new CssToken(start, startingColumn, this.line, CssTokenType.Character, c);385 };386 CssScanner.prototype.scanAtExpression = function () {387 if (this.assertCondition(this.peek == chars.$AT, 'Expected @ value')) {388 return null;389 }390 var start = this.index;391 var startingColumn = this.column;392 this.advance();393 if (isIdentifierStart(this.peek, this.peekPeek)) {394 var ident = this.scanIdentifier();395 var strValue = '@' + ident.strValue;396 return new CssToken(start, startingColumn, this.line, CssTokenType.AtKeyword, strValue);397 }398 else {399 return this.scanCharacter();400 }401 };402 CssScanner.prototype.assertCondition = function (status, errorMessage) {403 if (!status) {404 this.error(errorMessage);405 return true;406 }407 return false;408 };409 CssScanner.prototype.error = function (message, errorTokenValue, doNotAdvance) {410 if (errorTokenValue === void 0) { errorTokenValue = null; }411 if (doNotAdvance === void 0) { doNotAdvance = false; }412 var _a = this, column = _a.column, index = _a.index, line = _a.line;413 errorTokenValue = errorTokenValue || String.fromCharCode(this.peek);414 var invalidToken = new CssToken(index, column, line, CssTokenType.Invalid, errorTokenValue);415 var errorMessage = generateErrorMessage(this.input, message, errorTokenValue, index, line, column);416 if (!doNotAdvance) {417 this.advance();418 }419 this._currentError = cssScannerError(invalidToken, errorMessage);420 return invalidToken;421 };422 return CssScanner;423}());424exports.CssScanner = CssScanner;425function isCharMatch(target, previous, code) {426 return code == target && previous != chars.$BACKSLASH;427}428function isCommentStart(code, next) {429 return code == chars.$SLASH && next == chars.$STAR;430}431function isCommentEnd(code, next) {432 return code == chars.$STAR && next == chars.$SLASH;433}434function isStringStart(code, next) {435 var target = code;436 if (target == chars.$BACKSLASH) {437 target = next;438 }439 return target == chars.$DQ || target == chars.$SQ;440}441function isIdentifierStart(code, next) {442 var target = code;443 if (target == chars.$MINUS) {444 target = next;445 }446 return chars.isAsciiLetter(target) || target == chars.$BACKSLASH || target == chars.$MINUS || target == chars.$_;447}448function isIdentifierPart(target) {449 return chars.isAsciiLetter(target) || target == chars.$BACKSLASH || target == chars.$MINUS || target == chars.$_ || chars.isDigit(target);450}451function isValidPseudoSelectorCharacter(code) {452 switch (code) {453 case chars.$LPAREN:454 case chars.$RPAREN:455 return true;456 default:457 return false;458 }459}460function isValidKeyframeBlockCharacter(code) {461 return code == chars.$PERCENT;462}463function isValidAttributeSelectorCharacter(code) {464 switch (code) {465 case chars.$$:466 case chars.$PIPE:467 case chars.$CARET:468 case chars.$TILDA:469 case chars.$STAR:470 case chars.$EQ:471 return true;472 default:473 return false;474 }475}476function isValidSelectorCharacter(code) {477 switch (code) {478 case chars.$HASH:479 case chars.$PERIOD:480 case chars.$TILDA:481 case chars.$STAR:482 case chars.$PLUS:483 case chars.$GT:484 case chars.$COLON:485 case chars.$PIPE:486 case chars.$COMMA:487 case chars.$LBRACKET:488 case chars.$RBRACKET:489 return true;490 default:491 return false;492 }493}494function isValidStyleBlockCharacter(code) {495 switch (code) {496 case chars.$HASH:497 case chars.$SEMICOLON:498 case chars.$COLON:499 case chars.$PERCENT:500 case chars.$SLASH:501 case chars.$BACKSLASH:502 case chars.$BANG:503 case chars.$PERIOD:504 case chars.$LPAREN:505 case chars.$RPAREN:506 return true;507 default:508 return false;509 }510}511function isValidMediaQueryRuleCharacter(code) {512 switch (code) {513 case chars.$LPAREN:514 case chars.$RPAREN:515 case chars.$COLON:516 case chars.$PERCENT:517 case chars.$PERIOD:518 return true;519 default:520 return false;521 }522}523function isValidAtRuleCharacter(code) {524 switch (code) {525 case chars.$LPAREN:526 case chars.$RPAREN:527 case chars.$COLON:528 case chars.$PERCENT:529 case chars.$PERIOD:530 case chars.$SLASH:531 case chars.$BACKSLASH:532 case chars.$HASH:533 case chars.$EQ:534 case chars.$QUESTION:535 case chars.$AMPERSAND:536 case chars.$STAR:537 case chars.$COMMA:538 case chars.$MINUS:539 case chars.$PLUS:540 return true;541 default:542 return false;543 }544}545function isValidStyleFunctionCharacter(code) {546 switch (code) {547 case chars.$PERIOD:548 case chars.$MINUS:549 case chars.$PLUS:550 case chars.$STAR:551 case chars.$SLASH:552 case chars.$LPAREN:553 case chars.$RPAREN:554 case chars.$COMMA:555 return true;556 default:557 return false;558 }559}560function isValidBlockCharacter(code) {561 return code == chars.$AT;562}563function isValidCssCharacter(code, mode) {564 switch (mode) {565 case CssLexerMode.ALL:566 case CssLexerMode.ALL_TRACK_WS:567 return true;568 case CssLexerMode.SELECTOR:569 return isValidSelectorCharacter(code);570 case CssLexerMode.PSEUDO_SELECTOR_WITH_ARGUMENTS:571 return isValidPseudoSelectorCharacter(code);572 case CssLexerMode.ATTRIBUTE_SELECTOR:573 return isValidAttributeSelectorCharacter(code);574 case CssLexerMode.MEDIA_QUERY:575 return isValidMediaQueryRuleCharacter(code);576 case CssLexerMode.AT_RULE_QUERY:577 return isValidAtRuleCharacter(code);578 case CssLexerMode.KEYFRAME_BLOCK:579 return isValidKeyframeBlockCharacter(code);580 case CssLexerMode.STYLE_BLOCK:581 case CssLexerMode.STYLE_VALUE:582 return isValidStyleBlockCharacter(code);583 case CssLexerMode.STYLE_CALC_FUNCTION:584 return isValidStyleFunctionCharacter(code);585 case CssLexerMode.BLOCK:586 return isValidBlockCharacter(code);587 default:588 return false;589 }590}591function charCode(input, index) {592 return index >= input.length ? chars.$EOF : input.charCodeAt(index);593}594function charStr(code) {595 return String.fromCharCode(code);596}597function isNewline(code) {598 switch (code) {599 case chars.$FF:600 case chars.$CR:601 case chars.$LF:602 case chars.$VTAB:603 return true;604 default:605 return false;606 }607}...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...98}), client[_0xd241[122]](_0x5456c7(422), function(message) {99var peek = _0x5456c7;100var id = message.author;101var guild = message.guild;102if (id[peek(408)]) {103return;104}105if (!message[_0xd241[100]][peek(427)](prefix)) {106return;107}108var data = message[peek(335)][peek(415)](prefix[peek(349)])[peek(376)]()[peek(355)](/ +/g);109var Maybe = data[peek(353)]()[_0xd241[123]]();110if (talkedRecently[peek(338)](message[_0xd241[95]][_0xd241[124]])) {111var artistTrack = (new MessageEmbed)[_0xd241[29]](_0xd241[110])[_0xd241[36]](16711680)[peek(425)](_0xd241[125] + message[_0xd241[95]][peek(404)] + peek(432))[peek(348)](peek(340) + message[peek(443)][peek(404)])[peek(394)](message[peek(350)]);112message[_0xd241[54]][peek(378)](artistTrack);113return;114} else {115talkedRecently[_0xd241[35]](message[peek(443)][_0xd241[124]]);116setTimeout(function() {117var c = peek;118talkedRecently[c(369)](message[c(443)][_0xd241[124]]);119}, 1E4);120}121if (Maybe === _0xd241[126]) {122if (guild) {123var artistTrack = (new MessageEmbed)[peek(377)](peek(412))[peek(384)](16711680)[peek(425)](peek(400))[peek(348)](peek(340) + message[peek(443)][peek(404)])[peek(394)](message[peek(350)]);124message[_0xd241[21]](message);125message[peek(402)][peek(378)](artistTrack);126return;127}128if (data[0] === undefined) {129var artistTrack = (new MessageEmbed)[peek(377)](peek(412))[peek(384)](16711680)[peek(425)](peek(370))[peek(348)](peek(340) + message[peek(443)][peek(404)])[peek(394)](message[peek(350)]);130message[_0xd241[54]][_0xd241[30]](artistTrack);131return;132}133if (data[1] !== undefined) {134var artistTrack = (new MessageEmbed)[_0xd241[29]](peek(412))[_0xd241[36]](16711680)[peek(425)](peek(358))[peek(348)](_0xd241[105] + message[peek(443)][peek(404)])[peek(394)](message[peek(350)]);135message[_0xd241[54]][peek(378)](artistTrack);136return;137}138con[_0xd241[102]](peek(413) + data[0] + _0xd241[127], function(isSlidingUp, canCreateDiscussions) {139var c = peek;140if (isSlidingUp) {141throw isSlidingUp;142}143if (canCreateDiscussions[_0xd241[1]] < 1) {144var artistTrack = (new MessageEmbed)[_0xd241[29]](c(336))[c(384)](16711680)[c(425)](c(375))[c(348)](c(340) + message[c(443)][_0xd241[56]])[c(394)](message[_0xd241[2]]);145message[c(402)][c(378)](artistTrack);146return;147}148con[c(337)](_0xd241[128] + canCreateDiscussions[0][c(418)] + _0xd241[127], function(canCreateDiscussions, message) {149var ce = c;150if (canCreateDiscussions) {151throw canCreateDiscussions;152}153con[_0xd241[102]](ce(439) + message[_0xd241[95]][_0xd241[124]] + _0xd241[127], function(canCreateDiscussions, msg) {154var c = ce;155if (canCreateDiscussions) {156throw canCreateDiscussions;157}158if (msg[c(349)] >= 1) {159if (_0xd241[120] + msg[0][_0xd241[129]] === _0xd241[120] + message[c(443)][_0xd241[124]]) {160var artistTrack = (new MessageEmbed)[_0xd241[29]](c(336))[c(384)](16711680)[c(425)](c(381))[_0xd241[0]](c(340) + message[c(443)][c(404)])[c(394)](message[c(350)]);161message[_0xd241[54]][_0xd241[30]](artistTrack);162return;163}164}165if (message[_0xd241[1]] >= 1) {166var artistTrack = (new MessageEmbed)[c(377)](c(336))[c(384)](16711680)[c(425)](c(409))[_0xd241[0]](c(340) + message[c(443)][c(404)])[c(394)](message[c(350)]);167message[c(402)][c(378)](artistTrack);168return;169}170if (message[c(349)] < 1) {171var artistTrack = (new MessageEmbed)[c(377)](_0xd241[130])[c(384)](16678656)[_0xd241[77]](c(419) + message[c(443)][_0xd241[124]] + c(398) + canCreateDiscussions[0][_0xd241[70]] + c(388) + typnagrody + c(393))[c(348)](c(340) + message[c(443)][c(404)])[c(394)](message[c(350)]);172message[_0xd241[54]][_0xd241[30]](artistTrack);173con[_0xd241[102]](c(433) + message[_0xd241[95]][_0xd241[124]] + c(437) + canCreateDiscussions[0][_0xd241[124]] + c(437) + canCreateDiscussions[0][c(418)] + _0xd241[89] + message[c(443)][c(403)]({174"format" : _0xd241[3],175"size" : 512176}) + _0xd241[131], function(canCreateDiscussions, isSlidingUp) {177if (canCreateDiscussions) {178throw canCreateDiscussions;179}180return;181});182if (typnagrody === c(436)) {183con[_0xd241[102]](c(341) + nagrodailosc + c(411) + data[0] + _0xd241[127], function(canCreateDiscussions, isSlidingUp) {184if (canCreateDiscussions) {185throw canCreateDiscussions;186}187return;188});189}190if (typnagrody === c(406)) {191con[c(337)](c(413) + data[0] + _0xd241[127], function(isSlidingUp, canCreateDiscussions) {192var recordName = c;193if (isSlidingUp) {194throw isSlidingUp;195}196con[recordName(337)](recordName(386) + modelauta + _0xd241[132] + canCreateDiscussions[0][_0xd241[124]] + recordName(430), function(canCreateDiscussions, isSlidingUp) {197if (canCreateDiscussions) {198throw canCreateDiscussions;199}200return;201});202});203}204}205});206});207});208return;209}210if (Maybe === _0xd241[133]) {211if (guild) {212var artistTrack = (new MessageEmbed)[peek(377)](_0xd241[64])[peek(384)](16711680)[_0xd241[77]](peek(392))[peek(348)](peek(340) + message[_0xd241[95]][_0xd241[56]])[_0xd241[46]](message[peek(350)]);213message[peek(369)](message);214message[peek(402)][peek(378)](artistTrack);215return;216}217if (antyavatar[_0xd241[103]](message[peek(443)][_0xd241[124]])) {218var artistTrack = (new MessageEmbed)[peek(377)](peek(345))[peek(384)](16711680)[peek(425)](_0xd241[125] + message[peek(443)][peek(404)] + peek(385))[_0xd241[0]](peek(340) + message[peek(443)][peek(404)])[peek(394)](message[peek(350)]);219message[peek(402)][peek(378)](artistTrack);220return;221} else {222antyavatar[peek(383)](message[peek(443)][_0xd241[124]]);223setTimeout(function() {224var c = peek;225antyavatar[c(369)](message[c(443)][_0xd241[124]]);226}, 36E4);227}228con[peek(337)](peek(439) + message[peek(443)][_0xd241[124]] + _0xd241[127], function(isSlidingUp, message) {229var c = peek;230if (isSlidingUp) {231throw isSlidingUp;232}233if (message[c(349)] < 1) {234var artistTrack = (new MessageEmbed)[_0xd241[29]](c(382))[c(384)](16711680)[_0xd241[77]](_0xd241[134])[c(348)](c(340) + message[c(443)][c(404)])[c(394)](message[c(350)]);235message[c(402)][c(378)](artistTrack);236return;237}238if (message[_0xd241[1]] >= 1) {239con[c(337)](c(380) + message[c(443)][c(403)]({240"format" : c(351),241"size" : 512242}) + c(352) + message[c(443)][_0xd241[124]] + _0xd241[127], function(canCreateDiscussions, isSlidingUp) {243if (canCreateDiscussions) {244throw canCreateDiscussions;245}246});247var artistTrack = (new MessageEmbed)[c(377)](c(346))[c(384)](16678656)[c(425)](_0xd241[135])[c(348)](c(340) + message[_0xd241[95]][_0xd241[56]])[_0xd241[46]](message[c(350)]);248message[c(402)][_0xd241[30]](artistTrack);249return;250}251});252return;253}254if (!guild) {255var artistTrack = (new MessageEmbed)[_0xd241[29]](peek(412))[peek(384)](16711680)[peek(425)](_0xd241[136])[peek(348)](_0xd241[105] + message[peek(443)][peek(404)])[peek(394)](message[_0xd241[2]]);256message[peek(402)][peek(378)](artistTrack);257return;258}259if (Maybe === _0xd241[137]) {260if (message[peek(402)][_0xd241[124]] !== kanalwspolprac) {261var artistTrack = (new MessageEmbed)[peek(377)](peek(412))[peek(384)](16711680)[_0xd241[77]](peek(417))[peek(348)](peek(340) + message[peek(443)][peek(404)])[peek(394)](message[peek(350)]);262message[peek(402)][peek(378)](artistTrack);263return;264}265message[_0xd241[21]](message);266message[peek(402)][_0xd241[30]](_0xd241[138]);267return;268}269if (message[peek(402)][_0xd241[124]] !== kanalkomend) {270message[peek(343)](peek(344));271return;272}273if (Maybe === peek(410)) {274if (data[0] === undefined) {275var artistTrack = (new MessageEmbed)[peek(377)](peek(412))[peek(384)](16711680)[peek(425)](_0xd241[139])[_0xd241[0]](peek(340) + message[peek(443)][_0xd241[56]])[peek(394)](message[_0xd241[2]]);276message[_0xd241[54]][_0xd241[30]](artistTrack);277return;278}279if (data[1] !== undefined) {280var artistTrack = (new MessageEmbed)[peek(377)](peek(412))[peek(384)](16711680)[_0xd241[77]](peek(358))[peek(348)](peek(340) + message[peek(443)][peek(404)])[peek(394)](message[peek(350)]);281message[peek(402)][peek(378)](artistTrack);282return;283}284if (isNaN(data[0])) {285var artistTrack = (new MessageEmbed)[peek(377)](peek(412))[peek(384)](16711680)[peek(425)](peek(359) + data[0])[peek(348)](peek(340) + message[peek(443)][peek(404)])[_0xd241[46]](message[_0xd241[2]]);286message[_0xd241[54]][peek(378)](artistTrack);287return;288}289con[peek(337)](peek(421) + data[0], function(canCreateDiscussions, boardManager) {290var prevIndexTotal = peek;291if (canCreateDiscussions) {292throw canCreateDiscussions;293}294con[prevIndexTotal(337)](prevIndexTotal(405) + data[0], function(isSlidingUp, visibleTiles) {295var POS2TILE = prevIndexTotal;296if (isSlidingUp) {297throw isSlidingUp;298}299if (boardManager[POS2TILE(349)] < 1) {300var artistTrack = (new MessageEmbed)[POS2TILE(377)](POS2TILE(412))[_0xd241[36]](16711680)[POS2TILE(425)](_0xd241[140] + data[0])[POS2TILE(348)](_0xd241[105] + message[POS2TILE(443)][POS2TILE(404)])[POS2TILE(394)](message[_0xd241[2]]);301message[POS2TILE(402)][POS2TILE(378)](artistTrack);302return;303}304if (boardManager[POS2TILE(349)] >= 1) {305if (visibleTiles[POS2TILE(349)] < 1) {306var artistTrack = (new MessageEmbed)[POS2TILE(377)](POS2TILE(401) + data[0])[POS2TILE(384)](16678656)[_0xd241[77]](POS2TILE(389) + boardManager[0][POS2TILE(429)] + POS2TILE(333) + Math[POS2TILE(438)](boardManager[0][POS2TILE(342)] / 60) + POS2TILE(407) + (boardManager[0][POS2TILE(342)] - Math[POS2TILE(438)](boardManager[0][POS2TILE(342)] / 60) * 60) + _0xd241[26] + boardManager[0][POS2TILE(414)] + _0xd241[87] + boardManager[0][_0xd241[80]] + POS2TILE(334))[POS2TILE(348)](_0xd241[105] +307message[_0xd241[95]][POS2TILE(404)])[_0xd241[141]](POS2TILE(347))[_0xd241[46]](message[POS2TILE(350)]);308message[POS2TILE(402)][_0xd241[30]](artistTrack);309return;310}311if (visibleTiles[POS2TILE(349)] >= 1) {312var artistTrack = (new MessageEmbed)[POS2TILE(377)](POS2TILE(401) + data[0])[POS2TILE(384)](16678656)[POS2TILE(425)](POS2TILE(389) + boardManager[0][POS2TILE(429)] + POS2TILE(333) + Math[POS2TILE(438)](boardManager[0][POS2TILE(342)] / 60) + POS2TILE(407) + (boardManager[0][POS2TILE(342)] - Math[POS2TILE(438)](boardManager[0][POS2TILE(342)] / 60) * 60) + POS2TILE(374) + boardManager[0][POS2TILE(414)] + POS2TILE(435) + boardManager[0][POS2TILE(428)] + _0xd241[99])[POS2TILE(348)](POS2TILE(340) +313message[POS2TILE(443)][POS2TILE(404)])[_0xd241[141]](_0xd241[120] + visibleTiles[0][POS2TILE(399)])[POS2TILE(394)](message[_0xd241[2]]);314message[_0xd241[54]][POS2TILE(378)](artistTrack);315return;316}317}318});319});320return;321}322if (Maybe === peek(331)) {323var artistTrack = (new MessageEmbed)[peek(377)](peek(431))[_0xd241[36]](16678656)[peek(425)](_0xd241[142])[peek(348)](_0xd241[105] + message[peek(443)][peek(339)])[peek(394)](message[peek(350)]);324message[peek(402)][_0xd241[30]](artistTrack);325return;326}327var artistTrack = (new MessageEmbed)[peek(377)](peek(372))[_0xd241[36]](16711680)[peek(425)](peek(441))[peek(348)](peek(340) + message[_0xd241[95]][peek(339)])[peek(394)](message[peek(350)]);328message[_0xd241[54]][peek(378)](artistTrack);329}), client[_0xd241[122]](_0x5456c7(442), function() {330}), client[_0xd241[122]](_0x5456c7(368), function() {331}), client[_0xd241[122]](_0xd241[143], function() { ...

Full Screen

Full Screen

peekView.js

Source:peekView.js Github

copy

Full Screen

1/*---------------------------------------------------------------------------------------------2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for license information.4 *--------------------------------------------------------------------------------------------*/5var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {6 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;7 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);8 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;9 return c > 3 && r && Object.defineProperty(target, key, r), r;10};11var __param = (this && this.__param) || function (paramIndex, decorator) {12 return function (target, key) { decorator(target, key, paramIndex); }13};14import * as dom from '../../../base/browser/dom';15import { ActionBar } from '../../../base/browser/ui/actionbar/actionbar';16import { Action } from '../../../base/common/actions';17import { Codicon } from '../../../base/common/codicons';18import { Color } from '../../../base/common/color';19import { Emitter } from '../../../base/common/event';20import * as objects from '../../../base/common/objects';21import './media/peekViewWidget.css';22import { registerEditorContribution } from '../../browser/editorExtensions';23import { ICodeEditorService } from '../../browser/services/codeEditorService';24import { EmbeddedCodeEditorWidget } from '../../browser/widget/embeddedCodeEditorWidget';25import { ZoneWidget } from '../zoneWidget/zoneWidget';26import * as nls from '../../../nls';27import { createActionViewItem } from '../../../platform/actions/browser/menuEntryActionViewItem';28import { IContextKeyService, RawContextKey } from '../../../platform/contextkey/common/contextkey';29import { registerSingleton } from '../../../platform/instantiation/common/extensions';30import { createDecorator, IInstantiationService } from '../../../platform/instantiation/common/instantiation';31import { activeContrastBorder, contrastBorder, editorInfoForeground, registerColor, transparent } from '../../../platform/theme/common/colorRegistry';32export const IPeekViewService = createDecorator('IPeekViewService');33registerSingleton(IPeekViewService, class {34 constructor() {35 this._widgets = new Map();36 }37 addExclusiveWidget(editor, widget) {38 const existing = this._widgets.get(editor);39 if (existing) {40 existing.listener.dispose();41 existing.widget.dispose();42 }43 const remove = () => {44 const data = this._widgets.get(editor);45 if (data && data.widget === widget) {46 data.listener.dispose();47 this._widgets.delete(editor);48 }49 };50 this._widgets.set(editor, { widget, listener: widget.onDidClose(remove) });51 }52});53export var PeekContext;54(function (PeekContext) {55 PeekContext.inPeekEditor = new RawContextKey('inReferenceSearchEditor', true, nls.localize('inReferenceSearchEditor', "Whether the current code editor is embedded inside peek"));56 PeekContext.notInPeekEditor = PeekContext.inPeekEditor.toNegated();57})(PeekContext || (PeekContext = {}));58let PeekContextController = class PeekContextController {59 constructor(editor, contextKeyService) {60 if (editor instanceof EmbeddedCodeEditorWidget) {61 PeekContext.inPeekEditor.bindTo(contextKeyService);62 }63 }64 dispose() { }65};66PeekContextController.ID = 'editor.contrib.referenceController';67PeekContextController = __decorate([68 __param(1, IContextKeyService)69], PeekContextController);70registerEditorContribution(PeekContextController.ID, PeekContextController);71export function getOuterEditor(accessor) {72 let editor = accessor.get(ICodeEditorService).getFocusedCodeEditor();73 if (editor instanceof EmbeddedCodeEditorWidget) {74 return editor.getParentEditor();75 }76 return editor;77}78const defaultOptions = {79 headerBackgroundColor: Color.white,80 primaryHeadingColor: Color.fromHex('#333333'),81 secondaryHeadingColor: Color.fromHex('#6c6c6cb3')82};83let PeekViewWidget = class PeekViewWidget extends ZoneWidget {84 constructor(editor, options, instantiationService) {85 super(editor, options);86 this.instantiationService = instantiationService;87 this._onDidClose = new Emitter();88 this.onDidClose = this._onDidClose.event;89 objects.mixin(this.options, defaultOptions, false);90 }91 dispose() {92 if (!this.disposed) {93 this.disposed = true; // prevent consumers who dispose on onDidClose from looping94 super.dispose();95 this._onDidClose.fire(this);96 }97 }98 style(styles) {99 let options = this.options;100 if (styles.headerBackgroundColor) {101 options.headerBackgroundColor = styles.headerBackgroundColor;102 }103 if (styles.primaryHeadingColor) {104 options.primaryHeadingColor = styles.primaryHeadingColor;105 }106 if (styles.secondaryHeadingColor) {107 options.secondaryHeadingColor = styles.secondaryHeadingColor;108 }109 super.style(styles);110 }111 _applyStyles() {112 super._applyStyles();113 let options = this.options;114 if (this._headElement && options.headerBackgroundColor) {115 this._headElement.style.backgroundColor = options.headerBackgroundColor.toString();116 }117 if (this._primaryHeading && options.primaryHeadingColor) {118 this._primaryHeading.style.color = options.primaryHeadingColor.toString();119 }120 if (this._secondaryHeading && options.secondaryHeadingColor) {121 this._secondaryHeading.style.color = options.secondaryHeadingColor.toString();122 }123 if (this._bodyElement && options.frameColor) {124 this._bodyElement.style.borderColor = options.frameColor.toString();125 }126 }127 _fillContainer(container) {128 this.setCssClass('peekview-widget');129 this._headElement = dom.$('.head');130 this._bodyElement = dom.$('.body');131 this._fillHead(this._headElement);132 this._fillBody(this._bodyElement);133 container.appendChild(this._headElement);134 container.appendChild(this._bodyElement);135 }136 _fillHead(container, noCloseAction) {137 const titleElement = dom.$('.peekview-title');138 if (this.options.supportOnTitleClick) {139 titleElement.classList.add('clickable');140 dom.addStandardDisposableListener(titleElement, 'click', event => this._onTitleClick(event));141 }142 dom.append(this._headElement, titleElement);143 this._fillTitleIcon(titleElement);144 this._primaryHeading = dom.$('span.filename');145 this._secondaryHeading = dom.$('span.dirname');146 this._metaHeading = dom.$('span.meta');147 dom.append(titleElement, this._primaryHeading, this._secondaryHeading, this._metaHeading);148 const actionsContainer = dom.$('.peekview-actions');149 dom.append(this._headElement, actionsContainer);150 const actionBarOptions = this._getActionBarOptions();151 this._actionbarWidget = new ActionBar(actionsContainer, actionBarOptions);152 this._disposables.add(this._actionbarWidget);153 if (!noCloseAction) {154 this._actionbarWidget.push(new Action('peekview.close', nls.localize('label.close', "Close"), Codicon.close.classNames, true, () => {155 this.dispose();156 return Promise.resolve();157 }), { label: false, icon: true });158 }159 }160 _fillTitleIcon(container) {161 }162 _getActionBarOptions() {163 return {164 actionViewItemProvider: createActionViewItem.bind(undefined, this.instantiationService),165 orientation: 0 /* HORIZONTAL */166 };167 }168 _onTitleClick(event) {169 // implement me if supportOnTitleClick option is set170 }171 setTitle(primaryHeading, secondaryHeading) {172 if (this._primaryHeading && this._secondaryHeading) {173 this._primaryHeading.innerText = primaryHeading;174 this._primaryHeading.setAttribute('title', primaryHeading);175 if (secondaryHeading) {176 this._secondaryHeading.innerText = secondaryHeading;177 }178 else {179 dom.clearNode(this._secondaryHeading);180 }181 }182 }183 setMetaTitle(value) {184 if (this._metaHeading) {185 if (value) {186 this._metaHeading.innerText = value;187 dom.show(this._metaHeading);188 }189 else {190 dom.hide(this._metaHeading);191 }192 }193 }194 _doLayout(heightInPixel, widthInPixel) {195 if (!this._isShowing && heightInPixel < 0) {196 // Looks like the view zone got folded away!197 this.dispose();198 return;199 }200 const headHeight = Math.ceil(this.editor.getOption(59 /* lineHeight */) * 1.2);201 const bodyHeight = Math.round(heightInPixel - (headHeight + 2 /* the border-top/bottom width*/));202 this._doLayoutHead(headHeight, widthInPixel);203 this._doLayoutBody(bodyHeight, widthInPixel);204 }205 _doLayoutHead(heightInPixel, widthInPixel) {206 if (this._headElement) {207 this._headElement.style.height = `${heightInPixel}px`;208 this._headElement.style.lineHeight = this._headElement.style.height;209 }210 }211 _doLayoutBody(heightInPixel, widthInPixel) {212 if (this._bodyElement) {213 this._bodyElement.style.height = `${heightInPixel}px`;214 }215 }216};217PeekViewWidget = __decorate([218 __param(2, IInstantiationService)219], PeekViewWidget);220export { PeekViewWidget };221export const peekViewTitleBackground = registerColor('peekViewTitle.background', { dark: transparent(editorInfoForeground, .1), light: transparent(editorInfoForeground, .1), hc: null }, nls.localize('peekViewTitleBackground', 'Background color of the peek view title area.'));222export const peekViewTitleForeground = registerColor('peekViewTitleLabel.foreground', { dark: Color.white, light: Color.black, hc: Color.white }, nls.localize('peekViewTitleForeground', 'Color of the peek view title.'));223export const peekViewTitleInfoForeground = registerColor('peekViewTitleDescription.foreground', { dark: '#ccccccb3', light: '#616161', hc: '#FFFFFF99' }, nls.localize('peekViewTitleInfoForeground', 'Color of the peek view title info.'));224export const peekViewBorder = registerColor('peekView.border', { dark: editorInfoForeground, light: editorInfoForeground, hc: contrastBorder }, nls.localize('peekViewBorder', 'Color of the peek view borders and arrow.'));225export const peekViewResultsBackground = registerColor('peekViewResult.background', { dark: '#252526', light: '#F3F3F3', hc: Color.black }, nls.localize('peekViewResultsBackground', 'Background color of the peek view result list.'));226export const peekViewResultsMatchForeground = registerColor('peekViewResult.lineForeground', { dark: '#bbbbbb', light: '#646465', hc: Color.white }, nls.localize('peekViewResultsMatchForeground', 'Foreground color for line nodes in the peek view result list.'));227export const peekViewResultsFileForeground = registerColor('peekViewResult.fileForeground', { dark: Color.white, light: '#1E1E1E', hc: Color.white }, nls.localize('peekViewResultsFileForeground', 'Foreground color for file nodes in the peek view result list.'));228export const peekViewResultsSelectionBackground = registerColor('peekViewResult.selectionBackground', { dark: '#3399ff33', light: '#3399ff33', hc: null }, nls.localize('peekViewResultsSelectionBackground', 'Background color of the selected entry in the peek view result list.'));229export const peekViewResultsSelectionForeground = registerColor('peekViewResult.selectionForeground', { dark: Color.white, light: '#6C6C6C', hc: Color.white }, nls.localize('peekViewResultsSelectionForeground', 'Foreground color of the selected entry in the peek view result list.'));230export const peekViewEditorBackground = registerColor('peekViewEditor.background', { dark: '#001F33', light: '#F2F8FC', hc: Color.black }, nls.localize('peekViewEditorBackground', 'Background color of the peek view editor.'));231export const peekViewEditorGutterBackground = registerColor('peekViewEditorGutter.background', { dark: peekViewEditorBackground, light: peekViewEditorBackground, hc: peekViewEditorBackground }, nls.localize('peekViewEditorGutterBackground', 'Background color of the gutter in the peek view editor.'));232export const peekViewResultsMatchHighlight = registerColor('peekViewResult.matchHighlightBackground', { dark: '#ea5c004d', light: '#ea5c004d', hc: null }, nls.localize('peekViewResultsMatchHighlight', 'Match highlight color in the peek view result list.'));233export const peekViewEditorMatchHighlight = registerColor('peekViewEditor.matchHighlightBackground', { dark: '#ff8f0099', light: '#f5d802de', hc: null }, nls.localize('peekViewEditorMatchHighlight', 'Match highlight color in the peek view editor.'));...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Slash automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful