Best JavaScript code snippet using playwright-internal
cssTokenizer.js
Source:cssTokenizer.js
...164 }165 }166 else if(code == 0x27) return consumeAStringToken();167 else if(code == 0x28) return new OpenParenToken();168 else if(code == 0x29) return new CloseParenToken();169 else if(code == 0x2a) {170 if(next() == 0x3d) {171 consume();172 return new SubstringMatchToken();173 } else {174 return new DelimToken(code);175 }176 }177 else if(code == 0x2b) {178 if(startsWithANumber()) {179 reconsume();180 return consumeANumericToken();181 } else {182 return new DelimToken(code);183 }184 }185 else if(code == 0x2c) return new CommaToken();186 else if(code == 0x2d) {187 if(startsWithANumber()) {188 reconsume();189 return consumeANumericToken();190 } else if(next(1) == 0x2d && next(2) == 0x3e) {191 consume(2);192 return new CDCToken();193 } else if(startsWithAnIdentifier()) {194 reconsume();195 return consumeAnIdentlikeToken();196 } else {197 return new DelimToken(code);198 }199 }200 else if(code == 0x2e) {201 if(startsWithANumber()) {202 reconsume();203 return consumeANumericToken();204 } else {205 return new DelimToken(code);206 }207 }208 else if(code == 0x3a) return new ColonToken;209 else if(code == 0x3b) return new SemicolonToken;210 else if(code == 0x3c) {211 if(next(1) == 0x21 && next(2) == 0x2d && next(3) == 0x2d) {212 consume(3);213 return new CDOToken();214 } else {215 return new DelimToken(code);216 }217 }218 else if(code == 0x40) {219 if(wouldStartAnIdentifier(next(1), next(2), next(3))) {220 return new AtKeywordToken(consumeAName());221 } else {222 return new DelimToken(code);223 }224 }225 else if(code == 0x5b) return new OpenSquareToken();226 else if(code == 0x5c) {227 if(startsWithAValidEscape()) {228 reconsume();229 return consumeAnIdentlikeToken();230 } else {231 parseerror();232 return new DelimToken(code);233 }234 }235 else if(code == 0x5d) return new CloseSquareToken();236 else if(code == 0x5e) {237 if(next() == 0x3d) {238 consume();239 return new PrefixMatchToken();240 } else {241 return new DelimToken(code);242 }243 }244 else if(code == 0x7b) return new OpenCurlyToken();245 else if(code == 0x7c) {246 if(next() == 0x3d) {247 consume();248 return new DashMatchToken();249 } else if(next() == 0x7c) {250 consume();251 return new ColumnToken();252 } else {253 return new DelimToken(code);254 }255 }256 else if(code == 0x7d) return new CloseCurlyToken();257 else if(code == 0x7e) {258 if(next() == 0x3d) {259 consume();260 return new IncludeMatchToken();261 } else {262 return new DelimToken(code);263 }264 }265 else if(digit(code)) {266 reconsume();267 return consumeANumericToken();268 }269 else if(namestartchar(code)) {270 reconsume();271 return consumeAnIdentlikeToken();272 }273 else if(eof()) return new EOFToken();274 else return new DelimToken(code);275 };276 var consumeComments = function() {277 while(next(1) == 0x2f && next(2) == 0x2a) {278 consume(2);279 while(true) {280 consume();281 if(code == 0x2a && next() == 0x2f) {282 consume();283 break;284 } else if(eof()) {285 parseerror();286 return;287 }288 }289 }290 };291 var consumeANumericToken = function() {292 var num = consumeANumber();293 if(wouldStartAnIdentifier(next(1), next(2), next(3))) {294 var token = new DimensionToken();295 token.value = num.value;296 token.repr = num.repr;297 token.type = num.type;298 token.unit = consumeAName();299 return token;300 } else if(next() == 0x25) {301 consume();302 var token = new PercentageToken();303 token.value = num.value;304 token.repr = num.repr;305 return token;306 } else {307 var token = new NumberToken();308 token.value = num.value;309 token.repr = num.repr;310 token.type = num.type;311 return token;312 }313 };314 var consumeAnIdentlikeToken = function() {315 var str = consumeAName();316 if(str.toLowerCase() == "url" && next() == 0x28) {317 consume();318 while(whitespace(next(1)) && whitespace(next(2))) consume();319 if(next() == 0x22 || next() == 0x27) {320 return new FunctionToken(str);321 } else if(whitespace(next()) && (next(2) == 0x22 || next(2) == 0x27)) {322 return new FunctionToken(str);323 } else {324 return consumeAURLToken();325 }326 } else if(next() == 0x28) {327 consume();328 return new FunctionToken(str);329 } else {330 return new IdentToken(str);331 }332 };333 var consumeAStringToken = function(endingCodePoint) {334 if(endingCodePoint === undefined) endingCodePoint = code;335 var string = "";336 while(consume()) {337 if(code == endingCodePoint || eof()) {338 return new StringToken(string);339 } else if(newline(code)) {340 parseerror();341 reconsume();342 return new BadStringToken();343 } else if(code == 0x5c) {344 if(eof(next())) {345 donothing();346 } else if(newline(next())) {347 consume();348 } else {349 string += stringFromCode(consumeEscape())350 }351 } else {352 string += stringFromCode(code);353 }354 }355 };356 var consumeAURLToken = function() {357 var token = new URLToken("");358 while(whitespace(next())) consume();359 if(eof(next())) return token;360 while(consume()) {361 if(code == 0x29 || eof()) {362 return token;363 } else if(whitespace(code)) {364 while(whitespace(next())) consume();365 if(next() == 0x29 || eof(next())) {366 consume();367 return token;368 } else {369 consumeTheRemnantsOfABadURL();370 return new BadURLToken();371 }372 } else if(code == 0x22 || code == 0x27 || code == 0x28 || nonprintable(code)) {373 parseerror();374 consumeTheRemnantsOfABadURL();375 return new BadURLToken();376 } else if(code == 0x5c) {377 if(startsWithAValidEscape()) {378 token.value += stringFromCode(consumeEscape());379 } else {380 parseerror();381 consumeTheRemnantsOfABadURL();382 return new BadURLToken();383 }384 } else {385 token.value += stringFromCode(code);386 }387 }388 };389 var consumeEscape = function() {390 // Assume the the current character is the \391 // and the next code point is not a newline.392 consume();393 if(hexdigit(code)) {394 // Consume 1-6 hex digits395 var digits = [code];396 for(var total = 0; total < 5; total++) {397 if(hexdigit(next())) {398 consume();399 digits.push(code);400 } else {401 break;402 }403 }404 if(whitespace(next())) consume();405 var value = parseInt(digits.map(function(x){return String.fromCharCode(x);}).join(''), 16);406 if( value > maximumallowedcodepoint ) value = 0xfffd;407 return value;408 } else if(eof()) {409 return 0xfffd;410 } else {411 return code;412 }413 };414 var areAValidEscape = function(c1, c2) {415 if(c1 != 0x5c) return false;416 if(newline(c2)) return false;417 return true;418 };419 var startsWithAValidEscape = function() {420 return areAValidEscape(code, next());421 };422 var wouldStartAnIdentifier = function(c1, c2, c3) {423 if(c1 == 0x2d) {424 return namestartchar(c2) || c2 == 0x2d || areAValidEscape(c2, c3);425 } else if(namestartchar(c1)) {426 return true;427 } else if(c1 == 0x5c) {428 return areAValidEscape(c1, c2);429 } else {430 return false;431 }432 };433 var startsWithAnIdentifier = function() {434 return wouldStartAnIdentifier(code, next(1), next(2));435 };436 var wouldStartANumber = function(c1, c2, c3) {437 if(c1 == 0x2b || c1 == 0x2d) {438 if(digit(c2)) return true;439 if(c2 == 0x2e && digit(c3)) return true;440 return false;441 } else if(c1 == 0x2e) {442 if(digit(c2)) return true;443 return false;444 } else if(digit(c1)) {445 return true;446 } else {447 return false;448 }449 };450 var startsWithANumber = function() {451 return wouldStartANumber(code, next(1), next(2));452 };453 var consumeAName = function() {454 var result = "";455 while(consume()) {456 if(namechar(code)) {457 result += stringFromCode(code);458 } else if(startsWithAValidEscape()) {459 result += stringFromCode(consumeEscape());460 } else {461 reconsume();462 return result;463 }464 }465 };466 var consumeANumber = function() {467 var repr = [];468 var type = "integer";469 if(next() == 0x2b || next() == 0x2d) {470 consume();471 repr += stringFromCode(code);472 }473 while(digit(next())) {474 consume();475 repr += stringFromCode(code);476 }477 if(next(1) == 0x2e && digit(next(2))) {478 consume();479 repr += stringFromCode(code);480 consume();481 repr += stringFromCode(code);482 type = "number";483 while(digit(next())) {484 consume();485 repr += stringFromCode(code);486 }487 }488 var c1 = next(1), c2 = next(2), c3 = next(3);489 if((c1 == 0x45 || c1 == 0x65) && digit(c2)) {490 consume();491 repr += stringFromCode(code);492 consume();493 repr += stringFromCode(code);494 type = "number";495 while(digit(next())) {496 consume();497 repr += stringFromCode(code);498 }499 } else if((c1 == 0x45 || c1 == 0x65) && (c2 == 0x2b || c2 == 0x2d) && digit(c3)) {500 consume();501 repr += stringFromCode(code);502 consume();503 repr += stringFromCode(code);504 consume();505 repr += stringFromCode(code);506 type = "number";507 while(digit(next())) {508 consume();509 repr += stringFromCode(code);510 }511 }512 var value = convertAStringToANumber(repr);513 return {type:type, value:value, repr:repr};514 };515 var convertAStringToANumber = function(string) {516 // CSS's number rules are identical to JS, afaik.517 return +string;518 };519 var consumeTheRemnantsOfABadURL = function() {520 while(consume()) {521 if(code == 0x29 || eof()) {522 return;523 } else if(startsWithAValidEscape()) {524 consumeEscape();525 donothing();526 } else {527 donothing();528 }529 }530 };531 var iterationCount = 0;532 while(!eof(next())) {533 tokens.push(consumeAToken());534 iterationCount++;535 if(iterationCount > str.length*2) return "I'm infinite-looping!";536 }537 return tokens;538}539function CSSParserToken() { throw "Abstract Base Class"; }540CSSParserToken.prototype.toJSON = function() {541 return {token: this.tokenType};542}543CSSParserToken.prototype.toString = function() { return this.tokenType; }544CSSParserToken.prototype.toSource = function() { return ''+this; }545function BadStringToken() { return this; }546BadStringToken.prototype = Object.create(CSSParserToken.prototype);547BadStringToken.prototype.tokenType = "BADSTRING";548function BadURLToken() { return this; }549BadURLToken.prototype = Object.create(CSSParserToken.prototype);550BadURLToken.prototype.tokenType = "BADURL";551function WhitespaceToken() { return this; }552WhitespaceToken.prototype = Object.create(CSSParserToken.prototype);553WhitespaceToken.prototype.tokenType = "WHITESPACE";554WhitespaceToken.prototype.toString = function() { return "WS"; }555WhitespaceToken.prototype.toSource = function() { return " "; }556function CDOToken() { return this; }557CDOToken.prototype = Object.create(CSSParserToken.prototype);558CDOToken.prototype.tokenType = "CDO";559CDOToken.prototype.toSource = function() { return "<!--"; }560function CDCToken() { return this; }561CDCToken.prototype = Object.create(CSSParserToken.prototype);562CDCToken.prototype.tokenType = "CDC";563CDCToken.prototype.toSource = function() { return "-->"; }564function ColonToken() { return this; }565ColonToken.prototype = Object.create(CSSParserToken.prototype);566ColonToken.prototype.tokenType = ":";567function SemicolonToken() { return this; }568SemicolonToken.prototype = Object.create(CSSParserToken.prototype);569SemicolonToken.prototype.tokenType = ";";570function CommaToken() { return this; }571CommaToken.prototype = Object.create(CSSParserToken.prototype);572CommaToken.prototype.tokenType = ",";573function GroupingToken() { throw "Abstract Base Class"; }574GroupingToken.prototype = Object.create(CSSParserToken.prototype);575function OpenCurlyToken() { this.value = "{"; this.mirror = "}"; return this; }576OpenCurlyToken.prototype = Object.create(GroupingToken.prototype);577OpenCurlyToken.prototype.tokenType = "{";578function CloseCurlyToken() { this.value = "}"; this.mirror = "{"; return this; }579CloseCurlyToken.prototype = Object.create(GroupingToken.prototype);580CloseCurlyToken.prototype.tokenType = "}";581function OpenSquareToken() { this.value = "["; this.mirror = "]"; return this; }582OpenSquareToken.prototype = Object.create(GroupingToken.prototype);583OpenSquareToken.prototype.tokenType = "[";584function CloseSquareToken() { this.value = "]"; this.mirror = "["; return this; }585CloseSquareToken.prototype = Object.create(GroupingToken.prototype);586CloseSquareToken.prototype.tokenType = "]";587function OpenParenToken() { this.value = "("; this.mirror = ")"; return this; }588OpenParenToken.prototype = Object.create(GroupingToken.prototype);589OpenParenToken.prototype.tokenType = "(";590function CloseParenToken() { this.value = ")"; this.mirror = "("; return this; }591CloseParenToken.prototype = Object.create(GroupingToken.prototype);592CloseParenToken.prototype.tokenType = ")";593function IncludeMatchToken() { return this; }594IncludeMatchToken.prototype = Object.create(CSSParserToken.prototype);595IncludeMatchToken.prototype.tokenType = "~=";596function DashMatchToken() { return this; }597DashMatchToken.prototype = Object.create(CSSParserToken.prototype);598DashMatchToken.prototype.tokenType = "|=";599function PrefixMatchToken() { return this; }600PrefixMatchToken.prototype = Object.create(CSSParserToken.prototype);601PrefixMatchToken.prototype.tokenType = "^=";602function SuffixMatchToken() { return this; }603SuffixMatchToken.prototype = Object.create(CSSParserToken.prototype);604SuffixMatchToken.prototype.tokenType = "$=";...
oneLineRule.js
Source:oneLineRule.js
1"use strict";2var __extends = (this && this.__extends) || function (d, b) {3 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];4 function __() { this.constructor = d; }5 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());6};7var ts = require("typescript");8var Lint = require("../lint");9var OPTION_BRACE = "check-open-brace";10var OPTION_CATCH = "check-catch";11var OPTION_ELSE = "check-else";12var OPTION_FINALLY = "check-finally";13var OPTION_WHITESPACE = "check-whitespace";14var Rule = (function (_super) {15 __extends(Rule, _super);16 function Rule() {17 _super.apply(this, arguments);18 }19 Rule.prototype.apply = function (sourceFile) {20 var oneLineWalker = new OneLineWalker(sourceFile, this.getOptions());21 return this.applyWithWalker(oneLineWalker);22 };23 Rule.metadata = {24 ruleName: "one-line",25 description: "Requires the specified tokens to be on the same line as the expression preceding them.",26 optionsDescription: (_a = ["\n Five arguments may be optionally provided:\n\n * `\"check-catch\"` checks that `catch` is on the same line as the closing brace for `try`.\n * `\"check-finally\"` checks that `finally` is on the same line as the closing brace for `catch`.\n * `\"check-else\"` checks that `else` is on the same line as the closing brace for `if`.\n * `\"check-open-brace\"` checks that an open brace falls on the same line as its preceding expression.\n * `\"check-whitespace\"` checks preceding whitespace for the specified tokens."], _a.raw = ["\n Five arguments may be optionally provided:\n\n * \\`\"check-catch\"\\` checks that \\`catch\\` is on the same line as the closing brace for \\`try\\`.\n * \\`\"check-finally\"\\` checks that \\`finally\\` is on the same line as the closing brace for \\`catch\\`.\n * \\`\"check-else\"\\` checks that \\`else\\` is on the same line as the closing brace for \\`if\\`.\n * \\`\"check-open-brace\"\\` checks that an open brace falls on the same line as its preceding expression.\n * \\`\"check-whitespace\"\\` checks preceding whitespace for the specified tokens."], Lint.Utils.dedent(_a)),27 options: {28 type: "array",29 items: {30 type: "string",31 enum: ["check-catch", "check-finally", "check-else", "check-open-brace", "check-whitespace"],32 },33 minLength: 0,34 maxLength: 5,35 },36 optionExamples: ['[true, "check-catch", "check-finally", "check-else"]'],37 type: "style",38 };39 Rule.BRACE_FAILURE_STRING = "misplaced opening brace";40 Rule.CATCH_FAILURE_STRING = "misplaced 'catch'";41 Rule.ELSE_FAILURE_STRING = "misplaced 'else'";42 Rule.FINALLY_FAILURE_STRING = "misplaced 'finally'";43 Rule.WHITESPACE_FAILURE_STRING = "missing whitespace";44 return Rule;45 var _a;46}(Lint.Rules.AbstractRule));47exports.Rule = Rule;48var OneLineWalker = (function (_super) {49 __extends(OneLineWalker, _super);50 function OneLineWalker() {51 _super.apply(this, arguments);52 }53 OneLineWalker.prototype.visitIfStatement = function (node) {54 var sourceFile = node.getSourceFile();55 var thenStatement = node.thenStatement;56 if (thenStatement.kind === ts.SyntaxKind.Block) {57 var expressionCloseParen = node.getChildAt(3);58 var thenOpeningBrace = thenStatement.getChildAt(0);59 this.handleOpeningBrace(expressionCloseParen, thenOpeningBrace);60 }61 var elseStatement = node.elseStatement;62 if (elseStatement != null) {63 var elseKeyword = getFirstChildOfKind(node, ts.SyntaxKind.ElseKeyword);64 if (elseStatement.kind === ts.SyntaxKind.Block) {65 var elseOpeningBrace = elseStatement.getChildAt(0);66 this.handleOpeningBrace(elseKeyword, elseOpeningBrace);67 }68 if (this.hasOption(OPTION_ELSE)) {69 var thenStatementEndLine = sourceFile.getLineAndCharacterOfPosition(thenStatement.getEnd()).line;70 var elseKeywordLine = sourceFile.getLineAndCharacterOfPosition(elseKeyword.getStart()).line;71 if (thenStatementEndLine !== elseKeywordLine) {72 var failure = this.createFailure(elseKeyword.getStart(), elseKeyword.getWidth(), Rule.ELSE_FAILURE_STRING);73 this.addFailure(failure);74 }75 }76 }77 _super.prototype.visitIfStatement.call(this, node);78 };79 OneLineWalker.prototype.visitCatchClause = function (node) {80 var catchClosingParen = node.getChildren().filter(function (n) { return n.kind === ts.SyntaxKind.CloseParenToken; })[0];81 var catchOpeningBrace = node.block.getChildAt(0);82 this.handleOpeningBrace(catchClosingParen, catchOpeningBrace);83 _super.prototype.visitCatchClause.call(this, node);84 };85 OneLineWalker.prototype.visitTryStatement = function (node) {86 var sourceFile = node.getSourceFile();87 var catchClause = node.catchClause;88 var finallyBlock = node.finallyBlock;89 var finallyKeyword = node.getChildren().filter(function (n) { return n.kind === ts.SyntaxKind.FinallyKeyword; })[0];90 var tryKeyword = node.getChildAt(0);91 var tryBlock = node.tryBlock;92 var tryOpeningBrace = tryBlock.getChildAt(0);93 this.handleOpeningBrace(tryKeyword, tryOpeningBrace);94 if (this.hasOption(OPTION_CATCH) && catchClause != null) {95 var tryClosingBrace = node.tryBlock.getChildAt(node.tryBlock.getChildCount() - 1);96 var catchKeyword = catchClause.getChildAt(0);97 var tryClosingBraceLine = sourceFile.getLineAndCharacterOfPosition(tryClosingBrace.getEnd()).line;98 var catchKeywordLine = sourceFile.getLineAndCharacterOfPosition(catchKeyword.getStart()).line;99 if (tryClosingBraceLine !== catchKeywordLine) {100 var failure = this.createFailure(catchKeyword.getStart(), catchKeyword.getWidth(), Rule.CATCH_FAILURE_STRING);101 this.addFailure(failure);102 }103 }104 if (finallyBlock != null && finallyKeyword != null) {105 var finallyOpeningBrace = finallyBlock.getChildAt(0);106 this.handleOpeningBrace(finallyKeyword, finallyOpeningBrace);107 if (this.hasOption(OPTION_FINALLY)) {108 var previousBlock = catchClause != null ? catchClause.block : node.tryBlock;109 var closingBrace = previousBlock.getChildAt(previousBlock.getChildCount() - 1);110 var closingBraceLine = sourceFile.getLineAndCharacterOfPosition(closingBrace.getEnd()).line;111 var finallyKeywordLine = sourceFile.getLineAndCharacterOfPosition(finallyKeyword.getStart()).line;112 if (closingBraceLine !== finallyKeywordLine) {113 var failure = this.createFailure(finallyKeyword.getStart(), finallyKeyword.getWidth(), Rule.FINALLY_FAILURE_STRING);114 this.addFailure(failure);115 }116 }117 }118 _super.prototype.visitTryStatement.call(this, node);119 };120 OneLineWalker.prototype.visitForStatement = function (node) {121 this.handleIterationStatement(node);122 _super.prototype.visitForStatement.call(this, node);123 };124 OneLineWalker.prototype.visitForInStatement = function (node) {125 this.handleIterationStatement(node);126 _super.prototype.visitForInStatement.call(this, node);127 };128 OneLineWalker.prototype.visitWhileStatement = function (node) {129 this.handleIterationStatement(node);130 _super.prototype.visitWhileStatement.call(this, node);131 };132 OneLineWalker.prototype.visitBinaryExpression = function (node) {133 var rightkind = node.right.kind;134 var opkind = node.operatorToken.kind;135 if (opkind === ts.SyntaxKind.EqualsToken && rightkind === ts.SyntaxKind.ObjectLiteralExpression) {136 var equalsToken = node.getChildAt(1);137 var openBraceToken = node.right.getChildAt(0);138 this.handleOpeningBrace(equalsToken, openBraceToken);139 }140 _super.prototype.visitBinaryExpression.call(this, node);141 };142 OneLineWalker.prototype.visitVariableDeclaration = function (node) {143 var initializer = node.initializer;144 if (initializer != null && initializer.kind === ts.SyntaxKind.ObjectLiteralExpression) {145 var equalsToken = node.getChildren().filter(function (n) { return n.kind === ts.SyntaxKind.EqualsToken; })[0];146 var openBraceToken = initializer.getChildAt(0);147 this.handleOpeningBrace(equalsToken, openBraceToken);148 }149 _super.prototype.visitVariableDeclaration.call(this, node);150 };151 OneLineWalker.prototype.visitDoStatement = function (node) {152 var doKeyword = node.getChildAt(0);153 var statement = node.statement;154 if (statement.kind === ts.SyntaxKind.Block) {155 var openBraceToken = statement.getChildAt(0);156 this.handleOpeningBrace(doKeyword, openBraceToken);157 }158 _super.prototype.visitDoStatement.call(this, node);159 };160 OneLineWalker.prototype.visitModuleDeclaration = function (node) {161 var nameNode = node.name;162 var body = node.body;163 if (body.kind === ts.SyntaxKind.ModuleBlock) {164 var openBraceToken = body.getChildAt(0);165 this.handleOpeningBrace(nameNode, openBraceToken);166 }167 _super.prototype.visitModuleDeclaration.call(this, node);168 };169 OneLineWalker.prototype.visitEnumDeclaration = function (node) {170 var nameNode = node.name;171 var openBraceToken = getFirstChildOfKind(node, ts.SyntaxKind.OpenBraceToken);172 this.handleOpeningBrace(nameNode, openBraceToken);173 _super.prototype.visitEnumDeclaration.call(this, node);174 };175 OneLineWalker.prototype.visitSwitchStatement = function (node) {176 var closeParenToken = node.getChildAt(3);177 var openBraceToken = node.caseBlock.getChildAt(0);178 this.handleOpeningBrace(closeParenToken, openBraceToken);179 _super.prototype.visitSwitchStatement.call(this, node);180 };181 OneLineWalker.prototype.visitInterfaceDeclaration = function (node) {182 this.handleClassLikeDeclaration(node);183 _super.prototype.visitInterfaceDeclaration.call(this, node);184 };185 OneLineWalker.prototype.visitClassDeclaration = function (node) {186 this.handleClassLikeDeclaration(node);187 _super.prototype.visitClassDeclaration.call(this, node);188 };189 OneLineWalker.prototype.visitFunctionDeclaration = function (node) {190 this.handleFunctionLikeDeclaration(node);191 _super.prototype.visitFunctionDeclaration.call(this, node);192 };193 OneLineWalker.prototype.visitMethodDeclaration = function (node) {194 this.handleFunctionLikeDeclaration(node);195 _super.prototype.visitMethodDeclaration.call(this, node);196 };197 OneLineWalker.prototype.visitConstructorDeclaration = function (node) {198 this.handleFunctionLikeDeclaration(node);199 _super.prototype.visitConstructorDeclaration.call(this, node);200 };201 OneLineWalker.prototype.visitArrowFunction = function (node) {202 var body = node.body;203 if (body != null && body.kind === ts.SyntaxKind.Block) {204 var arrowToken = getFirstChildOfKind(node, ts.SyntaxKind.EqualsGreaterThanToken);205 var openBraceToken = node.body.getChildAt(0);206 this.handleOpeningBrace(arrowToken, openBraceToken);207 }208 _super.prototype.visitArrowFunction.call(this, node);209 };210 OneLineWalker.prototype.handleFunctionLikeDeclaration = function (node) {211 var body = node.body;212 if (body != null && body.kind === ts.SyntaxKind.Block) {213 var openBraceToken = node.body.getChildAt(0);214 if (node.type != null) {215 this.handleOpeningBrace(node.type, openBraceToken);216 }217 else {218 var closeParenToken = getFirstChildOfKind(node, ts.SyntaxKind.CloseParenToken);219 this.handleOpeningBrace(closeParenToken, openBraceToken);220 }221 }222 };223 OneLineWalker.prototype.handleClassLikeDeclaration = function (node) {224 var lastNodeOfDeclaration = node.name;225 var openBraceToken = getFirstChildOfKind(node, ts.SyntaxKind.OpenBraceToken);226 if (node.heritageClauses != null) {227 lastNodeOfDeclaration = node.heritageClauses[node.heritageClauses.length - 1];228 }229 else if (node.typeParameters != null) {230 lastNodeOfDeclaration = node.typeParameters[node.typeParameters.length - 1];231 }232 this.handleOpeningBrace(lastNodeOfDeclaration, openBraceToken);233 };234 OneLineWalker.prototype.handleIterationStatement = function (node) {235 var closeParenToken = node.getChildAt(node.getChildCount() - 2);236 var statement = node.statement;237 if (statement.kind === ts.SyntaxKind.Block) {238 var openBraceToken = statement.getChildAt(0);239 this.handleOpeningBrace(closeParenToken, openBraceToken);240 }241 };242 OneLineWalker.prototype.handleOpeningBrace = function (previousNode, openBraceToken) {243 if (previousNode == null || openBraceToken == null) {244 return;245 }246 var sourceFile = previousNode.getSourceFile();247 var previousNodeLine = sourceFile.getLineAndCharacterOfPosition(previousNode.getEnd()).line;248 var openBraceLine = sourceFile.getLineAndCharacterOfPosition(openBraceToken.getStart()).line;249 var failure;250 if (this.hasOption(OPTION_BRACE) && previousNodeLine !== openBraceLine) {251 failure = this.createFailure(openBraceToken.getStart(), openBraceToken.getWidth(), Rule.BRACE_FAILURE_STRING);252 }253 else if (this.hasOption(OPTION_WHITESPACE) && previousNode.getEnd() === openBraceToken.getStart()) {254 failure = this.createFailure(openBraceToken.getStart(), openBraceToken.getWidth(), Rule.WHITESPACE_FAILURE_STRING);255 }256 if (failure) {257 this.addFailure(failure);258 }259 };260 return OneLineWalker;261}(Lint.RuleWalker));262function getFirstChildOfKind(node, kind) {263 return node.getChildren().filter(function (child) { return child.kind === kind; })[0];...
spaces.js
Source:spaces.js
1/**2 * @fileoverview A task to automatically adjust spaces as needed.3 * @author Nicholas C. Zakas4 */5//-----------------------------------------------------------------------------6// Helpers7//-----------------------------------------------------------------------------8function findNextCommaOrSemicolon(layout, start) {9 return layout.findNext(part => part.type === "Punctuator", start);10}11function normalizePunctuatorSpacing(layout) {12 let token = findNextCommaOrSemicolon(layout);13 while (token) {14 switch (token.value) {15 case ",":16 case ";":17 layout.noSpaceBefore(token);18 layout.spaceAfter(token);19 break;20 21 case ".":22 layout.noSpaces(token);23 break;24 default:25 if (token.value.includes("=")) {26 layout.spaceBefore(token);27 layout.spaceAfter(token);28 }29 }30 token = findNextCommaOrSemicolon(layout, token);31 }32}33function spaceKeywordAndBrace(node, bodyKey, layout) {34 const firstToken = layout.firstToken(node);35 layout.spaceAfter(firstToken);36 const braceToken = layout.firstToken(node[bodyKey]);37 if (braceToken.value === "{") {38 layout.spaceBefore(braceToken);39 }40}41//-----------------------------------------------------------------------------42// Task43//-----------------------------------------------------------------------------44export default function(context) {45 const layout = context.layout;46 // first, adjust all commas47 normalizePunctuatorSpacing(layout);48 return {49 ArrayExpression(node) {50 51 const { firstToken, lastToken } = layout.boundaryTokens(node);52 layout.noSpaceAfter(firstToken);53 54 // no spacing work for multiline55 if (!layout.isMultiLine(node)) {56 57 layout.noSpaceBefore(lastToken);58 if (node.elements.length) {59 node.elements.forEach((element, index) => {60 if (index > 0) {61 layout.spaceBefore(element);62 }63 layout.noSpaceAfter(element);64 });65 }66 }67 },68 ArrayPattern(node) {69 this.ArrayExpression(node);70 },71 ArrowFunctionExpression(node) {72 73 let openParenToken, closeParenToken;74 const firstToken = layout.firstToken(node);75 76 if (node.async) {77 layout.spaceAfter(firstToken);78 }79 80 if (node.params.length === 0) {81 82 openParenToken = node.async83 ? layout.findNext("(", firstToken)84 : firstToken;85 86 closeParenToken = layout.findNext(")", openParenToken);87 } else if (node.params.length === 1) {88 89 if (node.async) {90 layout.spaceAfter(firstToken);91 openParenToken = layout.findPrevious(part => {92 return part === firstToken || part.value === "(";93 }, node.params[0]);94 95 if (openParenToken.value !== "(") {96 openParenToken = null;97 } else {98 closeParenToken = layout.findNext(")", node.params[0]);99 }100 101 } else {102 if (firstToken.value === "(") {103 openParenToken = firstToken;104 closeParenToken = layout.findNext(")", node.params[0]);105 }106 }107 108 } else {109 110 openParenToken = node.async111 ? layout.findNext("(", firstToken)112 : firstToken;113 114 closeParenToken = layout.findNext(")", node.params[node.params.length - 1]);115 }116 117 if (openParenToken) {118 // have to do both in case there's a comment inside119 layout.noSpaceAfter(openParenToken);120 layout.noSpaceBefore(closeParenToken);121 }122 },123 AwaitExpression(node) {124 const firstToken = layout.firstToken(node);125 layout.spaceAfter(firstToken);126 },127 BinaryExpression(node) {128 const firstToken = layout.firstToken(node);129 const operatorToken = layout.findNext(node.operator, firstToken);130 layout.spaces(operatorToken);131 },132 BlockStatement(node) {133 const { firstToken, lastToken } = layout.boundaryTokens(node);134 if (layout.isSameLine(firstToken, lastToken)) {135 if (node.body.length) {136 layout.spaceAfter(firstToken);137 layout.spaceBefore(lastToken);138 } else {139 layout.noSpaceAfter(firstToken);140 layout.noSpaceBefore(lastToken);141 }142 }143 },144 ConditionalExpression(node) {145 const questionMark = layout.findPrevious("?", node.consequent);146 const colon = layout.findNext(":", node.consequent);147 148 layout.spaceBefore(questionMark);149 layout.spaces(questionMark);150 layout.spaces(colon);151 },152 DoWhileStatement(node) {153 spaceKeywordAndBrace(node, "body", layout);154 const whileToken = layout.findPrevious("while", node.test);155 layout.spaces(whileToken);156 },157 ExportNamedDeclaration(node) {158 const firstToken = layout.firstToken(node);159 layout.spaceAfter(firstToken);160 if (node.specifiers.length) {161 // adjust spaces around braces162 layout.spaceAfter(layout.findNext("{", firstToken));163 layout.spaceBefore(layout.findNext("}", firstToken));164 }165 },166 ForStatement(node) {167 spaceKeywordAndBrace(node, "body", layout);168 },169 ForInStatement(node) {170 this.ForStatement(node);171 },172 ForOfStatement(node) {173 this.ForStatement(node);174 },175 FunctionDeclaration(node, parent) {176 this.FunctionExpression(node, parent);177 },178 FunctionExpression(node, parent) {179 // ESTree quirk: concise methods don't have "function" keyword180 const isConcise =181 (parent.type === "Property" && parent.method) ||182 (parent.type === "MethodDefinition");183 let token = layout.firstToken(node);184 let id, openParen;185 if (!isConcise) {186 187 // "async" keyword188 if (token.value === "async") {189 layout.spaceAfter(token);190 token = layout.nextToken(token);191 }192 // "function" keyword193 layout.spaceAfter(token);194 token = layout.nextToken(token);195 // "*" punctuator196 if (token.value === "*") {197 layout.noSpaceAfter(token);198 token = layout.nextToken(token);199 }200 // function name201 if (token.type === "Identifier") {202 layout.noSpaceAfter(token);203 token = layout.nextToken(token);204 }205 206 if (token.value === "(") {207 openParen = token;208 } else {209 throw new Error(`Unexpected token "${token.value}".`);210 }211 } else {212 let idStart = layout.firstToken(parent.key);213 id = idStart;214 if (parent.computed) {215 const leftBracket = layout.previousToken(idStart);216 layout.noSpaceAfter(leftBracket);217 const rightBracket = layout.nextToken(idStart);218 layout.noSpaceBefore(rightBracket);219 idStart = leftBracket;220 id = rightBracket;221 }222 if (parent.generator) {223 const star = layout.previousToken(idStart);224 layout.noSpaceAfter(star);225 }226 openParen = token;227 }228 if (id) {229 layout.noSpaceAfter(id);230 }231 232 layout.noSpaces(openParen);233 const openBrace = layout.firstToken(node.body);234 layout.spaceBefore(openBrace);235 236 const closeParen = layout.findPrevious(")", openBrace);237 layout.noSpaceBefore(closeParen);238 },239 240 IfStatement(node) {241 spaceKeywordAndBrace(node, "consequent", layout);242 if (node.alternate) {243 const elseToken = layout.findPrevious("else", node.alternate);244 layout.spaces(elseToken);245 }246 },247 ImportDeclaration(node) {248 const firstToken = layout.firstToken(node);249 layout.spaceAfter(firstToken);250 const fromToken = layout.findPrevious("from", node.source);251 layout.spaces(fromToken);252 if (node.specifiers.some(node => node.type === "ImportSpecifier")) {253 // adjust spaces around braces254 layout.spaceAfter(layout.findNext("{", firstToken));255 layout.spaceBefore(layout.findNext("}", firstToken));256 }257 },258 LogicalExpression(node) {259 this.BinaryExpression(node);260 },261 MethodDefinition(node) {262 this.FunctionExpression(node.value, node);263 },264 ObjectExpression(node) {265 const { firstToken, lastToken } = layout.boundaryTokens(node);266 layout.spaceAfter(firstToken);267 if (!layout.isMultiLine(node)) {268 269 if (node.properties.length) {270 271 node.properties.forEach((property, index) => {272 273 if (index > 0) {274 layout.spaceBefore(property);275 }276 layout.noSpaceAfter(property);277 });278 }279 }280 281 layout.spaceBefore(lastToken);282 },283 ObjectPattern(node) {284 this.ObjectExpression(node);285 },286 Property(node) {287 // ensure there's a space after the colon in properties288 if (!node.shorthand && !node.method) {289 layout.spaceBefore(node.value);290 291 // also be sure to check spacing of computed properties292 if (node.computed) {293 const firstToken = layout.firstToken(node.key);294 const openBracket = layout.findPrevious("[", firstToken);295 const closeBracket = layout.findNext("]", firstToken);296 297 layout.noSpaceAfter(openBracket);298 layout.noSpaceBefore(closeBracket);299 layout.noSpaceAfter(closeBracket);300 } else {301 layout.noSpaceAfter(node.key);302 }303 }304 if (node.method) {305 layout.spaceBefore(node.value.body);306 }307 },308 ReturnStatement(node) {309 if (node.argument) {310 layout.spaceBefore(node.argument);311 } else {312 layout.noSpaceAfter(node);313 }314 },315 SwitchStatement(node) {316 const firstToken = layout.firstToken(node);317 layout.spaceAfter(firstToken);318 const braceToken = layout.findNext("{", node.discriminant);319 layout.spaceBefore(braceToken);320 },321 SwitchCase(node) {322 const colon = layout.findPrevious(":", node.consequent[0]);323 layout.noSpaceBefore(colon);324 layout.spaceAfter(colon);325 },326 TemplateLiteral(node) {327 const [firstQuasi, ...quasis] = node.quasis;328 if (quasis.length) {329 layout.noSpaceAfter(firstQuasi);330 331 quasis.forEach(quasi => {332 layout.noSpaceBefore(quasi);333 layout.noSpaceAfter(quasi);334 });335 }336 },337 ThrowStatement(node) {338 const firstToken = layout.firstToken(node);339 layout.spaceAfter(firstToken);340 },341 TryStatement(node) {342 spaceKeywordAndBrace(node, "block", layout);343 const catchToken = layout.firstToken(node.handler);344 layout.spaces(catchToken);345 const catchBraceToken = layout.firstToken(node.handler.body);346 layout.spaceBefore(catchBraceToken);347 if (node.finalizer) {348 const finallyBraceToken = layout.firstToken(node.finalizer);349 const finallyToken = layout.findPrevious("finally", finallyBraceToken);350 layout.spaces(finallyToken);351 }352 },353 UpdateExpression(node) {354 if (node.prefix) {355 const operatorToken = layout.firstToken(node);356 // "typeof" is also an operator and requires a space no matter what357 if (operatorToken.type === "Punctuator") {358 layout.noSpaceAfter(operatorToken);359 } else {360 layout.spaceAfter(operatorToken);361 }362 } else {363 const operatorToken = layout.lastToken(node);364 layout.noSpaceBefore(operatorToken);365 }366 },367 UnaryExpression(node) {368 this.UpdateExpression(node);369 },370 VariableDeclaration(node) {371 const firstToken = layout.firstToken(node);372 layout.spaceAfter(firstToken);373 },374 375 WhileStatement(node) {376 spaceKeywordAndBrace(node, "body", layout);377 },378 YieldExpression(node) {379 const firstToken = layout.firstToken(node);380 layout.spaceAfter(firstToken);381 },382 383 };...
lang.mjs
Source:lang.mjs
1import Parser, {2 sequence,3 alternatives,4 char,5 satisfy,6 regex,7 empty,8 lazy,9 succeed,10 string,11 item,12} from './parser.mjs';13import StateContext from './state-context.mjs';14import ContextWithHoles from './context-with-holes.mjs';15import { Outcome, Failure } from './outcome.mjs';16const snd = ([, x]) => x;17class Token {18 constructor(type, value) {19 this.type = type;20 this.value = value;21 }22 toString() {23 return `Token { type = ${this.type}, value = ${this.value} }`;24 }25}26const emptySigal = {};27function isToken(type, value = emptySigal) {28 return satisfy(29 x => {30 if (x != null && x.type === type) {31 return value === emptySigal || value === x.value;32 }33 return false;34 },35 c =>36 `${c} is not a token with type ${type}${37 value === empty ? '' : ` or value ${value}`38 }`39 );40}41class Rule {42 constructor(name, definition) {43 this.name = name;44 this.definition = definition;45 }46}47const hole = satisfy(o => {48 return o != null && typeof o === 'object' && ContextWithHoles.hole in o;49});50const whitespace = regex(/[ \t\n]+/);51const optWhitespace = whitespace.or(succeed(''));52const identStart = regex(/[a-zA-Z]/);53const identRest = regex(/[a-zA-Z0-9]*/).or(succeed(''));54const ident = sequence(identStart, identRest).tie();55const isLineTerminator = ch =>56 ch === 0x0a || ch === 0x0d || ch === 0x2028 || ch === 0x2029;57const nonEscapedStringCharacter = satisfy(58 ch => ch !== "'" && ch !== '\\' && ch !== '\n'59);60const hexDigit = alternatives(61 satisfy(ch => ch >= '0' && ch <= '9').map(ch => ch.charCodeAt(0) - 48),62 satisfy(ch => ch >= 'a' && ch <= 'f').map(ch => ch.charCodeAt(0) - 87),63 satisfy(ch => ch >= 'A' && ch <= 'F').map(ch => ch.charCodeAt(0) - 55)64);65const hexDigits = hexDigit66 .atLeast(1)67 .map(hexCodes => hexCodes.reduce((acc, hex) => (acc << 4) | hex, 0))68 .map(unescaped => String.fromCodePoint(unescaped));69const escapedStringCharacter = char('\\').then(70 alternatives(71 char('n').result('\n'),72 char('r').result('\r'),73 char('t').result('\t'),74 char('b').result('\b'),75 char('f').result('\f'),76 char('v').result('\v'),77 char('u').then(78 alternatives(sequence(char('{'), hexDigits, char('}')).map(snd))79 ),80 item()81 )82);83const stringLiteral = sequence(84 char("'"),85 alternatives(nonEscapedStringCharacter, escapedStringCharacter)86 .many()87 .tie(),88 char("'")89).map(snd);90const slash = char('/');91const reFlags = regex(/[gimuy]+/).or(succeed(''));92const looseRegexPattern = alternatives(93 sequence(regex(/\\\\/).map(s => '\\'), char('/')).tie(),94 regex(/[^\n\/]+/)95)96 .many()97 .tie();98const punctuator = alternatives(99 char('='),100 char('|'),101 char('('),102 char(')'),103 char('*'),104 char('+'),105 char(';'),106 char('!'),107 string('>>'),108 char('>'),109 char('@')110);111export const lex = sequence(112 optWhitespace,113 alternatives(114 sequence(slash, looseRegexPattern, slash, reFlags, optWhitespace).map(115 ([, body, , flags]) => new Token('regex', { body, flags })116 ),117 sequence(ident, optWhitespace).map(([value]) => new Token('ident', value)),118 sequence(hole, optWhitespace).map(119 ([value]) => new Token('hole', value[ContextWithHoles.hole])120 ),121 sequence(stringLiteral, optWhitespace).map(122 ([value]) => new Token('string', value)123 ),124 sequence(punctuator, optWhitespace).map(125 ([value]) => new Token('punctuator', value)126 )127 ).many()128).map(snd);129const isPunctuatorToken = value => isToken('punctuator', value);130const identToken = isToken('ident');131const stringToken = isToken('string');132const holeToken = isToken('hole');133const regexToken = isToken('regex');134const eqToken = isPunctuatorToken('=');135const pipeToken = isPunctuatorToken('|');136const starToken = isPunctuatorToken('*');137const plusToken = isPunctuatorToken('+');138const openParenToken = isPunctuatorToken('(');139const closeParenToken = isPunctuatorToken(')');140const semicolonToken = isPunctuatorToken(';');141const bangToken = isPunctuatorToken('!');142const rarrowToken = isPunctuatorToken('>');143const chainToken = isPunctuatorToken('>>');144const atToken = isPunctuatorToken('@');145function getState(f) {146 return new Parser(ctx => {147 if (typeof ctx[StateContext.state] !== 'function') {148 return new Failure('State does not exist on the context');149 }150 let state = ctx[StateContext.state]();151 return Outcome.of({152 value: succeed().chain(() => {153 return f(state);154 }),155 ctx,156 });157 });158}159const identDefinition = identToken.chain(({ value: name }) =>160 getState(state => state[name])161);162const stringLiteralDefinition = stringToken.map(({ value }) => string(value));163const satisfiesDefinition = bangToken164 .then(holeToken)165 .map(({ value: satFunc }) => satisfy(satFunc));166const parserHoleDefinition = atToken167 .then(holeToken)168 .map(({ value: parser }) => parser);169const regexDefinition = regexToken.map(({ value: { body, flags } }) =>170 regex(new RegExp(body, flags))171);172const primDefinition = lazy(() =>173 alternatives(174 stringLiteralDefinition,175 identDefinition,176 regexDefinition,177 satisfiesDefinition,178 parserHoleDefinition,179 sequence(openParenToken, definition, closeParenToken).map(snd)180 )181);182const baseDefinition = alternatives(183 sequence(primDefinition, starToken).map(([p]) => p.many()),184 sequence(primDefinition, plusToken).map(([p]) => p.atLeast(1)),185 primDefinition186);187const isMapToken = t => t != null && t.type === 'punctuator' && t.value === '>';188const mapDefinition = sequence(189 alternatives(190 baseDefinition.atLeast(2).map(defs => sequence(...defs)),191 baseDefinition192 ),193 sequence(alternatives(rarrowToken, chainToken), holeToken).many()194).map(([base, maps]) => maps.reduce((acc, [t, { value: f }]) => isMapToken(t) ? acc.map(f) : acc.chain(f), base));195const sequenceDefinition = mapDefinition196 .many()197 .map(rest => (rest.length === 1 ? rest[0] : sequence(...rest)));198const alternativeDefinition = sequence(199 sequenceDefinition,200 sequence(pipeToken, sequenceDefinition).many()201).map(([first, rest]) =>202 alternatives(...[first].concat(rest.map(([, p]) => p)))203);204const definition = alternativeDefinition;205const rule = sequence(identToken, eqToken, definition, semicolonToken).map(206 ([name, , definition]) => new Rule(name.value, definition)207);208const rules = rule.many();209export default function lang({ raw: strings }, ...args) {210 let lexemes = lex.tryParse(new ContextWithHoles(strings, args));211 let state = {};212 let parseValue = rules.tryParse(StateContext.from(lexemes, state));213 parseValue.forEach(({ name, definition }) => {214 state[name] = definition;215 });216 return state;...
newLineRule.js
Source:newLineRule.js
1function Rule()2{3 Lint.Rules.AbstractRule.apply(this, arguments);4}5Rule.prototype = Object.create(Lint.Rules.AbstractRule.prototype);6Rule.prototype.apply = function(syntaxTree)7{8 return this.applyWithWalker(new NewLineWalker(syntaxTree, this.getOptions()));9};10Rule.FAILURE_STRING = 'Missing newline before {';11function NewLineWalker()12{13 Lint.RuleWalker.apply(this, arguments);14}15NewLineWalker.prototype = Object.create(Lint.StateAwareRuleWalker.prototype);16NewLineWalker.prototype.visitClassDeclaration = function(node)17{18 var token = null;19 if (node.heritageClauses && node.heritageClauses.length > 0)20 token = TypeScript.lastToken(node.heritageClauses[node.heritageClauses.length - 1]);21 else if (node.typeParameterList)22 token = TypeScript.lastToken(node.typeParameterList);23 else24 token = node.identifier;25 if (token)26 this.checkNewLine(token, node);27 Lint.StateAwareRuleWalker.prototype.visitClassDeclaration.call(this, node);28};29NewLineWalker.prototype.visitInterfaceDeclaration = function(node)30{31 var token = null;32 if (node.heritageClauses && node.heritageClauses.length > 0)33 token = TypeScript.lastToken(node.heritageClauses[node.heritageClauses.length - 1]);34 else if (node.typeParameterList)35 token = TypeScript.lastToken(node.typeParameterList);36 else37 token = node.identifier;38 if (token)39 this.checkNewLine(token, node);40 41 Lint.StateAwareRuleWalker.prototype.visitInterfaceDeclaration.call(this, node);42};43NewLineWalker.prototype.visitEnumDeclaration = function(node)44{45 this.checkNewLine(node.identifier, node);46 Lint.StateAwareRuleWalker.prototype.visitEnumDeclaration.call(this, node);47};48/**49 * function ...(...) { ... }50 */51NewLineWalker.prototype.visitFunctionDeclaration = function(node)52{53 this.checkNewLine(TypeScript.lastToken(node.callSignature), node);54 Lint.StateAwareRuleWalker.prototype.visitFunctionDeclaration.call(this, node);55};56/**57 * "... = function(...) { ... }"58 */59NewLineWalker.prototype.visitFunctionExpression = function(node)60{61 this.checkNewLine(TypeScript.lastToken(node.callSignature), node);62 Lint.StateAwareRuleWalker.prototype.visitFunctionExpression.call(this, node);63};64NewLineWalker.prototype.visitMemberFunctionDeclaration = function(node)65{66 if (node.block)67 this.checkNewLine(TypeScript.lastToken(node.callSignature), node);68 Lint.StateAwareRuleWalker.prototype.visitMemberFunctionDeclaration.call(this, node);69};70NewLineWalker.prototype.visitConstructorDeclaration = function(node)71{72 if (node.block)73 this.checkNewLine(TypeScript.lastToken(node.callSignature), node);74 Lint.StateAwareRuleWalker.prototype.visitConstructorDeclaration.call(this, node);75};76NewLineWalker.prototype.visitGetAccessor = function(node)77{78 this.checkNewLine(TypeScript.lastToken(node.callSignature), node);79 Lint.StateAwareRuleWalker.prototype.visitGetAccessor.call(this, node);80};81NewLineWalker.prototype.visitSetAccessor = function(node)82{83 this.checkNewLine(TypeScript.lastToken(node.callSignature), node);84 Lint.StateAwareRuleWalker.prototype.visitSetAccessor.call(this, node);85};86NewLineWalker.prototype.visitIfStatement = function(node)87{88 this.checkNewLine(node.closeParenToken, node);89 Lint.StateAwareRuleWalker.prototype.visitIfStatement.call(this, node);90};91NewLineWalker.prototype.visitElseClause = function(node)92{93 if (node.statement.kind() === TypeScript.SyntaxKind.IfStatement)94 {95 if (node.elseKeyword.trailingTrivia().count() !== 1)96 this.addFailure(this.createFailure(this.getPosition() + TypeScript.leadingTriviaWidth(node), 1, '"else" must be followed by exactly one space'));97 }98 else99 this.checkNewLine(node.elseKeyword, node);100 Lint.StateAwareRuleWalker.prototype.visitElseClause.call(this, node);101};102NewLineWalker.prototype.visitForStatement = function(node)103{104 this.checkNewLine(node.closeParenToken, node);105 Lint.StateAwareRuleWalker.prototype.visitForStatement.call(this, node);106};107NewLineWalker.prototype.visitForInStatement = function(node)108{109 this.checkNewLine(node.closeParenToken, node);110 Lint.StateAwareRuleWalker.prototype.visitForInStatement.call(this, node);111};112NewLineWalker.prototype.visitWhileStatement = function(node)113{114 this.checkNewLine(node.closeParenToken, node);115 Lint.StateAwareRuleWalker.prototype.visitWhileStatement.call(this, node);116};117NewLineWalker.prototype.visitDoStatement = function(node)118{119 this.checkNewLine(node.closeParenToken, node);120 Lint.StateAwareRuleWalker.prototype.visitDoStatement.call(this, node);121};122NewLineWalker.prototype.visitTryStatement = function(node)123{124 this.checkNewLine(node.tryKeyword, node);125 Lint.StateAwareRuleWalker.prototype.visitTryStatement.call(this, node);126};127NewLineWalker.prototype.visitCatchClause = function(node)128{129 this.checkNewLine(node.closeParenToken, node);130 Lint.StateAwareRuleWalker.prototype.visitCatchClause.call(this, node);131};132NewLineWalker.prototype.visitFinallyClause = function(node)133{134 this.checkNewLine(node.finallyKeyword, node);135 Lint.StateAwareRuleWalker.prototype.visitFinallyClause.call(this, node);136};137NewLineWalker.prototype.checkNewLine = function(token, node)138{139 if (!token.trailingTrivia().hasNewLine())140 this.addFailure(this.createFailure(this.getPosition() + TypeScript.leadingTriviaWidth(node), 1, Rule.FAILURE_STRING));141};...
lexer.js
Source:lexer.js
1/**2 * Token ç±»åæ举3 */4 const SyntaxKind = {5 Unknown: 'Unknown',6 EndOfFileToken: 'EndOfFileToken',7 ConstKeyword: 'ConstKeyword',8 LetKeyword: 'LetKeyword',9 Identifier: 'Identifier',10 ColonToken: 'ColonToken',11 StringLiteral: 'StringLiteral',12 NumericLiteral: 'NumericLiteral',13 SemicolonToken: 'SemicolonToken',14 EqualsToken: 'EqualsToken',15 DotToken: 'DotToken',16 OpenParenToken: 'OpenParenToken',17 CloseParenToken: 'CloseParenToken'18}19/**20 * å
³é®åæ å°21 */22const textToKeyword = {23 const: SyntaxKind.ConstKeyword,24 let: SyntaxKind.LetKeyword,25}26class Lexer {27 constructor(text) {28 // æºä»£ç 29 this.text = text30 // æéä½ç½®31 this.pos = 032 // å½å符å·ç±»å33 this.token = SyntaxKind.Unknown34 // å½å符å·å¼35 this.tokenValue = null36 }37 scan() {38 // while 循ç¯è¡¨ç¤ºæéä¸æåä¸è¯»åçè¿ç¨39 while (true) {40 // åææ¬å
¨é¨è¯»åå®æ¯æ¶ï¼è¾åºãç»æ符å·ã41 if (this.pos >= this.text.length) {42 return this.token = SyntaxKind.EndOfFileToken43 }44 const ch = this.text[this.pos]45 switch (ch) {46 case ' ':47 case '\n':48 this.pos++49 continue50 case ':':51 this.pos++52 this.tokenValue = ':'53 return this.token = SyntaxKind.ColonToken54 case '':55 this.pos++56 this.tokenValue = ''57 return this.token = SyntaxKind.SemicolonToken58 case '=':59 this.pos++60 this.tokenValue = '='61 return this.token = SyntaxKind.EqualsToken62 case '"':63 case '\'':64 this.tokenValue = this.scanString()65 return this.token = SyntaxKind.StringLiteral66 case '1':67 case '2':68 case '3':69 case '4':70 case '5':71 case '6':72 case '7':73 case '8':74 case '9':75 this.tokenValue = this.scanNumericLiteral()76 return this.token = SyntaxKind.NumericLiteral77 default:78 return this.token = this.scanIdentifier(ch)79 }80 }81 }82 scanNumericLiteral() {83 const start = this.pos84 while (0 <= this.text[this.pos] && this.text[this.pos] <= 9) {85 this.pos++86 }87 return this.tokenValue = Number(this.text.substring(start, this.pos))88 }89 scanString() {90 const quote = this.text[this.pos]91 this.pos++92 const start = this.pos93 while (this.text[this.pos] !== quote) {94 this.pos++95 }96 this.tokenValue = this.text.substring(start, this.pos)97 this.pos++98 return this.tokenValue99 }100 scanIdentifier() {101 const start = this.pos102 while (true) {103 const ch = this.text[this.pos]104 if (!(('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ch === '_')) {105 break106 }107 this.pos++108 }109 this.tokenValue = this.text.substring(start, this.pos)110 if (!this.tokenValue) {111 throw new Error('Lexer error')112 }113 // å½åçæ è¯ç¬¦æ¯å¦æ¯å
³é®å114 const keyword = textToKeyword[this.tokenValue]115 if (keyword) {116 return keyword117 }118 return this.token = SyntaxKind.Identifier119 }120 getToken() {121 return this.token122 }123 getTokenValue() {124 return this.tokenValue125 }126}127exports.SyntaxKind = SyntaxKind...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.type('input[aria-label="Search"]', 'Playwright', {delay: 100});7 await page.keyboard.press('Enter
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('input[aria-label="Search"]');7 await page.keyboard.type('Playwright');8 await page.keyboard.press('Enter');9 await page.waitForTimeout(3000);
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.keyboard.press('Enter');7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.keyboard.press('Enter');15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.keyboard.press('Enter');23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.keyboard.press('Enter');31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.keyboard.press('Enter');39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch();44 const context = await browser.newContext();45 const page = await context.newPage();46 await page.keyboard.press('Enter');47 await browser.close();48})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const page = await browser.newPage();5 await page.waitForTimeout(5000);6 await page.keyboard.press('Escape');7 await page.waitForTimeout(5000);8 await browser.close();9})();
Using AI Code Generation
1const {test} = require('@playwright/test');2test('test', async ({page}) => {3 await page.click('text=Get started');4 await page.click('text=API');5 await page.click('text=Page');6 await page.click('text=Page.close');
Using AI Code Generation
1const {CloseParenToken} = require('playwright/lib/protocol/channels');2const {CloseParenToken} = require('playwright/lib/protocol/channels');3const {CloseParenToken} = require('playwright/lib/protocol/channels');4const {CloseParenToken} = require('playwright/lib/protocol/channels');5const {CloseParenToken} = require('playwright/lib/protocol/channels');6const {CloseParenToken} = require('playwright/lib/protocol/channels');7const {CloseParenToken} = require('playwright/lib/protocol/channels');8const {CloseParenToken} = require('playwright/lib/protocol/channels');9const {CloseParenToken} = require('playwright/lib/protocol/channels');10const {CloseParenToken} = require('playwright/lib/protocol/channels');11const {CloseParenToken} = require('playwright/lib/protocol/channels');12const {CloseParenToken} = require('playwright/lib/protocol/channels');13const {CloseParenToken} = require('playwright/lib/protocol/channels');14const {CloseParenToken} = require('playwright/lib/protocol/channels');15const {CloseParenToken} = require('playwright/lib/protocol/channels');16const {CloseParenToken} = require('playwright/lib/protocol/channels');17const {CloseParenToken} = require('playwright/lib/protocol/channels');18const {CloseParenToken} = require('playwright/lib/protocol/channels');19const {CloseParenToken} = require('playwright/lib/protocol/channels');20const {CloseParenToken} = require('playwright/lib/protocol/channels');21const {CloseParenToken} = require('playwright/lib/protocol/channels');
Using AI Code Generation
1const { CloseParenToken } = require('playwright/lib/server/supplements/recorder/recorderSupplement');2const closeParenToken = new CloseParenToken();3console.log(closeParenToken);4const { CloseParenToken } = require('playwright/lib/server/supplements/recorder/recorderSupplement');5const closeParenToken = new CloseParenToken();6console.log(closeParenToken);7const { CloseParenToken } = require('playwright/lib/server/supplements/recorder/recorderSupplement');8const closeParenToken = new CloseParenToken();9console.log(closeParenToken);10const { CloseParenToken } = require('playwright/lib/server/supplements/recorder/recorderSupplement');11const closeParenToken = new CloseParenToken();12console.log(closeParenToken);13const { CloseParenToken } = require('playwright/lib/server/supplements/recorder/recorderSupplement');14const closeParenToken = new CloseParenToken();15console.log(closeParenToken);16const { CloseParenToken } = require('playwright/lib/server/supplements/recorder/recorderSupplement');17const closeParenToken = new CloseParenToken();18console.log(closeParenToken);19const { CloseParenToken } = require('playwright/lib/server/supplements/recorder/recorderSupplement');20const closeParenToken = new CloseParenToken();21console.log(closeParenToken);
Using AI Code Generation
1const { CloseParenToken } = require('playwright/lib/server/frames');2const closeParenToken = new CloseParenToken();3const closeParenTokenValue = closeParenToken.value;4const { OpenParenToken } = require('playwright/lib/server/frames');5const openParenToken = new OpenParenToken();6const openParenTokenValue = openParenToken.value;7const { CloseBracketToken } = require('playwright/lib/server/frames');8const closeBracketToken = new CloseBracketToken();9const closeBracketTokenValue = closeBracketToken.value;10const { OpenBracketToken } = require('playwright/lib/server/frames');11const openBracketToken = new OpenBracketToken();12const openBracketTokenValue = openBracketToken.value;13const { CommaToken } = require('playwright/lib/server/frames');14const commaToken = new CommaToken();15const commaTokenValue = commaToken.value;16const { SemicolonToken } = require('playwright/lib/server/frames');17const semicolonToken = new SemicolonToken();18const semicolonTokenValue = semicolonToken.value;19const { ColonToken } = require('playwright/lib/server/frames');20const colonToken = new ColonToken();21const colonTokenValue = colonToken.value;22const { QuestionToken } = require('playwright/lib/server/frames');23const questionToken = new QuestionToken();24const questionTokenValue = questionToken.value;25const { TildeToken } = require('playwright/lib/server/frames');26const tildeToken = new TildeToken();27const tildeTokenValue = tildeToken.value;28const { EqualToken } = require('playwright/lib/server/frames');29const equalToken = new EqualToken();30const equalTokenValue = equalToken.value;31const { Pipe
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.
Get 100 minutes of automation test minutes FREE!!