How to use forceRegExp method in Playwright Internal

Best JavaScript code snippet using playwright-internal

tokenizer.js

Source:tokenizer.js Github

copy

Full Screen

1/*jshint -W054 */2// jshint ignore: start3// A second optional argument can be given to further configure4// the parser process. These options are recognized:5"use strict";6Object.defineProperty(exports, "__esModule", {7 value: true8});9var _exports = {};10var options, input, inputLen, sourceFile;11var defaultOptions = _exports.defaultOptions = {12 // `ecmaVersion` indicates the ECMAScript version to parse. Must13 // be either 3, or 5, or 6. This influences support for strict14 // mode, the set of reserved words, support for getters and15 // setters and other features. ES6 support is only partial.16 ecmaVersion: 5,17 // Turn on `strictSemicolons` to prevent the parser from doing18 // automatic semicolon insertion.19 strictSemicolons: false,20 // When `allowTrailingCommas` is false, the parser will not allow21 // trailing commas in array and object literals.22 allowTrailingCommas: true,23 // By default, reserved words are not enforced. Enable24 // `forbidReserved` to enforce them. When this option has the25 // value "everywhere", reserved words and keywords can also not be26 // used as property names.27 forbidReserved: false,28 // When enabled, a return at the top level is not considered an29 // error.30 allowReturnOutsideFunction: false,31 // When `locations` is on, `loc` properties holding objects with32 // `start` and `end` properties in `{line, column}` form (with33 // line being 1-based and column 0-based) will be attached to the34 // nodes.35 locations: false,36 // A function can be passed as `onComment` option, which will37 // cause Acorn to call that function with `(block, text, start,38 // end)` parameters whenever a comment is skipped. `block` is a39 // boolean indicating whether this is a block (`/* */`) comment,40 // `text` is the content of the comment, and `start` and `end` are41 // character offsets that denote the start and end of the comment.42 // When the `locations` option is on, two more parameters are43 // passed, the full `{line, column}` locations of the start and44 // end of the comments. Note that you are not allowed to call the45 // parser from the callback—that will corrupt its internal state.46 onComment: null,47 // Nodes have their start and end characters offsets recorded in48 // `start` and `end` properties (directly on the node, rather than49 // the `loc` object, which holds line/column data. To also add a50 // [semi-standardized][range] `range` property holding a `[start,51 // end]` array with the same numbers, set the `ranges` option to52 // `true`.53 //54 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=74567855 ranges: false,56 // It is possible to parse multiple files into a single AST by57 // passing the tree produced by parsing the first file as58 // `program` option in subsequent parses. This will add the59 // toplevel forms of the parsed file to the `Program` (top) node60 // of an existing parse tree.61 program: null,62 // When `locations` is on, you can pass this to record the source63 // file in every node's `loc` object.64 sourceFile: null,65 // This value, if given, is stored in every node, whether66 // `locations` is on or off.67 directSourceFile: null68};69function setOptions(opts) {70 options = opts || {};71 for (var opt in defaultOptions) if (!Object.prototype.hasOwnProperty.call(options, opt)) options[opt] = defaultOptions[opt];72 sourceFile = options.sourceFile || null;73 isKeyword = options.ecmaVersion >= 6 ? isEcma6Keyword : isEcma5AndLessKeyword;74}75// The `getLineInfo` function is mostly useful when the76// `locations` option is off (for performance reasons) and you77// want to find the line/column position for a given character78// offset. `input` should be the code string that the offset refers79// into.80var getLineInfo = _exports.getLineInfo = function (input, offset) {81 for (var line = 1, cur = 0;;) {82 lineBreak.lastIndex = cur;83 var match = lineBreak.exec(input);84 if (match && match.index < offset) {85 ++line;86 cur = match.index + match[0].length;87 } else break;88 }89 return { line: line, column: offset - cur };90};91// Acorn is organized as a tokenizer and a recursive-descent parser.92// The `tokenize` export provides an interface to the tokenizer.93// Because the tokenizer is optimized for being efficiently used by94// the Acorn parser itself, this interface is somewhat crude and not95// very modular. Performing another parse or call to `tokenize` will96// reset the internal state, and invalidate existing tokenizers.97_exports.tokenize = function (inpt, opts) {98 input = String(inpt);inputLen = input.length;99 setOptions(opts);100 initTokenState();101 var t = {};102 function getToken(forceRegexp) {103 lastEnd = tokEnd;104 readToken(forceRegexp);105 t.start = tokStart;t.end = tokEnd;106 t.startLoc = tokStartLoc;t.endLoc = tokEndLoc;107 t.type = tokType;t.value = tokVal;108 return t;109 }110 getToken.jumpTo = function (pos, reAllowed) {111 tokPos = pos;112 if (options.locations) {113 tokCurLine = 1;114 tokLineStart = lineBreak.lastIndex = 0;115 var match;116 while ((match = lineBreak.exec(input)) && match.index < pos) {117 ++tokCurLine;118 tokLineStart = match.index + match[0].length;119 }120 }121 tokRegexpAllowed = reAllowed;122 skipSpace();123 };124 return getToken;125};126// State is kept in (closure-)global variables. We already saw the127// `options`, `input`, and `inputLen` variables above.128// The current position of the tokenizer in the input.129var tokPos;130// The start and end offsets of the current token.131var tokStart, tokEnd;132// When `options.locations` is true, these hold objects133// containing the tokens start and end line/column pairs.134var tokStartLoc, tokEndLoc;135// The type and value of the current token. Token types are objects,136// named by variables against which they can be compared, and137// holding properties that describe them (indicating, for example,138// the precedence of an infix operator, and the original name of a139// keyword token). The kind of value that's held in `tokVal` depends140// on the type of the token. For literals, it is the literal value,141// for operators, the operator name, and so on.142var tokType, tokVal;143// Interal state for the tokenizer. To distinguish between division144// operators and regular expressions, it remembers whether the last145// token was one that is allowed to be followed by an expression.146// (If it is, a slash is probably a regexp, if it isn't it's a147// division operator. See the `parseStatement` function for a148// caveat.)149var tokRegexpAllowed;150// When `options.locations` is true, these are used to keep151// track of the current line, and know when a new line has been152// entered.153var tokCurLine, tokLineStart;154// These store the position of the previous token, which is useful155// when finishing a node and assigning its `end` position.156var lastStart, lastEnd, lastEndLoc;157// This is the parser's state. `inFunction` is used to reject158// `return` statements outside of functions, `labels` to verify that159// `break` and `continue` have somewhere to jump to, and `strict`160// indicates whether strict mode is on.161var inFunction, labels, strict;162// This function is used to raise exceptions on parse errors. It163// takes an offset integer (into the current `input`) to indicate164// the location of the error, attaches the position to the end165// of the error message, and then raises a `SyntaxError` with that166// message.167function raise(pos, message) {168 var loc = getLineInfo(input, pos);169 message += " (" + loc.line + ":" + loc.column + ")";170 var err = new SyntaxError(message);171 err.pos = pos;err.loc = loc;err.raisedAt = tokPos;172 throw err;173}174// Reused empty array added for node fields that are always empty.175var empty = [];176// ## Token types177// The assignment of fine-grained, information-carrying type objects178// allows the tokenizer to store the information it has about a179// token in a way that is very cheap for the parser to look up.180// All token type variables start with an underscore, to make them181// easy to recognize.182// These are the general types. The `type` property is only used to183// make them recognizeable when debugging.184var _num = { type: "num" },185 _regexp = { type: "regexp" },186 _string = { type: "string" };187var _name = { type: "name" },188 _eof = { type: "eof" };189// Keyword tokens. The `keyword` property (also used in keyword-like190// operators) indicates that the token originated from an191// identifier-like word, which is used when parsing property names.192//193// The `beforeExpr` property is used to disambiguate between regular194// expressions and divisions. It is set on all token types that can195// be followed by an expression (thus, a slash after them would be a196// regular expression).197//198// `isLoop` marks a keyword as starting a loop, which is important199// to know when parsing a label, in order to allow or disallow200// continue jumps to that label.201var _break = { keyword: "break" },202 _case = { keyword: "case", beforeExpr: true },203 _catch = { keyword: "catch" };204var _continue = { keyword: "continue" },205 _debugger = { keyword: "debugger" },206 _default = { keyword: "default" };207var _do = { keyword: "do", isLoop: true },208 _else = { keyword: "else", beforeExpr: true };209var _finally = { keyword: "finally" },210 _for = { keyword: "for", isLoop: true },211 _function = { keyword: "function" };212var _if = { keyword: "if" },213 _return = { keyword: "return", beforeExpr: true },214 _switch = { keyword: "switch" };215var _throw = { keyword: "throw", beforeExpr: true },216 _try = { keyword: "try" },217 _var = { keyword: "var" };218var _let = { keyword: "let" },219 _const = { keyword: "const" };220var _while = { keyword: "while", isLoop: true },221 _with = { keyword: "with" },222 _new = { keyword: "new", beforeExpr: true };223var _this = { keyword: "this" };224// The keywords that denote values.225var _null = { keyword: "null", atomValue: null },226 _true = { keyword: "true", atomValue: true };227var _false = { keyword: "false", atomValue: false };228// Some keywords are treated as regular operators. `in` sometimes229// (when parsing `for`) needs to be tested against specifically, so230// we assign a variable name to it for quick comparing.231var _in = { keyword: "in", binop: 7, beforeExpr: true };232// Map keyword names to token types.233var keywordTypes = { "break": _break, "case": _case, "catch": _catch,234 "continue": _continue, "debugger": _debugger, "default": _default,235 "do": _do, "else": _else, "finally": _finally, "for": _for,236 "function": _function, "if": _if, "return": _return, "switch": _switch,237 "throw": _throw, "try": _try, "var": _var, "let": _let, "const": _const,238 "while": _while, "with": _with,239 "null": _null, "true": _true, "false": _false, "new": _new, "in": _in,240 "instanceof": { keyword: "instanceof", binop: 7, beforeExpr: true }, "this": _this,241 "typeof": { keyword: "typeof", prefix: true, beforeExpr: true },242 "void": { keyword: "void", prefix: true, beforeExpr: true },243 "delete": { keyword: "delete", prefix: true, beforeExpr: true } };244// Punctuation token types. Again, the `type` property is purely for debugging.245var _bracketL = { type: "[", beforeExpr: true },246 _bracketR = { type: "]" },247 _braceL = { type: "{", beforeExpr: true };248var _braceR = { type: "}" },249 _parenL = { type: "(", beforeExpr: true },250 _parenR = { type: ")" };251var _comma = { type: ",", beforeExpr: true },252 _semi = { type: ";", beforeExpr: true };253var _colon = { type: ":", beforeExpr: true },254 _dot = { type: "." },255 _ellipsis = { type: "..." },256 _question = { type: "?", beforeExpr: true };257// Operators. These carry several kinds of properties to help the258// parser use them properly (the presence of these properties is259// what categorizes them as operators).260//261// `binop`, when present, specifies that this operator is a binary262// operator, and will refer to its precedence.263//264// `prefix` and `postfix` mark the operator as a prefix or postfix265// unary operator. `isUpdate` specifies that the node produced by266// the operator should be of type UpdateExpression rather than267// simply UnaryExpression (`++` and `--`).268//269// `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as270// binary operators with a very low precedence, that should result271// in AssignmentExpression nodes.272var _slash = { binop: 10, beforeExpr: true },273 _eq = { isAssign: true, beforeExpr: true };274var _assign = { isAssign: true, beforeExpr: true };275var _incDec = { postfix: true, prefix: true, isUpdate: true },276 _prefix = { prefix: true, beforeExpr: true };277var _logicalOR = { binop: 1, beforeExpr: true };278var _logicalAND = { binop: 2, beforeExpr: true };279var _bitwiseOR = { binop: 3, beforeExpr: true };280var _bitwiseXOR = { binop: 4, beforeExpr: true };281var _bitwiseAND = { binop: 5, beforeExpr: true };282var _equality = { binop: 6, beforeExpr: true };283var _relational = { binop: 7, beforeExpr: true };284var _bitShift = { binop: 8, beforeExpr: true };285var _plusMin = { binop: 9, prefix: true, beforeExpr: true };286var _multiplyModulo = { binop: 10, beforeExpr: true };287// Provide access to the token types for external users of the288// tokenizer.289_exports.tokTypes = { bracketL: _bracketL, bracketR: _bracketR, braceL: _braceL, braceR: _braceR,290 parenL: _parenL, parenR: _parenR, comma: _comma, semi: _semi, colon: _colon,291 dot: _dot, ellipsis: _ellipsis, question: _question, slash: _slash, eq: _eq,292 name: _name, eof: _eof, num: _num, regexp: _regexp, string: _string };293for (var kw in keywordTypes) _exports.tokTypes["_" + kw] = keywordTypes[kw];294// This is a trick taken from Esprima. It turns out that, on295// non-Chrome browsers, to check whether a string is in a set, a296// predicate containing a big ugly `switch` statement is faster than297// a regular expression, and on Chrome the two are about on par.298// This function uses `eval` (non-lexical) to produce such a299// predicate from a space-separated string of words.300//301// It starts by sorting the words by length.302function makePredicate(words) {303 words = words.split(" ");304 var f = "",305 cats = [];306 out: for (var i = 0; i < words.length; ++i) {307 for (var j = 0; j < cats.length; ++j) if (cats[j][0].length == words[i].length) {308 cats[j].push(words[i]);309 continue out;310 }311 cats.push([words[i]]);312 }313 function compareTo(arr) {314 if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";315 f += "switch(str){";316 for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":";317 f += "return true}return false;";318 }319 // When there are more than three length categories, an outer320 // switch first dispatches on the lengths, to save on comparisons.321 if (cats.length > 3) {322 cats.sort(function (a, b) {323 return b.length - a.length;324 });325 f += "switch(str.length){";326 for (var i = 0; i < cats.length; ++i) {327 var cat = cats[i];328 f += "case " + cat[0].length + ":";329 compareTo(cat);330 }331 f += "}";332 // Otherwise, simply generate a flat `switch` statement.333 } else {334 compareTo(words);335 }336 return new Function("str", f);337}338// The ECMAScript 3 reserved word list.339var isReservedWord3 = makePredicate("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile");340// ECMAScript 5 reserved words.341var isReservedWord5 = makePredicate("class enum extends super const export import");342// The additional reserved words in strict mode.343var isStrictReservedWord = makePredicate("implements interface let package private protected public static yield");344// The forbidden variable names in strict mode.345var isStrictBadIdWord = makePredicate("eval arguments");346// And the keywords.347var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";348var isEcma5AndLessKeyword = makePredicate(ecma5AndLessKeywords);349var isEcma6Keyword = makePredicate(ecma5AndLessKeywords + " let const");350var isKeyword = isEcma5AndLessKeyword;351// ## Character categories352// Big ugly regular expressions that match characters in the353// whitespace, identifier, and identifier-start categories. These354// are only applied when a character is found to actually have a355// code point above 128.356var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;357var nonASCIIidentifierStartChars = "ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";358var nonASCIIidentifierChars = "̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ؚؠ-ىٲ-ۓۧ-ۨۻ-ۼܰ-݊ࠀ-ࠔࠛ-ࠣࠥ-ࠧࠩ-࠭ࡀ-ࡗࣤ-ࣾऀ-ःऺ-़ा-ॏ॑-ॗॢ-ॣ०-९ঁ-ঃ়া-ৄেৈৗয়-ৠਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢ-ૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୟ-ୠ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఁ-ఃె-ైొ-్ౕౖౢ-ౣ౦-౯ಂಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢ-ೣ೦-೯ംഃെ-ൈൗൢ-ൣ൦-൯ංඃ්ා-ුූෘ-ෟෲෳิ-ฺเ-ๅ๐-๙ິ-ູ່-ໍ໐-໙༘༙༠-༩༹༵༷ཁ-ཇཱ-྄྆-྇ྍ-ྗྙ-ྼ࿆က-ဩ၀-၉ၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜎ-ᜐᜠ-ᜰᝀ-ᝐᝲᝳក-ឲ៝០-៩᠋-᠍᠐-᠙ᤠ-ᤫᤰ-᤻ᥑ-ᥭᦰ-ᧀᧈ-ᧉ᧐-᧙ᨀ-ᨕᨠ-ᩓ᩠-᩿᩼-᪉᪐-᪙ᭆ-ᭋ᭐-᭙᭫-᭳᮰-᮹᯦-᯳ᰀ-ᰢ᱀-᱉ᱛ-ᱽ᳐-᳒ᴀ-ᶾḁ-ἕ‌‍‿⁀⁔⃐-⃥⃜⃡-⃰ⶁ-ⶖⷠ-ⷿ〡-〨゙゚Ꙁ-ꙭꙴ-꙽ꚟ꛰-꛱ꟸ-ꠀ꠆ꠋꠣ-ꠧꢀ-ꢁꢴ-꣄꣐-꣙ꣳ-ꣷ꤀-꤉ꤦ-꤭ꤰ-ꥅꦀ-ꦃ꦳-꧀ꨀ-ꨧꩀ-ꩁꩌ-ꩍ꩐-꩙ꩻꫠ-ꫩꫲ-ꫳꯀ-ꯡ꯬꯭꯰-꯹ﬠ-ﬨ︀-️︠-︦︳︴﹍-﹏0-9_";359var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");360var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");361// Whether a single character denotes a newline.362var newline = /[\n\r\u2028\u2029]/;363// Matches a whole line break (where CRLF is considered a single364// line break). Used to count lines.365var lineBreak = /\r\n|[\n\r\u2028\u2029]/g;366// Test whether a given character code starts an identifier.367var isIdentifierStart = _exports.isIdentifierStart = function (code) {368 if (code < 65) return code === 36;369 if (code < 91) return true;370 if (code < 97) return code === 95;371 if (code < 123) return true;372 return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));373};374// Test whether a given character is part of an identifier.375var isIdentifierChar = _exports.isIdentifierChar = function (code) {376 if (code < 48) return code === 36;377 if (code < 58) return true;378 if (code < 65) return false;379 if (code < 91) return true;380 if (code < 97) return code === 95;381 if (code < 123) return true;382 return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));383};384// ## Tokenizer385// These are used when `options.locations` is on, for the386// `tokStartLoc` and `tokEndLoc` properties.387function Position() {388 this.line = tokCurLine;389 this.column = tokPos - tokLineStart;390}391// Reset the token state. Used at the start of a parse.392function initTokenState() {393 tokCurLine = 1;394 tokPos = tokLineStart = 0;395 tokRegexpAllowed = true;396 skipSpace();397}398// Called at the end of every token. Sets `tokEnd`, `tokVal`, and399// `tokRegexpAllowed`, and skips the space after the token, so that400// the next one's `tokStart` will point at the right position.401function finishToken(type, val) {402 tokEnd = tokPos;403 if (options.locations) tokEndLoc = new Position();404 tokType = type;405 skipSpace();406 tokVal = val;407 tokRegexpAllowed = type.beforeExpr;408}409function skipBlockComment() {410 var startLoc = options.onComment && options.locations && new Position();411 var start = tokPos,412 end = input.indexOf("*/", tokPos += 2);413 if (end === -1) raise(tokPos - 2, "Unterminated comment");414 tokPos = end + 2;415 if (options.locations) {416 lineBreak.lastIndex = start;417 var match;418 while ((match = lineBreak.exec(input)) && match.index < tokPos) {419 ++tokCurLine;420 tokLineStart = match.index + match[0].length;421 }422 }423 if (options.onComment) options.onComment(true, input.slice(start + 2, end), start, tokPos, startLoc, options.locations && new Position());424}425function skipLineComment() {426 var start = tokPos;427 var startLoc = options.onComment && options.locations && new Position();428 var ch = input.charCodeAt(tokPos += 2);429 while (tokPos < inputLen && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {430 ++tokPos;431 ch = input.charCodeAt(tokPos);432 }433 if (options.onComment) options.onComment(false, input.slice(start + 2, tokPos), start, tokPos, startLoc, options.locations && new Position());434}435// Called at the start of the parse and after every token. Skips436// whitespace and comments, and.437function skipSpace() {438 while (tokPos < inputLen) {439 var ch = input.charCodeAt(tokPos);440 if (ch === 32) {441 // ' '442 ++tokPos;443 } else if (ch === 13) {444 ++tokPos;445 var next = input.charCodeAt(tokPos);446 if (next === 10) {447 ++tokPos;448 }449 if (options.locations) {450 ++tokCurLine;451 tokLineStart = tokPos;452 }453 } else if (ch === 10 || ch === 8232 || ch === 8233) {454 ++tokPos;455 if (options.locations) {456 ++tokCurLine;457 tokLineStart = tokPos;458 }459 } else if (ch > 8 && ch < 14) {460 ++tokPos;461 } else if (ch === 47) {462 // '/'463 var next = input.charCodeAt(tokPos + 1);464 if (next === 42) {465 // '*'466 skipBlockComment();467 } else if (next === 47) {468 // '/'469 skipLineComment();470 } else break;471 } else if (ch === 160) {472 // '\xa0'473 ++tokPos;474 } else if (ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {475 ++tokPos;476 } else {477 break;478 }479 }480}481// ### Token reading482// This is the function that is called to fetch the next token. It483// is somewhat obscure, because it works in character codes rather484// than characters, and because operator parsing has been inlined485// into it.486//487// All in the name of speed.488//489// The `forceRegexp` parameter is used in the one case where the490// `tokRegexpAllowed` trick does not work. See `parseStatement`.491function readToken_dot() {492 var next = input.charCodeAt(tokPos + 1);493 if (next >= 48 && next <= 57) return readNumber(true);494 var next2 = input.charCodeAt(tokPos + 2);495 if (options.ecmaVersion >= 6 && next === 46 && next2 === 46) {496 // 46 = dot '.'497 tokPos += 3;498 return finishToken(_ellipsis);499 } else {500 ++tokPos;501 return finishToken(_dot);502 }503}504function readToken_slash() {505 // '/'506 var next = input.charCodeAt(tokPos + 1);507 if (tokRegexpAllowed) {508 ++tokPos;return readRegexp();509 }510 if (next === 61) return finishOp(_assign, 2);511 return finishOp(_slash, 1);512}513function readToken_mult_modulo() {514 // '%*'515 var next = input.charCodeAt(tokPos + 1);516 if (next === 61) return finishOp(_assign, 2);517 return finishOp(_multiplyModulo, 1);518}519function readToken_pipe_amp(code) {520 // '|&'521 var next = input.charCodeAt(tokPos + 1);522 if (next === code) return finishOp(code === 124 ? _logicalOR : _logicalAND, 2);523 if (next === 61) return finishOp(_assign, 2);524 return finishOp(code === 124 ? _bitwiseOR : _bitwiseAND, 1);525}526function readToken_caret() {527 // '^'528 var next = input.charCodeAt(tokPos + 1);529 if (next === 61) return finishOp(_assign, 2);530 return finishOp(_bitwiseXOR, 1);531}532function readToken_plus_min(code) {533 // '+-'534 var next = input.charCodeAt(tokPos + 1);535 if (next === code) {536 if (next == 45 && input.charCodeAt(tokPos + 2) == 62 && newline.test(input.slice(lastEnd, tokPos))) {537 // A `-->` line comment538 tokPos += 3;539 skipLineComment();540 skipSpace();541 return readToken();542 }543 return finishOp(_incDec, 2);544 }545 if (next === 61) return finishOp(_assign, 2);546 return finishOp(_plusMin, 1);547}548function readToken_lt_gt(code) {549 // '<>'550 var next = input.charCodeAt(tokPos + 1);551 var size = 1;552 if (next === code) {553 size = code === 62 && input.charCodeAt(tokPos + 2) === 62 ? 3 : 2;554 if (input.charCodeAt(tokPos + size) === 61) return finishOp(_assign, size + 1);555 return finishOp(_bitShift, size);556 }557 if (next == 33 && code == 60 && input.charCodeAt(tokPos + 2) == 45 && input.charCodeAt(tokPos + 3) == 45) {558 // `<!--`, an XML-style comment that should be interpreted as a line comment559 tokPos += 4;560 skipLineComment();561 skipSpace();562 return readToken();563 }564 if (next === 61) size = input.charCodeAt(tokPos + 2) === 61 ? 3 : 2;565 return finishOp(_relational, size);566}567function readToken_eq_excl(code) {568 // '=!'569 var next = input.charCodeAt(tokPos + 1);570 if (next === 61) return finishOp(_equality, input.charCodeAt(tokPos + 2) === 61 ? 3 : 2);571 return finishOp(code === 61 ? _eq : _prefix, 1);572}573function getTokenFromCode(code) {574 switch (code) {575 // The interpretation of a dot depends on whether it is followed576 // by a digit or another two dots.577 case 46:578 // '.'579 return readToken_dot();580 // Punctuation tokens.581 case 40:582 ++tokPos;return finishToken(_parenL);583 case 41:584 ++tokPos;return finishToken(_parenR);585 case 59:586 ++tokPos;return finishToken(_semi);587 case 44:588 ++tokPos;return finishToken(_comma);589 case 91:590 ++tokPos;return finishToken(_bracketL);591 case 93:592 ++tokPos;return finishToken(_bracketR);593 case 123:594 ++tokPos;return finishToken(_braceL);595 case 125:596 ++tokPos;return finishToken(_braceR);597 case 58:598 ++tokPos;return finishToken(_colon);599 case 63:600 ++tokPos;return finishToken(_question);601 // '0x' is a hexadecimal number.602 case 48:603 // '0'604 var next = input.charCodeAt(tokPos + 1);605 if (next === 120 || next === 88) return readHexNumber();606 // Anything else beginning with a digit is an integer, octal607 // number, or float.608 /* falls through */609 case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:610 // 1-9611 return readNumber(false);612 // Quotes produce strings.613 case 34:case 39:614 // '"', "'"615 return readString(code);616 // Operators are parsed inline in tiny state machines. '=' (61) is617 // often referred to. `finishOp` simply skips the amount of618 // characters it is given as second argument, and returns a token619 // of the type given by its first argument.620 case 47:621 // '/'622 return readToken_slash();623 case 37:case 42:624 // '%*'625 return readToken_mult_modulo();626 case 124:case 38:627 // '|&'628 return readToken_pipe_amp(code);629 case 94:630 // '^'631 return readToken_caret();632 case 43:case 45:633 // '+-'634 return readToken_plus_min(code);635 case 60:case 62:636 // '<>'637 return readToken_lt_gt(code);638 case 61:case 33:639 // '=!'640 return readToken_eq_excl(code);641 case 126:642 // '~'643 return finishOp(_prefix, 1);644 }645 return false;646}647function readToken(forceRegexp) {648 if (!forceRegexp) tokStart = tokPos;else tokPos = tokStart + 1;649 if (options.locations) tokStartLoc = new Position();650 if (forceRegexp) return readRegexp();651 if (tokPos >= inputLen) return finishToken(_eof);652 var code = input.charCodeAt(tokPos);653 // Identifier or keyword. '\uXXXX' sequences are allowed in654 // identifiers, so '\' also dispatches to that.655 if (isIdentifierStart(code) || code === 92 /* '\' */) return readWord();656 var tok = getTokenFromCode(code);657 if (tok === false) {658 // If we are here, we either found a non-ASCII identifier659 // character, or something that's entirely disallowed.660 var ch = String.fromCharCode(code);661 if (ch === "\\" || nonASCIIidentifierStart.test(ch)) return readWord();662 raise(tokPos, "Unexpected character '" + ch + "'");663 }664 return tok;665}666function finishOp(type, size) {667 var str = input.slice(tokPos, tokPos + size);668 tokPos += size;669 finishToken(type, str);670}671// Parse a regular expression. Some context-awareness is necessary,672// since a '/' inside a '[]' set does not end the expression.673function readRegexp() {674 var content = "",675 escaped,676 inClass,677 start = tokPos;678 for (;;) {679 if (tokPos >= inputLen) raise(start, "Unterminated regular expression");680 var ch = input.charAt(tokPos);681 if (newline.test(ch)) raise(start, "Unterminated regular expression");682 if (!escaped) {683 if (ch === "[") inClass = true;else if (ch === "]" && inClass) inClass = false;else if (ch === "/" && !inClass) break;684 escaped = ch === "\\";685 } else escaped = false;686 ++tokPos;687 }688 var content = input.slice(start, tokPos);689 ++tokPos;690 // Need to use `readWord1` because '\uXXXX' sequences are allowed691 // here (don't ask).692 var mods = readWord1();693 if (mods && !/^[gmsiy]*$/.test(mods)) raise(start, "Invalid regular expression flag");694 try {695 var value = new RegExp(content, mods);696 } catch (e) {697 if (e instanceof SyntaxError) raise(start, "Error parsing regular expression: " + e.message);698 raise(e);699 }700 return finishToken(_regexp, value);701}702// Read an integer in the given radix. Return null if zero digits703// were read, the integer value otherwise. When `len` is given, this704// will return `null` unless the integer has exactly `len` digits.705function readInt(radix, len) {706 var start = tokPos,707 total = 0;708 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {709 var code = input.charCodeAt(tokPos),710 val;711 if (code >= 97) val = code - 97 + 10; // a712 else if (code >= 65) val = code - 65 + 10; // A713 else if (code >= 48 && code <= 57) val = code - 48; // 0-9714 else val = Infinity;715 if (val >= radix) break;716 ++tokPos;717 total = total * radix + val;718 }719 if (tokPos === start || len != null && tokPos - start !== len) return null;720 return total;721}722function readHexNumber() {723 tokPos += 2; // 0x724 var val = readInt(16);725 if (val == null) raise(tokStart + 2, "Expected hexadecimal number");726 if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number");727 return finishToken(_num, val);728}729// Read an integer, octal integer, or floating-point number.730function readNumber(startsWithDot) {731 var start = tokPos,732 isFloat = false,733 octal = input.charCodeAt(tokPos) === 48;734 if (!startsWithDot && readInt(10) === null) raise(start, "Invalid number");735 if (input.charCodeAt(tokPos) === 46) {736 ++tokPos;737 readInt(10);738 isFloat = true;739 }740 var next = input.charCodeAt(tokPos);741 if (next === 69 || next === 101) {742 // 'eE'743 next = input.charCodeAt(++tokPos);744 if (next === 43 || next === 45) ++tokPos; // '+-'745 if (readInt(10) === null) raise(start, "Invalid number");746 isFloat = true;747 }748 if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number");749 var str = input.slice(start, tokPos),750 val;751 if (isFloat) val = parseFloat(str);else if (!octal || str.length === 1) val = parseInt(str, 10);else if (/[89]/.test(str) || strict) raise(start, "Invalid number");else val = parseInt(str, 8);752 return finishToken(_num, val);753}754// Read a string value, interpreting backslash-escapes.755function readString(quote) {756 tokPos++;757 var out = "";758 for (;;) {759 if (tokPos >= inputLen) raise(tokStart, "Unterminated string constant");760 var ch = input.charCodeAt(tokPos);761 if (ch === quote) {762 ++tokPos;763 return finishToken(_string, out);764 }765 if (ch === 92) {766 // '\'767 ch = input.charCodeAt(++tokPos);768 var octal = /^[0-7]+/.exec(input.slice(tokPos, tokPos + 3));769 if (octal) octal = octal[0];770 while (octal && parseInt(octal, 8) > 255) octal = octal.slice(0, -1);771 if (octal === "0") octal = null;772 ++tokPos;773 if (octal) {774 if (strict) raise(tokPos - 2, "Octal literal in strict mode");775 out += String.fromCharCode(parseInt(octal, 8));776 tokPos += octal.length - 1;777 } else {778 switch (ch) {779 case 110:780 out += "\n";break; // 'n' -> '\n'781 case 114:782 out += "\r";break; // 'r' -> '\r'783 case 120:784 out += String.fromCharCode(readHexChar(2));break; // 'x'785 case 117:786 out += String.fromCharCode(readHexChar(4));break; // 'u'787 case 85:788 out += String.fromCharCode(readHexChar(8));break; // 'U'789 case 116:790 out += "\t";break; // 't' -> '\t'791 case 98:792 out += "\b";break; // 'b' -> '\b'793 case 118:794 out += "\u000b";break; // 'v' -> '\u000b'795 case 102:796 out += "\f";break; // 'f' -> '\f'797 case 48:798 out += "\0";break; // 0 -> '\0'799 case 13:800 if (input.charCodeAt(tokPos) === 10) ++tokPos; // '\r\n'801 /* falls through */802 case 10:803 // ' \n'804 if (options.locations) {805 tokLineStart = tokPos;++tokCurLine;806 }807 break;808 default:809 out += String.fromCharCode(ch);break;810 }811 }812 } else {813 if (ch === 13 || ch === 10 || ch === 8232 || ch === 8233) raise(tokStart, "Unterminated string constant");814 out += String.fromCharCode(ch); // '\'815 ++tokPos;816 }817 }818}819// Used to read character escape sequences ('\x', '\u', '\U').820function readHexChar(len) {821 var n = readInt(16, len);822 if (n === null) raise(tokStart, "Bad character escape sequence");823 return n;824}825// Used to signal to callers of `readWord1` whether the word826// contained any escape sequences. This is needed because words with827// escape sequences must not be interpreted as keywords.828var containsEsc;829// Read an identifier, and return it as a string. Sets `containsEsc`830// to whether the word contained a '\u' escape.831//832// Only builds up the word character-by-character when it actually833// containeds an escape, as a micro-optimization.834function readWord1() {835 containsEsc = false;836 var word,837 first = true,838 start = tokPos;839 for (;;) {840 var ch = input.charCodeAt(tokPos);841 if (isIdentifierChar(ch)) {842 if (containsEsc) word += input.charAt(tokPos);843 ++tokPos;844 } else if (ch === 92) {845 // "\"846 if (!containsEsc) word = input.slice(start, tokPos);847 containsEsc = true;848 if (input.charCodeAt(++tokPos) != 117) // "u"849 raise(tokPos, "Expecting Unicode escape sequence \\uXXXX");850 ++tokPos;851 var esc = readHexChar(4);852 var escStr = String.fromCharCode(esc);853 if (!escStr) raise(tokPos - 1, "Invalid Unicode escape");854 if (!(first ? isIdentifierStart(esc) : isIdentifierChar(esc))) raise(tokPos - 4, "Invalid Unicode escape");855 word += escStr;856 } else {857 break;858 }859 first = false;860 }861 return containsEsc ? word : input.slice(start, tokPos);862}863// Read an identifier or keyword token. Will check for reserved864// words when necessary.865function readWord() {866 var word = readWord1();867 var type = _name;868 if (!containsEsc && isKeyword(word)) type = keywordTypes[word];869 return finishToken(type, word);870}871exports["default"] = { tokenize: _exports.tokenize };...

Full Screen

Full Screen

acorn_loose.js

Source:acorn_loose.js Github

copy

Full Screen

1// Acorn: Loose parser2//3// This module provides an alternative parser (`parse_dammit`) that4// exposes that same interface as `parse`, but will try to parse5// anything as JavaScript, repairing syntax error the best it can.6// There are circumstances in which it will raise an error and give7// up, but they are very rare. The resulting AST will be a mostly8// valid JavaScript AST (as per the [Mozilla parser API][api], except9// that:10//11// - Return outside functions is allowed12//13// - Label consistency (no conflicts, break only to existing labels)14// is not enforced.15//16// - Bogus Identifier nodes with a name of `"✖"` are inserted whenever17// the parser got too confused to return anything meaningful.18//19// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API20//21// The expected use for this is to *first* try `acorn.parse`, and only22// if that fails switch to `parse_dammit`. The loose parser might23// parse badly indented code incorrectly, so **don't** use it as24// your default parser.25//26// Quite a lot of acorn.js is duplicated here. The alternative was to27// add a *lot* of extra cruft to that file, making it less readable28// and slower. Copying and editing the code allowed me to make29// invasive changes and simplifications without creating a complicated30// tangle.31(function(root, mod) {32 if (typeof exports == "object" && typeof module == "object") return mod(exports, require("./acorn")); // CommonJS33 if (typeof define == "function" && define.amd) return define(["exports", "./acorn"], mod); // AMD34 mod(root.acorn || (root.acorn = {}), root.acorn); // Plain browser env35})(this, function(exports, acorn) {36 "use strict";37 var tt = acorn.tokTypes;38 var options, input, fetchToken, context;39 acorn.defaultOptions.tabSize = 4;40 exports.parse_dammit = function(inpt, opts) {41 if (!opts) opts = {};42 input = String(inpt);43 if (/^#!.*/.test(input)) input = "//" + input.slice(2);44 fetchToken = acorn.tokenize(input, opts);45 options = fetchToken.options;46 sourceFile = options.sourceFile || null;47 context = [];48 nextLineStart = 0;49 ahead.length = 0;50 next();51 return parseTopLevel();52 };53 var lastEnd, token = {start: 0, end: 0}, ahead = [];54 var curLineStart, nextLineStart, curIndent, lastEndLoc, sourceFile;55 function next(forceRegexp) {56 lastEnd = token.end;57 if (options.locations)58 lastEndLoc = token.endLoc;59 if (forceRegexp)60 ahead.length = 0;61 token = ahead.shift() || readToken(forceRegexp);62 if (token.start >= nextLineStart) {63 while (token.start >= nextLineStart) {64 curLineStart = nextLineStart;65 nextLineStart = lineEnd(curLineStart) + 1;66 }67 curIndent = indentationAfter(curLineStart);68 }69 }70 function readToken(forceRegexp) {71 for (;;) {72 try {73 var tok = fetchToken(forceRegexp);74 if (tok.type === tt.dot && input.substr(tok.end, 1) === '.') {75 tok = fetchToken();76 tok.start--;77 tok.type = tt.ellipsis;78 }79 return tok;80 } catch(e) {81 if (!(e instanceof SyntaxError)) throw e;82 // Try to skip some text, based on the error message, and then continue83 var msg = e.message, pos = e.raisedAt, replace = true;84 if (/unterminated/i.test(msg)) {85 pos = lineEnd(e.pos + 1);86 if (/string/.test(msg)) {87 replace = {start: e.pos, end: pos, type: tt.string, value: input.slice(e.pos + 1, pos)};88 } else if (/regular expr/i.test(msg)) {89 var re = input.slice(e.pos, pos);90 try { re = new RegExp(re); } catch(e) {}91 replace = {start: e.pos, end: pos, type: tt.regexp, value: re};92 } else {93 replace = false;94 }95 } else if (/invalid (unicode|regexp|number)|expecting unicode|octal literal|is reserved|directly after number/i.test(msg)) {96 while (pos < input.length && !isSpace(input.charCodeAt(pos))) ++pos;97 } else if (/character escape|expected hexadecimal/i.test(msg)) {98 while (pos < input.length) {99 var ch = input.charCodeAt(pos++);100 if (ch === 34 || ch === 39 || isNewline(ch)) break;101 }102 } else if (/unexpected character/i.test(msg)) {103 pos++;104 replace = false;105 } else if (/regular expression/i.test(msg)) {106 replace = true;107 } else {108 throw e;109 }110 resetTo(pos);111 if (replace === true) replace = {start: pos, end: pos, type: tt.name, value: "✖"};112 if (replace) {113 if (options.locations) {114 replace.startLoc = acorn.getLineInfo(input, replace.start);115 replace.endLoc = acorn.getLineInfo(input, replace.end);116 }117 return replace;118 }119 }120 }121 }122 function resetTo(pos) {123 for (;;) {124 try {125 var ch = input.charAt(pos - 1);126 var reAllowed = !ch || /[\[\{\(,;:?\/*=+\-~!|&%^<>]/.test(ch) ||127 /[enwfd]/.test(ch) && /\b(keywords|case|else|return|throw|new|in|(instance|type)of|delete|void)$/.test(input.slice(pos - 10, pos));128 return fetchToken.jumpTo(pos, reAllowed);129 } catch(e) {130 if (!(e instanceof SyntaxError && /unterminated comment/i.test(e.message))) throw e;131 pos = lineEnd(e.pos + 1);132 if (pos >= input.length) return;133 }134 }135 }136 function lookAhead(n) {137 while (n > ahead.length)138 ahead.push(readToken());139 return ahead[n-1];140 }141 var newline = /[\n\r\u2028\u2029]/;142 function isNewline(ch) {143 return ch === 10 || ch === 13 || ch === 8232 || ch === 8329;144 }145 function isSpace(ch) {146 return (ch < 14 && ch > 8) || ch === 32 || ch === 160 || isNewline(ch);147 }148 function pushCx() {149 context.push(curIndent);150 }151 function popCx() {152 curIndent = context.pop();153 }154 function lineEnd(pos) {155 while (pos < input.length && !isNewline(input.charCodeAt(pos))) ++pos;156 return pos;157 }158 function indentationAfter(pos) {159 for (var count = 0;; ++pos) {160 var ch = input.charCodeAt(pos);161 if (ch === 32) ++count;162 else if (ch === 9) count += options.tabSize;163 else return count;164 }165 }166 function closes(closeTok, indent, line, blockHeuristic) {167 if (token.type === closeTok || token.type === tt.eof) return true;168 if (line != curLineStart && curIndent < indent && tokenStartsLine() &&169 (!blockHeuristic || nextLineStart >= input.length ||170 indentationAfter(nextLineStart) < indent)) return true;171 return false;172 }173 function tokenStartsLine() {174 for (var p = token.start - 1; p >= curLineStart; --p) {175 var ch = input.charCodeAt(p);176 if (ch !== 9 && ch !== 32) return false;177 }178 return true;179 }180 function Node(start) {181 this.type = null;182 this.start = start;183 this.end = null;184 }185 Node.prototype = acorn.Node.prototype;186 function SourceLocation(start) {187 this.start = start || token.startLoc || {line: 1, column: 0};188 this.end = null;189 if (sourceFile !== null) this.source = sourceFile;190 }191 function startNode() {192 var node = new Node(token.start);193 if (options.locations)194 node.loc = new SourceLocation();195 if (options.directSourceFile)196 node.sourceFile = options.directSourceFile;197 if (options.ranges)198 node.range = [token.start, 0];199 return node;200 }201 function storeCurrentPos() {202 return options.locations ? [token.start, token.startLoc] : token.start;203 }204 function startNodeAt(pos) {205 var node;206 if (options.locations) {207 node = new Node(pos[0]);208 node.loc = new SourceLocation(pos[1]);209 } else {210 node = new Node(pos);211 }212 if (options.directSourceFile)213 node.sourceFile = options.directSourceFile;214 if (options.ranges)215 node.range = [pos[0], 0];216 return node;217 }218 function finishNode(node, type) {219 node.type = type;220 node.end = lastEnd;221 if (options.locations)222 node.loc.end = lastEndLoc;223 if (options.ranges)224 node.range[1] = lastEnd;225 return node;226 }227 function dummyIdent() {228 var dummy = startNode();229 dummy.name = "✖";230 return finishNode(dummy, "Identifier");231 }232 function isDummy(node) { return node.name == "✖"; }233 function eat(type) {234 if (token.type === type) {235 next();236 return true;237 } else {238 return false;239 }240 }241 function canInsertSemicolon() {242 return (token.type === tt.eof || token.type === tt.braceR || newline.test(input.slice(lastEnd, token.start)));243 }244 function semicolon() {245 return eat(tt.semi);246 }247 function expect(type) {248 if (eat(type)) return true;249 if (lookAhead(1).type == type) {250 next(); next();251 return true;252 }253 if (lookAhead(2).type == type) {254 next(); next(); next();255 return true;256 }257 }258 function checkLVal(expr) {259 if (!expr) return expr;260 switch (expr.type) {261 case "Identifier":262 case "MemberExpression":263 case "ObjectPattern":264 case "ArrayPattern":265 case "SpreadElement":266 return expr;267 default:268 return dummyIdent();269 }270 }271 function parseTopLevel() {272 var node = startNodeAt(options.locations ? [0, acorn.getLineInfo(input, 0)] : 0);273 node.body = [];274 while (token.type !== tt.eof) node.body.push(parseStatement());275 lastEnd = token.end;276 lastEndLoc = token.endLoc;277 return finishNode(node, "Program");278 }279 function parseStatement() {280 if (token.type === tt.slash || token.type === tt.assign && token.value === "/=")281 next(true);282 var starttype = token.type, node = startNode();283 switch (starttype) {284 case tt._break: case tt._continue:285 next();286 var isBreak = starttype === tt._break;287 if (semicolon() || canInsertSemicolon()) {288 node.label = null;289 } else {290 node.label = token.type === tt.name ? parseIdent() : null;291 semicolon();292 }293 return finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");294 case tt._debugger:295 next();296 semicolon();297 return finishNode(node, "DebuggerStatement");298 case tt._do:299 next();300 node.body = parseStatement();301 node.test = eat(tt._while) ? parseParenExpression() : dummyIdent();302 semicolon();303 return finishNode(node, "DoWhileStatement");304 case tt._for:305 next();306 pushCx();307 expect(tt.parenL);308 if (token.type === tt.semi) return parseFor(node, null);309 if (token.type === tt._var || token.type === tt._let) {310 var init = parseVar(true);311 if (init.declarations.length === 1 && (token.type === tt._in || token.type === tt.name && token.value === "of")) {312 return parseForIn(node, init);313 }314 return parseFor(node, init);315 }316 var init = parseExpression(false, true);317 if (token.type === tt._in || token.type === tt.name && token.value === "of") {318 return parseForIn(node, checkLVal(init));319 }320 return parseFor(node, init);321 case tt._function:322 next();323 return parseFunction(node, true);324 case tt._if:325 next();326 node.test = parseParenExpression();327 node.consequent = parseStatement();328 node.alternate = eat(tt._else) ? parseStatement() : null;329 return finishNode(node, "IfStatement");330 case tt._return:331 next();332 if (eat(tt.semi) || canInsertSemicolon()) node.argument = null;333 else { node.argument = parseExpression(); semicolon(); }334 return finishNode(node, "ReturnStatement");335 case tt._switch:336 var blockIndent = curIndent, line = curLineStart;337 next();338 node.discriminant = parseParenExpression();339 node.cases = [];340 pushCx();341 expect(tt.braceL);342 for (var cur; !closes(tt.braceR, blockIndent, line, true);) {343 if (token.type === tt._case || token.type === tt._default) {344 var isCase = token.type === tt._case;345 if (cur) finishNode(cur, "SwitchCase");346 node.cases.push(cur = startNode());347 cur.consequent = [];348 next();349 if (isCase) cur.test = parseExpression();350 else cur.test = null;351 expect(tt.colon);352 } else {353 if (!cur) {354 node.cases.push(cur = startNode());355 cur.consequent = [];356 cur.test = null;357 }358 cur.consequent.push(parseStatement());359 }360 }361 if (cur) finishNode(cur, "SwitchCase");362 popCx();363 eat(tt.braceR);364 return finishNode(node, "SwitchStatement");365 case tt._throw:366 next();367 node.argument = parseExpression();368 semicolon();369 return finishNode(node, "ThrowStatement");370 case tt._try:371 next();372 node.block = parseBlock();373 node.handler = null;374 if (token.type === tt._catch) {375 var clause = startNode();376 next();377 expect(tt.parenL);378 clause.param = parseIdent();379 expect(tt.parenR);380 clause.guard = null;381 clause.body = parseBlock();382 node.handler = finishNode(clause, "CatchClause");383 }384 node.finalizer = eat(tt._finally) ? parseBlock() : null;385 if (!node.handler && !node.finalizer) return node.block;386 return finishNode(node, "TryStatement");387 case tt._var:388 case tt._let:389 case tt._const:390 return parseVar();391 case tt._while:392 next();393 node.test = parseParenExpression();394 node.body = parseStatement();395 return finishNode(node, "WhileStatement");396 case tt._with:397 next();398 node.object = parseParenExpression();399 node.body = parseStatement();400 return finishNode(node, "WithStatement");401 case tt.braceL:402 return parseBlock();403 case tt.semi:404 next();405 return finishNode(node, "EmptyStatement");406 case tt._class:407 return parseObj(true, true);408 case tt._import:409 return parseImport();410 case tt._export:411 return parseExport();412 default:413 var expr = parseExpression();414 if (isDummy(expr)) {415 next();416 if (token.type === tt.eof) return finishNode(node, "EmptyStatement");417 return parseStatement();418 } else if (starttype === tt.name && expr.type === "Identifier" && eat(tt.colon)) {419 node.body = parseStatement();420 node.label = expr;421 return finishNode(node, "LabeledStatement");422 } else {423 node.expression = expr;424 semicolon();425 return finishNode(node, "ExpressionStatement");426 }427 }428 }429 function parseBlock() {430 var node = startNode();431 pushCx();432 expect(tt.braceL);433 var blockIndent = curIndent, line = curLineStart;434 node.body = [];435 while (!closes(tt.braceR, blockIndent, line, true))436 node.body.push(parseStatement());437 popCx();438 eat(tt.braceR);439 return finishNode(node, "BlockStatement");440 }441 function parseFor(node, init) {442 node.init = init;443 node.test = node.update = null;444 if (eat(tt.semi) && token.type !== tt.semi) node.test = parseExpression();445 if (eat(tt.semi) && token.type !== tt.parenR) node.update = parseExpression();446 popCx();447 expect(tt.parenR);448 node.body = parseStatement();449 return finishNode(node, "ForStatement");450 }451 function parseForIn(node, init) {452 var type = token.type === tt._in ? "ForInStatement" : "ForOfStatement";453 next();454 node.left = init;455 node.right = parseExpression();456 popCx();457 expect(tt.parenR);458 node.body = parseStatement();459 return finishNode(node, type);460 }461 function parseVar(noIn) {462 var node = startNode();463 node.kind = token.type.keyword;464 next();465 node.declarations = [];466 do {467 var decl = startNode();468 decl.id = options.ecmaVersion >= 6 ? toAssignable(parseExprAtom()) : parseIdent();469 decl.init = eat(tt.eq) ? parseExpression(true, noIn) : null;470 node.declarations.push(finishNode(decl, "VariableDeclarator"));471 } while (eat(tt.comma));472 if (!node.declarations.length) {473 var decl = startNode();474 decl.id = dummyIdent();475 node.declarations.push(finishNode(decl, "VariableDeclarator"));476 }477 if (!noIn) semicolon();478 return finishNode(node, "VariableDeclaration");479 }480 function parseExpression(noComma, noIn) {481 var start = storeCurrentPos();482 var expr = parseMaybeAssign(noIn);483 if (!noComma && token.type === tt.comma) {484 var node = startNodeAt(start);485 node.expressions = [expr];486 while (eat(tt.comma)) node.expressions.push(parseMaybeAssign(noIn));487 return finishNode(node, "SequenceExpression");488 }489 return expr;490 }491 function parseParenExpression() {492 pushCx();493 expect(tt.parenL);494 var val = parseExpression();495 popCx();496 expect(tt.parenR);497 return val;498 }499 function parseMaybeAssign(noIn) {500 var start = storeCurrentPos();501 var left = parseMaybeConditional(noIn);502 if (token.type.isAssign) {503 var node = startNodeAt(start);504 node.operator = token.value;505 node.left = token.type === tt.eq ? toAssignable(left) : checkLVal(left);506 next();507 node.right = parseMaybeAssign(noIn);508 return finishNode(node, "AssignmentExpression");509 }510 return left;511 }512 function parseMaybeConditional(noIn) {513 var start = storeCurrentPos();514 var expr = parseExprOps(noIn);515 if (eat(tt.question)) {516 var node = startNodeAt(start);517 node.test = expr;518 node.consequent = parseExpression(true);519 node.alternate = expect(tt.colon) ? parseExpression(true, noIn) : dummyIdent();520 return finishNode(node, "ConditionalExpression");521 }522 return expr;523 }524 function parseExprOps(noIn) {525 var start = storeCurrentPos();526 var indent = curIndent, line = curLineStart;527 return parseExprOp(parseMaybeUnary(noIn), start, -1, noIn, indent, line);528 }529 function parseExprOp(left, start, minPrec, noIn, indent, line) {530 if (curLineStart != line && curIndent < indent && tokenStartsLine()) return left;531 var prec = token.type.binop;532 if (prec != null && (!noIn || token.type !== tt._in)) {533 if (prec > minPrec) {534 var node = startNodeAt(start);535 node.left = left;536 node.operator = token.value;537 next();538 if (curLineStart != line && curIndent < indent && tokenStartsLine()) {539 node.right = dummyIdent();540 } else {541 var rightStart = storeCurrentPos();542 node.right = parseExprOp(parseMaybeUnary(noIn), rightStart, prec, noIn, indent, line);543 }544 finishNode(node, /&&|\|\|/.test(node.operator) ? "LogicalExpression" : "BinaryExpression");545 return parseExprOp(node, start, minPrec, noIn, indent, line);546 }547 }548 return left;549 }550 function parseMaybeUnary(noIn) {551 if (token.type.prefix) {552 var node = startNode(), update = token.type.isUpdate, nodeType;553 if (token.type === tt.ellipsis) {554 nodeType = "SpreadElement";555 } else {556 nodeType = update ? "UpdateExpression" : "UnaryExpression";557 node.operator = token.value;558 node.prefix = true;559 }560 node.operator = token.value;561 node.prefix = true;562 next();563 node.argument = parseMaybeUnary(noIn);564 if (update) node.argument = checkLVal(node.argument);565 return finishNode(node, nodeType);566 }567 var start = storeCurrentPos();568 var expr = parseExprSubscripts();569 while (token.type.postfix && !canInsertSemicolon()) {570 var node = startNodeAt(start);571 node.operator = token.value;572 node.prefix = false;573 node.argument = checkLVal(expr);574 next();575 expr = finishNode(node, "UpdateExpression");576 }577 return expr;578 }579 function parseExprSubscripts() {580 var start = storeCurrentPos();581 return parseSubscripts(parseExprAtom(), start, false, curIndent, curLineStart);582 }583 function parseSubscripts(base, start, noCalls, startIndent, line) {584 for (;;) {585 if (curLineStart != line && curIndent <= startIndent && tokenStartsLine()) {586 if (token.type == tt.dot && curIndent == startIndent)587 --startIndent;588 else589 return base;590 }591 if (eat(tt.dot)) {592 var node = startNodeAt(start);593 node.object = base;594 if (curLineStart != line && curIndent <= startIndent && tokenStartsLine())595 node.property = dummyIdent();596 else597 node.property = parsePropertyAccessor() || dummyIdent();598 node.computed = false;599 base = finishNode(node, "MemberExpression");600 } else if (token.type == tt.bracketL) {601 pushCx();602 next();603 var node = startNodeAt(start);604 node.object = base;605 node.property = parseExpression();606 node.computed = true;607 popCx();608 expect(tt.bracketR);609 base = finishNode(node, "MemberExpression");610 } else if (!noCalls && token.type == tt.parenL) {611 pushCx();612 var node = startNodeAt(start);613 node.callee = base;614 node.arguments = parseExprList(tt.parenR);615 base = finishNode(node, "CallExpression");616 } else {617 return base;618 }619 }620 }621 function parseExprAtom() {622 switch (token.type) {623 case tt._this:624 var node = startNode();625 next();626 return finishNode(node, "ThisExpression");627 case tt.name:628 var start = storeCurrentPos();629 var id = parseIdent();630 return eat(tt.arrow) ? parseArrowExpression(startNodeAt(start), [id]) : id;631 case tt.regexp:632 var node = startNode();633 var val = token.value;634 node.regex = {pattern: val.pattern, flags: val.flags};635 node.value = val.value;636 node.raw = input.slice(token.start, token.end);637 next();638 return finishNode(node, "Literal");639 case tt.num: case tt.string:640 var node = startNode();641 node.value = token.value;642 node.raw = input.slice(token.start, token.end);643 next();644 return finishNode(node, "Literal");645 case tt._null: case tt._true: case tt._false:646 var node = startNode();647 node.value = token.type.atomValue;648 node.raw = token.type.keyword;649 next();650 return finishNode(node, "Literal");651 case tt.parenL:652 var start = storeCurrentPos();653 next();654 var val = parseExpression();655 expect(tt.parenR);656 if (eat(tt.arrow)) {657 return parseArrowExpression(startNodeAt(start), val.expressions || (isDummy(val) ? [] : [val]));658 }659 if (options.preserveParens) {660 var par = startNodeAt(start);661 par.expression = val;662 val = finishNode(par, "ParenthesizedExpression");663 }664 return val;665 case tt.bracketL:666 var node = startNode();667 pushCx();668 node.elements = parseExprList(tt.bracketR, true);669 return finishNode(node, "ArrayExpression");670 case tt.braceL:671 return parseObj();672 case tt._class:673 return parseObj(true);674 case tt._function:675 var node = startNode();676 next();677 return parseFunction(node, false);678 case tt._new:679 return parseNew();680 case tt._yield:681 var node = startNode();682 next();683 if (semicolon() || canInsertSemicolon()) {684 node.delegate = false;685 node.argument = null;686 } else {687 node.delegate = eat(tt.star);688 node.argument = parseExpression(true);689 }690 return finishNode(node, "YieldExpression");691 default:692 return dummyIdent();693 }694 }695 function parseNew() {696 var node = startNode(), startIndent = curIndent, line = curLineStart;697 next();698 var start = storeCurrentPos();699 node.callee = parseSubscripts(parseExprAtom(), start, true, startIndent, line);700 if (token.type == tt.parenL) {701 pushCx();702 node.arguments = parseExprList(tt.parenR);703 } else {704 node.arguments = [];705 }706 return finishNode(node, "NewExpression");707 }708 function parseObj(isClass, isStatement) {709 var node = startNode();710 if (isClass) {711 next();712 if (token.type === tt.name) node.id = parseIdent();713 else if (isStatement) node.id = dummyIdent();714 node.superClass = eat(tt._extends) ? parseExpression() : null;715 node.body = startNode();716 node.body.body = [];717 } else {718 node.properties = [];719 }720 pushCx();721 var indent = curIndent + 1, line = curLineStart;722 eat(tt.braceL);723 if (curIndent + 1 < indent) { indent = curIndent; line = curLineStart; }724 while (!closes(tt.braceR, indent, line)) {725 var prop = startNode(), isGenerator;726 if (options.ecmaVersion >= 6) {727 if (isClass) {728 if (prop['static'] = (token.type === tt.name && token.value === "static")) next();729 } else {730 prop.method = false;731 prop.shorthand = false;732 }733 isGenerator = eat(tt.star);734 }735 parsePropertyName(prop);736 if (isDummy(prop.key)) { if (isDummy(parseExpression(true))) next(); eat(tt.comma); continue; }737 if (!isClass && eat(tt.colon)) {738 prop.kind = "init";739 prop.value = parseExpression(true);740 } else if (options.ecmaVersion >= 6 && (token.type === tt.parenL || token.type === tt.braceL)) {741 if (isClass) {742 prop.kind = "";743 } else {744 prop.kind = "init";745 prop.method = true;746 }747 prop.value = parseMethod(isGenerator);748 } else if (options.ecmaVersion >= 5 && prop.key.type === "Identifier" &&749 (prop.key.name === "get" || prop.key.name === "set")) {750 prop.kind = prop.key.name;751 parsePropertyName(prop);752 prop.value = parseMethod(false);753 } else if (isClass) {754 prop.kind = "";755 prop.value = parseMethod(isGenerator);756 } else {757 prop.kind = "init";758 prop.value = options.ecmaVersion >= 6 ? prop.key : dummyIdent();759 prop.shorthand = true;760 }761 if (isClass) {762 node.body.body.push(finishNode(prop, "MethodDefinition"));763 semicolon();764 } else {765 node.properties.push(finishNode(prop, "Property"));766 eat(tt.comma);767 }768 }769 popCx();770 eat(tt.braceR);771 if (isClass) {772 semicolon();773 finishNode(node.body, "ClassBody");774 return finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");775 } else {776 return finishNode(node, "ObjectExpression");777 }778 }779 function parsePropertyName(prop) {780 if (options.ecmaVersion >= 6) {781 if (eat(tt.bracketL)) {782 prop.computed = true;783 prop.key = parseExpression();784 expect(tt.bracketR);785 return;786 } else {787 prop.computed = false;788 }789 }790 var key = (token.type === tt.num || token.type === tt.string) ? parseExprAtom() : parseIdent();791 prop.key = key || dummyIdent();792 }793 function parsePropertyAccessor() {794 if (token.type === tt.name || token.type.keyword) return parseIdent();795 }796 function parseIdent() {797 var node = startNode();798 node.name = token.type === tt.name ? token.value : token.type.keyword;799 fetchToken.noRegexp();800 next();801 return finishNode(node, "Identifier");802 }803 function initFunction(node) {804 node.id = null;805 node.params = [];806 if (options.ecmaVersion >= 6) {807 node.defaults = [];808 node.rest = null;809 node.generator = false;810 node.expression = false;811 }812 }813 // Convert existing expression atom to assignable pattern814 // if possible.815 function toAssignable(node) {816 if (options.ecmaVersion >= 6 && node) {817 switch (node.type) {818 case "ObjectExpression":819 node.type = "ObjectPattern";820 var props = node.properties;821 for (var i = 0; i < props.length; i++) {822 props[i].value = toAssignable(props[i].value);823 }824 break;825 case "ArrayExpression":826 node.type = "ArrayPattern";827 var elms = node.elements;828 for (var i = 0; i < elms.length; i++) {829 elms[i] = toAssignable(elms[i]);830 }831 break;832 case "SpreadElement":833 node.argument = toAssignable(node.argument);834 break;835 }836 }837 return checkLVal(node);838 }839 function parseFunctionParams(node, params) {840 var defaults = [], hasDefaults = false;841 if (!params) {842 pushCx();843 params = parseExprList(tt.parenR);844 }845 for (var i = 0; i < params.length; i++) {846 var param = params[i], defValue = null;847 if (param.type === "AssignmentExpression") {848 defValue = param.right;849 param = param.left;850 }851 param = toAssignable(param);852 if (param.type === "SpreadElement") {853 param = param.argument;854 if (i === params.length - 1) {855 node.rest = param;856 continue;857 }858 }859 node.params.push(param);860 defaults.push(defValue);861 if (defValue) hasDefaults = true;862 }863 if (hasDefaults) node.defaults = defaults;864 }865 function parseFunction(node, isStatement) {866 initFunction(node);867 if (options.ecmaVersion >= 6) {868 node.generator = eat(tt.star);869 }870 if (token.type === tt.name) node.id = parseIdent();871 else if (isStatement) node.id = dummyIdent();872 parseFunctionParams(node);873 node.body = parseBlock();874 return finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");875 }876 function parseMethod(isGenerator) {877 var node = startNode();878 initFunction(node);879 parseFunctionParams(node);880 node.generator = isGenerator || false;881 node.expression = options.ecmaVersion >= 6 && token.type !== tt.braceL;882 node.body = node.expression ? parseExpression(true) : parseBlock();883 return finishNode(node, "FunctionExpression");884 }885 function parseArrowExpression(node, params) {886 initFunction(node);887 parseFunctionParams(node, params);888 node.expression = token.type !== tt.braceL;889 node.body = node.expression ? parseExpression(true) : parseBlock();890 return finishNode(node, "ArrowFunctionExpression");891 }892 function parseExport() {893 var node = startNode();894 next();895 node['default'] = eat(tt._default);896 node.specifiers = node.source = null;897 if (node['default']) {898 node.declaration = parseExpression();899 semicolon();900 } else if (token.type.keyword) {901 node.declaration = parseStatement();902 } else {903 node.declaration = null;904 parseSpecifierList(node, "Export");905 }906 semicolon();907 return finishNode(node, "ExportDeclaration");908 }909 function parseImport() {910 var node = startNode();911 next();912 if (token.type === tt.string) {913 node.specifiers = [];914 node.source = parseExprAtom();915 node.kind = '';916 } else {917 if (token.type === tt.name && token.value !== "from") {918 var elt = startNode();919 elt.id = parseIdent();920 elt.name = null;921 elt['default'] = true;922 finishNode(elt, "ImportSpecifier");923 eat(tt.comma);924 }925 parseSpecifierList(node, "Import");926 var specs = node.specifiers;927 for (var i = 0; i < specs.length; i++) specs[i]['default'] = false;928 if (elt) node.specifiers.unshift(elt);929 }930 semicolon();931 return finishNode(node, "ImportDeclaration");932 }933 function parseSpecifierList(node, prefix) {934 var elts = node.specifiers = [];935 if (token.type === tt.star) {936 var elt = startNode();937 next();938 if (token.type === tt.name && token.value === "as") {939 next();940 elt.name = parseIdent();941 }942 elts.push(finishNode(elt, prefix + "BatchSpecifier"));943 } else {944 var indent = curIndent, line = curLineStart, continuedLine = nextLineStart;945 pushCx();946 eat(tt.braceL);947 if (curLineStart > continuedLine) continuedLine = curLineStart;948 while (!closes(tt.braceR, indent + (curLineStart <= continuedLine ? 1 : 0), line)) {949 var elt = startNode();950 if (token.type === tt.star) {951 next();952 if (token.type === tt.name && token.value === "as") {953 next();954 elt.name = parseIdent();955 }956 finishNode(elt, prefix + "BatchSpecifier");957 } else {958 if (token.type === tt.name && token.value === "from") break;959 elt.id = parseIdent();960 if (token.type === tt.name && token.value === "as") {961 next();962 elt.name = parseIdent();963 } else {964 elt.name = null;965 }966 finishNode(elt, prefix + "Specifier");967 }968 elts.push(elt);969 eat(tt.comma);970 }971 eat(tt.braceR);972 popCx();973 }974 if (token.type === tt.name && token.value === "from") {975 next();976 node.source = parseExprAtom();977 } else {978 node.source = null;979 }980 }981 function parseExprList(close, allowEmpty) {982 var indent = curIndent, line = curLineStart, elts = [], continuedLine = nextLineStart;983 next(); // Opening bracket984 if (curLineStart > continuedLine) continuedLine = curLineStart;985 while (!closes(close, indent + (curLineStart <= continuedLine ? 1 : 0), line)) {986 if (eat(tt.comma)) {987 elts.push(allowEmpty ? null : dummyIdent());988 continue;989 }990 var elt = parseExpression(true);991 if (isDummy(elt)) {992 if (closes(close, indent, line)) break;993 next();994 } else {995 elts.push(elt);996 }997 eat(tt.comma);998 }999 popCx();1000 eat(close);1001 return elts;1002 }...

Full Screen

Full Screen

cli.js

Source:cli.js Github

copy

Full Screen

...139 }140 const filePatternFilters = args.map(arg => {141 const match = /^(.*):(\d+)$/.exec(arg);142 return {143 re: forceRegExp(match ? match[1] : arg),144 line: match ? parseInt(match[2], 10) : null145 };146 });147 const result = await runner.run(!!opts.list, filePatternFilters, opts.project || undefined);148 await (0, _profiler.stopProfiling)(undefined);149 if (result === 'sigint') process.exit(130);150 process.exit(result === 'passed' ? 0 : 1);151}152function forceRegExp(pattern) {153 const match = pattern.match(/^\/(.*)\/([gi]*)$/);154 if (match) return new RegExp(match[1], match[2]);155 return new RegExp(pattern, 'gi');156}157function overridesFromOptions(options) {158 const isDebuggerAttached = !!require('inspector').url();159 const shardPair = options.shard ? options.shard.split('/').map(t => parseInt(t, 10)) : undefined;160 return {161 forbidOnly: options.forbidOnly ? true : undefined,162 globalTimeout: isDebuggerAttached ? 0 : options.globalTimeout ? parseInt(options.globalTimeout, 10) : undefined,163 grep: options.grep ? forceRegExp(options.grep) : undefined,164 grepInvert: options.grepInvert ? forceRegExp(options.grepInvert) : undefined,165 maxFailures: options.x ? 1 : options.maxFailures ? parseInt(options.maxFailures, 10) : undefined,166 outputDir: options.output ? path.resolve(process.cwd(), options.output) : undefined,167 quiet: options.quiet ? options.quiet : undefined,168 repeatEach: options.repeatEach ? parseInt(options.repeatEach, 10) : undefined,169 retries: options.retries ? parseInt(options.retries, 10) : undefined,170 reporter: options.reporter && options.reporter.length ? options.reporter.split(',').map(r => [resolveReporter(r)]) : undefined,171 shard: shardPair ? {172 current: shardPair[0],173 total: shardPair[1]174 } : undefined,175 timeout: isDebuggerAttached ? 0 : options.timeout ? parseInt(options.timeout, 10) : undefined,176 updateSnapshots: options.updateSnapshots ? 'all' : undefined,177 workers: options.workers ? parseInt(options.workers, 10) : undefined178 };...

Full Screen

Full Screen

util.js

Source:util.js Github

copy

Full Screen

...164}165async function wrapInPromise(value) {166 return value;167}168function forceRegExp(pattern) {169 const match = pattern.match(/^\/(.*)\/([gi]*)$/);170 if (match) return new RegExp(match[1], match[2]);171 return new RegExp(pattern, 'g');172}173function relativeFilePath(file) {174 if (!_path.default.isAbsolute(file)) return file;175 return _path.default.relative(process.cwd(), file);176}177function formatLocation(location) {178 return relativeFilePath(location.file) + ':' + location.line + ':' + location.column;179}180function errorWithFile(file, message) {181 return new Error(`${relativeFilePath(file)}: ${message}`);182}...

Full Screen

Full Screen

start_game.js

Source:start_game.js Github

copy

Full Screen

1const config = require("../config.json");2const permissions = require("../permissions.js");3const channelFunctions = require("../channel_functions.js");4const rw = require("../reader_writer.js");5const newsModule = require("../news_posting.js");6const regexp = new RegExp(`^${config.prefix}START`, "i");7const forceRegexp = new RegExp(`^FORCE`, "i");8module.exports.enabled = true;9module.exports.gameTypesSupported = [config.dom4GameTypeName, config.dom5GameTypeName];10module.exports.getChannelRequiredToInvoke = "game";11module.exports.getReadableCommand = function()12{13 return "start";14};15module.exports.getCommandArguments = [`\`force\`, use only if the game crashed due to a start error and the bot does not allow it to be started again`];16module.exports.getHelpText = function()17{18 return `Starts the game hosted in the channel. It will take 60 seconds for it to start generating the map and nation starts (so if you want to cancel it, you can kill the server task with the kill command before that time).`;19};20module.exports.isInvoked = function(message, command, args, isDirectMessage, wasSentInGameChannel)21{22 if (regexp.test(command) === true && wasSentInGameChannel === true)23 {24 return true;25 }26 else return false;27};28module.exports.invoke = function(message, command, options)29{30 if (options.game.gameType !== config.dom4GameTypeName && options.game.gameType !== config.dom5GameTypeName)31 {32 message.channel.send("Only Dominions games support this function.");33 return;34 }35 if (options.game.isServerOnline === false)36 {37 message.channel.send("This game's server is not online.");38 return;39 }40 if (options.game.isOnline == null)41 {42 message.channel.send("There is no instance of this game online. It might be in the process of a timer change if someone else used the command, in which case you'll need to wait a few seconds.");43 return;44 }45 if (permissions.equalOrHigher("gameMaster", options.member, message.guild.id, options.game.organizer.id) === false)46 {47 message.channel.send(`Sorry, you do not have the permissions to do this. Only this game's organizer (${options.game.organizer.user.username}) or GMs can do this.`);48 return;49 }50 if (options.game.wasStarted === true && forceRegexp.test(options.args[0]) === false)51 {52 message.channel.send(`The game was already started.`);53 return;54 }55 rw.log("general", `${message.author.username} requested to start the game ${options.game.name}.`);56 options.game.start(function(err)57 {58 if (err)59 {60 message.channel.send(err);61 return;62 }63 rw.log("general", `The game ${options.game.name} is starting.`);64 message.channel.send("The game will start the map and nation generation process in 60 seconds.");65 channelFunctions.moveGameToStartedCategory(options.game, function(err)66 {67 if (err)68 {69 message.channel.send(`Could not move this channel to the ${config.gameCategoryName} category; someone with privileges should do it manually.`);70 }71 rw.log("general", `Moved the game ${options.game.name} to the ${config.gameCategoryName} category.`);72 });73 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { forceRegExp } = require('playwright-core/lib/utils/utils');2const { forceRegExp } = require('playwright/lib/utils/utils');3const { forceRegExp } = require('playwright-chromium/lib/utils/utils');4const { forceRegExp } = require('playwright-firefox/lib/utils/utils');5const { forceRegExp } = require('playwright-webkit/lib/utils/utils');6const { forceRegExp } = require('playwright/lib/utils/utils');7const { forceRegExp } = require('playwright-chromium/lib/utils/utils');8const { forceRegExp } = require('playwright-firefox/lib/utils/utils');9const { forceRegExp } = require('playwright-webkit/lib/utils/utils');10const { forceRegExp } = require('playwright/lib/utils/utils');11const { forceRegExp } = require('playwright-chromium/lib/utils/utils');12const { forceRegExp } = require('playwright-firefox/lib/utils/utils');13const { forceRegExp } = require('playwright-webkit/lib/utils/utils');14const { forceRegExp } = require('playwright/lib/utils/utils');15const { forceRegExp } = require('playwright-chromium/lib/utils/utils');16const { forceRegExp } = require('playwright-firefox/lib/utils/utils');17const { forceRegExp } = require('playwright-webkit/lib/utils/utils');18const { forceRegExp } = require('playwright/lib/utils/utils');19const { forceRegExp } = require('playwright-chromium/lib/utils/utils');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { forceRegExp } = require('playwright/lib/server/frames');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 await page.click(forceRegExp('Sign in'));7 await page.fill(forceRegExp('Email or phone'), '

Full Screen

Using AI Code Generation

copy

Full Screen

1const { forceRegExp } = require('playwright-core/lib/utils/utils');2const { isRegExp } = require('playwright-core/lib/utils/utils');3const { isString } = require('playwright-core/lib/utils/utils');4const { isNumber } = require('playwright-core/lib/utils/utils');5const { isBoolean } = require('playwright-core/lib/utils/utils');6const { isObject } = require('playwright-core/lib/utils/utils');7const { isPromise } = require('playwright-core/lib/utils/utils');8const { isFunction } = require('playwright-core/lib/utils/utils');9const { isNull } = require('playwright-core/lib/utils/utils');10const { isUndefined } = require('playwright-core/lib/utils/utils');11const { isArrayOfStrings } = require('playwright-core/lib/utils/utils');12const { isArrayOfRegExps } = require('playwright-core/lib/utils/utils');13const { isArrayOfNumbers } = require('playwright-core/lib/utils/utils');14const { isMap } = require('playwright-core/lib/utils/utils');15const { isSet } = require('playwright-core/lib/utils/utils');16const { isDate } = require('playwright-core/lib/utils/utils');17const { isRegExp } = require('playwright-core/lib/utils/utils');18const { isRegExp } = require('playwright-core

Full Screen

Using AI Code Generation

copy

Full Screen

1const { forceRegExp } = require('playwright/lib/utils/utils');2const regex = forceRegExp('test');3console.log(regex);4const { forceRegExp } = require('playwright/lib/utils/utils');5const regex = forceRegExp(/test/);6console.log(regex);7const { forceRegExp } = require('playwright/lib/utils/utils');8const regex = forceRegExp(new RegExp('test'));9console.log(regex);10const { forceRegExp } = require('playwright/lib/utils/utils');11const regex = forceRegExp(null);12console.log(regex);13const { forceRegExp } = require('playwright/lib/utils/utils');14const regex = forceRegExp(undefined);15console.log(regex);16const { forceRegExp } = require('playwright/lib/utils/utils');17const regex = forceRegExp(1);18console.log(regex);19const { forceRegExp } = require('playwright/lib/utils/utils');20const regex = forceRegExp({});21console.log(regex);22const { forceRegExp } = require('playwright/lib/utils/utils');23const regex = forceRegExp([]);24console.log(regex);25const { forceRegExp } = require('playwright/lib/utils/utils');26const regex = forceRegExp(() => {});27console.log(regex);28const { forceRegExp } = require('playwright/lib/utils/utils');29const regex = forceRegExp(Symbol('test'));30console.log(regex);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { forceRegExp } = require("@playwright/test/lib/server/regExpSerializer");2const regExp = forceRegExp(/test/);3console.log(regExp);4const { forceRegExp } = require("@playwright/test/lib/server/regExpSerializer");5const regExp = forceRegExp(/test/);6console.log(regExp);7const { forceRegExp } = require("@playwright/test/lib/server/regExpSerializer");8const regExp = forceRegExp(/test/);9console.log(regExp);10const { forceRegExp } = require("@playwright/test/lib/server/regExpSerializer");11const regExp = forceRegExp(/test/);12console.log(regExp);13const { forceRegExp } = require("@playwright/test/lib/server/regExpSerializer");14const regExp = forceRegExp(/test/);15console.log(regExp);16const { forceRegExp } = require("@playwright/test/lib/server/regExpSerializer");17const regExp = forceRegExp(/test/);18console.log(regExp);19const { forceRegExp } = require("@playwright/test/lib/server/regExpSerializer");20const regExp = forceRegExp(/test/);21console.log(regExp);22const { forceRegExp } = require("@playwright/test/lib/server/regExpSerializer");

Full Screen

Using AI Code Generation

copy

Full Screen

1const { forceRegExp } = require('playwright/lib/utils/regexpparser');2console.log(result.groups);3const { forceRegExp } = require('playwright/lib/utils/regexpparser');4console.log(result.groups);5const { forceRegExp } = require('playwright/lib/utils/regexpparser');6console.log(result.groups);7const { forceRegExp } = require('playwright/lib/utils/regexpparser');8console.log(result.groups);9const { forceRegExp } = require('playwright/lib/utils/regexpparser');10console.log(result.groups);11const { forceRegExp

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal 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