How to use sourceCode method in ladle

Best JavaScript code snippet using ladle

ts.ts

Source:ts.ts Github

copy

Full Screen

1import type { TSESTree } from "@typescript-eslint/types"2import type * as ESTree from "estree"3import {4 isClosingBracketToken,5 isClosingParenToken,6 isNotClosingParenToken,7 isNotOpeningBraceToken,8 isOpeningBraceToken,9 isOpeningBracketToken,10 isOpeningParenToken,11 isSemicolonToken,12} from "eslint-utils"13import type { AnyToken, IndentContext } from "./commons"14import { isBeginningOfLine } from "./commons"15import { getFirstAndLastTokens } from "./commons"16import type { TSNodeListener } from "../../types-for-node"17type NodeListener = TSNodeListener18/**19 * Creates AST event handlers for svelte nodes.20 *21 * @param context The rule context.22 * @returns AST event handlers.23 */24export function defineVisitor(context: IndentContext): NodeListener {25 const { offsets, sourceCode } = context26 const visitor = {27 TSTypeAnnotation(node: TSESTree.TSTypeAnnotation) {28 // : Type29 // => Type30 const [colonOrArrowToken, secondToken] = sourceCode.getFirstTokens(node, {31 count: 2,32 includeComments: false,33 })34 const baseToken = sourceCode.getFirstToken(node.parent!)35 offsets.setOffsetToken([colonOrArrowToken, secondToken], 1, baseToken)36 const before = sourceCode.getTokenBefore(colonOrArrowToken)37 if (before && before.value === "?") {38 offsets.setOffsetToken(before, 1, baseToken)39 }40 },41 TSAsExpression(node: TSESTree.TSAsExpression) {42 // foo as T43 const expressionTokens = getFirstAndLastTokens(44 sourceCode,45 node.expression as ESTree.Expression,46 )47 const asToken = sourceCode.getTokenAfter(expressionTokens.lastToken)!48 offsets.setOffsetToken(49 [50 asToken,51 getFirstAndLastTokens(sourceCode, node.typeAnnotation).firstToken,52 ],53 1,54 expressionTokens.firstToken,55 )56 },57 TSTypeReference(node: TSESTree.TSTypeReference) {58 // T<U>59 if (node.typeParameters) {60 const typeNameTokens = getFirstAndLastTokens(sourceCode, node.typeName)61 offsets.setOffsetToken(62 sourceCode.getFirstToken(node.typeParameters),63 1,64 typeNameTokens.firstToken,65 )66 }67 },68 TSTypeParameterInstantiation(69 node:70 | TSESTree.TSTypeParameterInstantiation71 | TSESTree.TSTypeParameterDeclaration,72 ) {73 // <T>74 offsets.setOffsetElementList(75 node.params,76 sourceCode.getFirstToken(node),77 sourceCode.getLastToken(node),78 1,79 )80 },81 TSTypeParameterDeclaration(node: TSESTree.TSTypeParameterDeclaration) {82 // <T>83 visitor.TSTypeParameterInstantiation(node)84 },85 TSTypeAliasDeclaration(node: TSESTree.TSTypeAliasDeclaration) {86 // type T = {}87 const typeToken = sourceCode.getFirstToken(node)88 const idToken = sourceCode.getFirstToken(node.id)89 offsets.setOffsetToken(idToken, 1, typeToken)90 let eqToken91 if (node.typeParameters) {92 offsets.setOffsetToken(93 sourceCode.getFirstToken(node.typeParameters),94 1,95 idToken,96 )97 eqToken = sourceCode.getTokenAfter(node.typeParameters)!98 } else {99 eqToken = sourceCode.getTokenAfter(node.id)!100 }101 const initToken = sourceCode.getTokenAfter(eqToken)102 offsets.setOffsetToken([eqToken, initToken], 1, idToken)103 },104 TSFunctionType(node: TSESTree.TSFunctionType | TSESTree.TSConstructorType) {105 // ()=>void106 const firstToken = sourceCode.getFirstToken(node)107 // new or < or (108 let currToken = firstToken109 if (node.type === "TSConstructorType") {110 // currToken is new token111 // < or (112 currToken = sourceCode.getTokenAfter(currToken)!113 offsets.setOffsetToken(currToken, 1, firstToken)114 }115 if (node.typeParameters) {116 // currToken is < token117 // (118 currToken = sourceCode.getTokenAfter(node.typeParameters)!119 offsets.setOffsetToken(currToken, 1, firstToken)120 }121 const leftParenToken = currToken122 const rightParenToken = sourceCode.getTokenAfter(123 node.params[node.params.length - 1] || leftParenToken,124 { filter: isClosingParenToken, includeComments: false },125 )!126 offsets.setOffsetElementList(127 node.params,128 leftParenToken,129 rightParenToken,130 1,131 )132 const arrowToken = sourceCode.getTokenAfter(rightParenToken)133 offsets.setOffsetToken(arrowToken, 1, leftParenToken)134 },135 TSConstructorType(node: TSESTree.TSConstructorType) {136 // new ()=>void137 visitor.TSFunctionType(node)138 },139 TSTypeLiteral(node: TSESTree.TSTypeLiteral) {140 // {foo:any}141 offsets.setOffsetElementList(142 node.members,143 sourceCode.getFirstToken(node),144 sourceCode.getLastToken(node),145 1,146 )147 },148 TSPropertySignature(node: TSESTree.TSPropertySignature) {149 // { target:any }150 // ^^^^^^^^^^151 const firstToken = sourceCode.getFirstToken(node)152 const keyTokens = getFirstAndLastTokens(sourceCode, node.key)153 let keyLast154 if (node.computed) {155 const closeBracket = sourceCode.getTokenAfter(keyTokens.lastToken)!156 offsets.setOffsetElementList([node.key], firstToken, closeBracket, 1)157 keyLast = closeBracket158 } else {159 keyLast = keyTokens.lastToken160 }161 if (node.typeAnnotation) {162 const typeAnnotationToken = sourceCode.getFirstToken(163 node.typeAnnotation,164 )165 offsets.setOffsetToken(166 [167 ...sourceCode.getTokensBetween(keyLast, typeAnnotationToken),168 typeAnnotationToken,169 ],170 1,171 firstToken,172 )173 } else if (node.optional) {174 const qToken = sourceCode.getLastToken(node)175 offsets.setOffsetToken(qToken, 1, firstToken)176 }177 },178 TSIndexSignature(node: TSESTree.TSIndexSignature) {179 // { [k: string ]: string[] };180 // ^^^^^^^^^^^^^^^^^^^^^^181 const leftBracketToken = sourceCode.getFirstToken(node)182 const rightBracketToken = sourceCode.getTokenAfter(183 node.parameters[node.parameters.length - 1] || leftBracketToken,184 { filter: isClosingBracketToken, includeComments: false },185 )!186 offsets.setOffsetElementList(187 node.parameters,188 leftBracketToken,189 rightBracketToken,190 1,191 )192 const keyLast = rightBracketToken193 if (node.typeAnnotation) {194 const typeAnnotationToken = sourceCode.getFirstToken(195 node.typeAnnotation,196 )197 offsets.setOffsetToken(198 [199 ...sourceCode.getTokensBetween(keyLast, typeAnnotationToken),200 typeAnnotationToken,201 ],202 1,203 leftBracketToken,204 )205 }206 },207 TSArrayType(node: TSESTree.TSArrayType) {208 // T[]209 const firstToken = sourceCode.getFirstToken(node)210 offsets.setOffsetToken(211 sourceCode.getLastTokens(node, { count: 2, includeComments: false }),212 0,213 firstToken,214 )215 },216 TSTupleType(node: TSESTree.TSTupleType) {217 // [T, U]218 offsets.setOffsetElementList(219 node.elementTypes,220 sourceCode.getFirstToken(node),221 sourceCode.getLastToken(node),222 1,223 )224 },225 TSQualifiedName(node: TSESTree.TSQualifiedName) {226 // A.B227 const objectToken = sourceCode.getFirstToken(node)228 const dotToken = sourceCode.getTokenBefore(node.right)!229 const propertyToken = sourceCode.getTokenAfter(dotToken)230 offsets.setOffsetToken([dotToken, propertyToken], 1, objectToken)231 },232 TSIndexedAccessType(node: TSESTree.TSIndexedAccessType) {233 // A[B]234 const objectToken = sourceCode.getFirstToken(node)235 const leftBracketToken = sourceCode.getTokenBefore(node.indexType, {236 filter: isOpeningBracketToken,237 includeComments: false,238 })!239 const rightBracketToken = sourceCode.getTokenAfter(node.indexType, {240 filter: isClosingBracketToken,241 includeComments: false,242 })243 offsets.setOffsetToken(leftBracketToken, 1, objectToken)244 offsets.setOffsetElementList(245 [node.indexType],246 leftBracketToken,247 rightBracketToken,248 1,249 )250 },251 TSUnionType(node: TSESTree.TSUnionType | TSESTree.TSIntersectionType) {252 // A | B253 const firstToken = sourceCode.getFirstToken(node)254 const types = [...node.types]255 if (256 getFirstAndLastTokens(sourceCode, types[0]).firstToken === firstToken257 ) {258 types.shift()259 }260 offsets.setOffsetElementList(261 types,262 firstToken,263 null,264 isBeginningOfLine(sourceCode, firstToken) ? 0 : 1,265 )266 },267 TSIntersectionType(node: TSESTree.TSIntersectionType) {268 // A & B269 visitor.TSUnionType(node)270 },271 TSMappedType(node: TSESTree.TSMappedType) {272 // {[key in foo]: bar}273 const leftBraceToken = sourceCode.getFirstToken(node)274 const leftBracketToken = sourceCode.getTokenBefore(node.typeParameter)!275 const rightBracketToken = sourceCode.getTokenAfter(276 node.nameType || node.typeParameter,277 )!278 offsets.setOffsetToken(279 [280 ...sourceCode.getTokensBetween(leftBraceToken, leftBracketToken),281 leftBracketToken,282 ],283 1,284 leftBraceToken,285 )286 offsets.setOffsetElementList(287 [node.typeParameter, node.nameType],288 leftBracketToken,289 rightBracketToken,290 1,291 )292 const rightBraceToken = sourceCode.getLastToken(node)293 if (node.typeAnnotation) {294 const typeAnnotationToken = sourceCode.getFirstToken(295 node.typeAnnotation,296 )297 offsets.setOffsetToken(298 [299 ...sourceCode.getTokensBetween(300 rightBracketToken,301 typeAnnotationToken,302 ),303 typeAnnotationToken,304 ],305 1,306 leftBraceToken,307 )308 } else {309 offsets.setOffsetToken(310 [...sourceCode.getTokensBetween(rightBracketToken, rightBraceToken)],311 1,312 leftBraceToken,313 )314 }315 offsets.setOffsetToken(rightBraceToken, 0, leftBraceToken)316 },317 TSTypeParameter(node: TSESTree.TSTypeParameter) {318 // {[key in foo]: bar}319 // ^^^^^^^^^^320 // type T<U extends V = W>321 // ^^^^^^^^^^^^^^^322 const [firstToken, ...afterTokens] = sourceCode.getTokens(node)323 for (const child of [node.constraint, node.default]) {324 if (!child) {325 continue326 }327 const [, ...removeTokens] = sourceCode.getTokens(child)328 for (const token of removeTokens) {329 const i = afterTokens.indexOf(token)330 if (i >= 0) {331 afterTokens.splice(i, 1)332 }333 }334 }335 const secondToken = afterTokens.shift()336 if (!secondToken) {337 return338 }339 offsets.setOffsetToken(secondToken, 1, firstToken)340 if (secondToken.value === "extends") {341 let prevToken: AnyToken | null = null342 let token = afterTokens.shift()343 while (token) {344 if (token.value === "=") {345 break346 }347 offsets.setOffsetToken(token, 1, secondToken)348 prevToken = token349 token = afterTokens.shift()350 }351 while (token) {352 offsets.setOffsetToken(token, 1, prevToken || secondToken)353 token = afterTokens.shift()354 }355 } else {356 offsets.setOffsetToken(afterTokens, 1, firstToken)357 }358 },359 TSConditionalType(node: TSESTree.TSConditionalType) {360 // T extends Foo ? T : U361 const checkTypeToken = sourceCode.getFirstToken(node)362 const extendsToken = sourceCode.getTokenAfter(node.checkType)!363 const extendsTypeToken = sourceCode.getFirstToken(node.extendsType)364 offsets.setOffsetToken(extendsToken, 1, checkTypeToken)365 offsets.setOffsetToken(extendsTypeToken, 1, extendsToken)366 const questionToken = sourceCode.getTokenAfter(node.extendsType, {367 filter: isNotClosingParenToken,368 includeComments: false,369 })!370 const consequentToken = sourceCode.getTokenAfter(questionToken)371 const colonToken = sourceCode.getTokenAfter(node.trueType, {372 filter: isNotClosingParenToken,373 includeComments: false,374 })!375 const alternateToken = sourceCode.getTokenAfter(colonToken)376 let baseNode = node377 let parent = baseNode.parent378 while (379 parent &&380 parent.type === "TSConditionalType" &&381 parent.falseType === baseNode382 ) {383 baseNode = parent384 parent = baseNode.parent385 }386 const baseToken = sourceCode.getFirstToken(baseNode)387 offsets.setOffsetToken([questionToken, colonToken], 1, baseToken)388 offsets.setOffsetToken(consequentToken, 1, questionToken)389 offsets.setOffsetToken(alternateToken, 1, colonToken)390 },391 TSInterfaceDeclaration(node: TSESTree.TSInterfaceDeclaration) {392 // interface I {}393 const interfaceToken = sourceCode.getFirstToken(node)394 offsets.setOffsetToken(395 sourceCode.getFirstToken(node.id),396 1,397 interfaceToken,398 )399 if (node.typeParameters != null) {400 offsets.setOffsetToken(401 sourceCode.getFirstToken(node.typeParameters),402 1,403 sourceCode.getFirstToken(node.id),404 )405 }406 if (node.extends != null && node.extends.length) {407 const extendsToken = sourceCode.getTokenBefore(node.extends[0])!408 offsets.setOffsetToken(extendsToken, 1, interfaceToken)409 offsets.setOffsetElementList(node.extends, extendsToken, null, 1)410 }411 // It may not calculate the correct location because the visitor key is not provided.412 // if (node.implements != null && node.implements.length) {413 // const implementsToken = sourceCode.getTokenBefore(node.implements[0])!414 // offsets.setOffsetToken(implementsToken, 1, interfaceToken)415 // offsets.setOffsetElementList( node.implements, implementsToken, null, 1)416 // }417 const bodyToken = sourceCode.getFirstToken(node.body)418 offsets.setOffsetToken(bodyToken, 0, interfaceToken)419 },420 TSInterfaceBody(node: TSESTree.TSInterfaceBody | TSESTree.TSModuleBlock) {421 offsets.setOffsetElementList(422 node.body,423 sourceCode.getFirstToken(node),424 sourceCode.getLastToken(node),425 1,426 )427 },428 TSClassImplements(429 node: TSESTree.TSClassImplements | TSESTree.TSInterfaceHeritage,430 ) {431 // class C implements T {}432 // ^433 if (node.typeParameters) {434 offsets.setOffsetToken(435 sourceCode.getFirstToken(node.typeParameters),436 1,437 sourceCode.getFirstToken(node),438 )439 }440 },441 TSInterfaceHeritage(node: TSESTree.TSInterfaceHeritage) {442 // interface I extends E implements T {}443 // ^ ^444 visitor.TSClassImplements(node)445 },446 TSEnumDeclaration(node: TSESTree.TSEnumDeclaration) {447 // enum E {}448 const firstToken = sourceCode.getFirstToken(node)449 const idTokens = getFirstAndLastTokens(sourceCode, node.id)450 const prefixTokens = sourceCode.getTokensBetween(451 firstToken,452 idTokens.firstToken,453 )454 offsets.setOffsetToken(prefixTokens, 0, firstToken)455 offsets.setOffsetToken(idTokens.firstToken, 1, firstToken)456 const leftBraceToken = sourceCode.getTokenAfter(idTokens.lastToken)!457 const rightBraceToken = sourceCode.getLastToken(node)458 offsets.setOffsetToken(leftBraceToken, 0, firstToken)459 offsets.setOffsetElementList(460 node.members,461 leftBraceToken,462 rightBraceToken,463 1,464 )465 },466 TSModuleDeclaration(node: TSESTree.TSModuleDeclaration) {467 const firstToken = sourceCode.getFirstToken(node)468 const idTokens = getFirstAndLastTokens(sourceCode, node.id)469 const prefixTokens = sourceCode.getTokensBetween(470 firstToken,471 idTokens.firstToken,472 )473 offsets.setOffsetToken(prefixTokens, 0, firstToken)474 offsets.setOffsetToken(idTokens.firstToken, 1, firstToken)475 if (node.body) {476 const bodyFirstToken = sourceCode.getFirstToken(node.body)477 offsets.setOffsetToken(478 bodyFirstToken,479 isOpeningBraceToken(bodyFirstToken) ? 0 : 1,480 firstToken,481 )482 }483 },484 TSModuleBlock(node: TSESTree.TSModuleBlock) {485 visitor.TSInterfaceBody(node)486 },487 TSMethodSignature(node: TSESTree.TSMethodSignature) {488 // fn(arg: A): R | null;489 const firstToken = sourceCode.getFirstToken(node)490 const keyTokens = getFirstAndLastTokens(sourceCode, node.key)491 let keyLast492 if (node.computed) {493 const closeBracket = sourceCode.getTokenAfter(keyTokens.lastToken)!494 offsets.setOffsetElementList([node.key], firstToken, closeBracket, 1)495 keyLast = closeBracket496 } else {497 keyLast = keyTokens.lastToken498 }499 const leftParenToken = sourceCode.getTokenAfter(keyLast, {500 filter: isOpeningParenToken,501 includeComments: false,502 })!503 offsets.setOffsetToken(504 [505 ...sourceCode.getTokensBetween(keyLast, leftParenToken),506 leftParenToken,507 ],508 1,509 firstToken,510 )511 const rightParenToken = sourceCode.getTokenAfter(512 node.params[node.params.length - 1] || leftParenToken,513 { filter: isClosingParenToken, includeComments: false },514 )!515 offsets.setOffsetElementList(516 node.params,517 leftParenToken,518 rightParenToken,519 1,520 )521 if (node.returnType) {522 const typeAnnotationToken = sourceCode.getFirstToken(node.returnType)523 offsets.setOffsetToken(524 [525 ...sourceCode.getTokensBetween(keyLast, typeAnnotationToken),526 typeAnnotationToken,527 ],528 1,529 firstToken,530 )531 }532 },533 TSCallSignatureDeclaration(534 node:535 | TSESTree.TSCallSignatureDeclaration536 | TSESTree.TSConstructSignatureDeclaration,537 ) {538 // interface A { <T> (e: E): R }539 // ^^^^^^^^^^^^^540 const firstToken = sourceCode.getFirstToken(node)541 // new or < or (542 let currToken = firstToken543 if (node.type === "TSConstructSignatureDeclaration") {544 // currToken is new token545 // < or (546 currToken = sourceCode.getTokenAfter(currToken)!547 offsets.setOffsetToken(currToken, 1, firstToken)548 }549 if (node.typeParameters) {550 // currToken is < token551 // (552 currToken = sourceCode.getTokenAfter(node.typeParameters)!553 offsets.setOffsetToken(currToken, 1, firstToken)554 }555 const leftParenToken = currToken556 const rightParenToken = sourceCode.getTokenAfter(557 node.params[node.params.length - 1] || leftParenToken,558 { filter: isClosingParenToken, includeComments: false },559 )!560 offsets.setOffsetElementList(561 node.params,562 leftParenToken,563 rightParenToken,564 1,565 )566 if (node.returnType) {567 const typeAnnotationToken = sourceCode.getFirstToken(node.returnType)568 offsets.setOffsetToken(569 [570 ...sourceCode.getTokensBetween(571 rightParenToken,572 typeAnnotationToken,573 ),574 typeAnnotationToken,575 ],576 1,577 firstToken,578 )579 }580 },581 TSConstructSignatureDeclaration(582 node: TSESTree.TSConstructSignatureDeclaration,583 ) {584 // interface A { new <T> (e: E): R }585 // ^^^^^^^^^^^^^^^^^586 visitor.TSCallSignatureDeclaration(node)587 },588 TSEmptyBodyFunctionExpression(589 node: TSESTree.TSEmptyBodyFunctionExpression | TSESTree.TSDeclareFunction,590 ) {591 const firstToken = sourceCode.getFirstToken(node)592 let leftParenToken, bodyBaseToken593 if (firstToken.type === "Punctuator") {594 // method595 leftParenToken = firstToken596 bodyBaseToken = sourceCode.getFirstToken(node.parent!)597 } else {598 let nextToken = sourceCode.getTokenAfter(firstToken)599 let nextTokenOffset = 0600 while (601 nextToken &&602 !isOpeningParenToken(nextToken) &&603 nextToken.value !== "<"604 ) {605 if (606 nextToken.value === "*" ||607 (node.id && nextToken.range[0] === node.id.range[0])608 ) {609 nextTokenOffset = 1610 }611 offsets.setOffsetToken(nextToken, nextTokenOffset, firstToken)612 nextToken = sourceCode.getTokenAfter(nextToken)613 }614 leftParenToken = nextToken!615 bodyBaseToken = firstToken616 }617 if (!isOpeningParenToken(leftParenToken) && node.typeParameters) {618 leftParenToken = sourceCode.getTokenAfter(node.typeParameters)!619 }620 const rightParenToken = sourceCode.getTokenAfter(621 node.params[node.params.length - 1] || leftParenToken,622 { filter: isClosingParenToken, includeComments: false },623 )!624 offsets.setOffsetToken(leftParenToken, 1, bodyBaseToken)625 offsets.setOffsetElementList(626 node.params,627 leftParenToken,628 rightParenToken,629 1,630 )631 },632 TSDeclareFunction(node: TSESTree.TSDeclareFunction) {633 // function fn(): void;634 visitor.TSEmptyBodyFunctionExpression(node)635 },636 TSTypeOperator(637 node:638 | TSESTree.TSTypeOperator639 | TSESTree.TSTypeQuery640 | TSESTree.TSInferType,641 ) {642 // keyof T643 const firstToken = sourceCode.getFirstToken(node)644 const nextToken = sourceCode.getTokenAfter(firstToken)645 offsets.setOffsetToken(nextToken, 1, firstToken)646 },647 TSTypeQuery(node: TSESTree.TSTypeQuery) {648 // type T = typeof a649 visitor.TSTypeOperator(node)650 },651 TSInferType(node: TSESTree.TSInferType) {652 // infer U653 visitor.TSTypeOperator(node)654 },655 TSTypePredicate(node: TSESTree.TSTypePredicate) {656 // v is T657 const firstToken = sourceCode.getFirstToken(node)658 const opToken = sourceCode.getTokenAfter(node.parameterName, {659 filter: isNotClosingParenToken,660 includeComments: false,661 })!662 const rightToken =663 node.typeAnnotation &&664 getFirstAndLastTokens(sourceCode, node.typeAnnotation).firstToken665 offsets.setOffsetToken(666 [opToken, rightToken],667 1,668 getFirstAndLastTokens(sourceCode, firstToken).firstToken,669 )670 },671 TSAbstractMethodDefinition(672 node:673 | TSESTree.TSAbstractMethodDefinition674 | TSESTree.TSAbstractPropertyDefinition675 | TSESTree.TSEnumMember,676 ) {677 const { keyNode, valueNode } =678 node.type === "TSEnumMember"679 ? { keyNode: node.id, valueNode: node.initializer }680 : { keyNode: node.key, valueNode: node.value }681 const firstToken = sourceCode.getFirstToken(node)682 const keyTokens = getFirstAndLastTokens(sourceCode, keyNode)683 const prefixTokens = sourceCode.getTokensBetween(684 firstToken,685 keyTokens.firstToken,686 )687 if (node.computed) {688 prefixTokens.pop() // pop [689 }690 offsets.setOffsetToken(prefixTokens, 0, firstToken)691 let lastKeyToken692 if (node.computed) {693 const leftBracketToken = sourceCode.getTokenBefore(694 keyTokens.firstToken,695 )!696 const rightBracketToken = (lastKeyToken = sourceCode.getTokenAfter(697 keyTokens.lastToken,698 )!)699 offsets.setOffsetToken(leftBracketToken, 0, firstToken)700 offsets.setOffsetElementList(701 [keyNode],702 leftBracketToken,703 rightBracketToken,704 1,705 )706 } else {707 offsets.setOffsetToken(keyTokens.firstToken, 0, firstToken)708 lastKeyToken = keyTokens.lastToken709 }710 if (valueNode != null) {711 const initToken = sourceCode.getFirstToken(valueNode)712 offsets.setOffsetToken(713 [...sourceCode.getTokensBetween(lastKeyToken, initToken), initToken],714 1,715 lastKeyToken,716 )717 }718 },719 TSAbstractPropertyDefinition(node: TSESTree.TSAbstractPropertyDefinition) {720 visitor.TSAbstractMethodDefinition(node)721 },722 TSEnumMember(node: TSESTree.TSEnumMember) {723 visitor.TSAbstractMethodDefinition(node)724 },725 TSOptionalType(726 node: TSESTree.TSOptionalType | TSESTree.TSNonNullExpression,727 ) {728 // [number?]729 // ^^^^^^^730 offsets.setOffsetToken(731 sourceCode.getLastToken(node),732 1,733 sourceCode.getFirstToken(node),734 )735 },736 TSNonNullExpression(node: TSESTree.TSNonNullExpression) {737 // v!738 visitor.TSOptionalType(node)739 },740 TSJSDocNonNullableType(741 // @ts-expect-error -- Missing TSJSDocNonNullableType type742 node: TSESTree.TSJSDocNonNullableType,743 ) {744 // T!745 visitor.TSOptionalType(node)746 },747 TSTypeAssertion(node: TSESTree.TSTypeAssertion) {748 // <const>749 const firstToken = sourceCode.getFirstToken(node)750 const expressionToken = getFirstAndLastTokens(751 sourceCode,752 node.expression,753 ).firstToken754 offsets.setOffsetElementList(755 [node.typeAnnotation],756 firstToken,757 sourceCode.getTokenBefore(expressionToken),758 1,759 )760 offsets.setOffsetToken(expressionToken, 1, firstToken)761 },762 TSImportType(node: TSESTree.TSImportType) {763 // import('foo').B764 const firstToken = sourceCode.getFirstToken(node)765 const leftParenToken = sourceCode.getTokenAfter(firstToken, {766 filter: isOpeningParenToken,767 includeComments: false,768 })!769 offsets.setOffsetToken(leftParenToken, 1, firstToken)770 const rightParenToken = sourceCode.getTokenAfter(node.parameter, {771 filter: isClosingParenToken,772 includeComments: false,773 })!774 offsets.setOffsetElementList(775 [node.parameter],776 leftParenToken,777 rightParenToken,778 1,779 )780 if (node.qualifier) {781 const dotToken = sourceCode.getTokenBefore(node.qualifier)!782 const propertyToken = sourceCode.getTokenAfter(dotToken)783 offsets.setOffsetToken([dotToken, propertyToken], 1, firstToken)784 }785 if (node.typeParameters) {786 offsets.setOffsetToken(787 sourceCode.getFirstToken(node.typeParameters),788 1,789 firstToken,790 )791 }792 },793 TSParameterProperty(node: TSESTree.TSParameterProperty) {794 // constructor(private a)795 const firstToken = sourceCode.getFirstToken(node)796 const parameterToken = sourceCode.getFirstToken(node.parameter)797 offsets.setOffsetToken(798 [799 ...sourceCode.getTokensBetween(firstToken, parameterToken),800 parameterToken,801 ],802 1,803 firstToken,804 )805 },806 TSImportEqualsDeclaration(node: TSESTree.TSImportEqualsDeclaration) {807 // import foo = require('foo')808 const importToken = sourceCode.getFirstToken(node)809 const idTokens = getFirstAndLastTokens(sourceCode, node.id)810 offsets.setOffsetToken(idTokens.firstToken, 1, importToken)811 const opToken = sourceCode.getTokenAfter(idTokens.lastToken)812 offsets.setOffsetToken(813 [opToken, sourceCode.getFirstToken(node.moduleReference)],814 1,815 idTokens.lastToken,816 )817 },818 TSExternalModuleReference(node: TSESTree.TSExternalModuleReference) {819 // require('foo')820 const requireToken = sourceCode.getFirstToken(node)821 const leftParenToken = sourceCode.getTokenAfter(requireToken, {822 filter: isOpeningParenToken,823 includeComments: false,824 })!825 const rightParenToken = sourceCode.getLastToken(node)826 offsets.setOffsetToken(leftParenToken, 1, requireToken)827 offsets.setOffsetElementList(828 [node.expression],829 leftParenToken,830 rightParenToken,831 1,832 )833 },834 TSExportAssignment(node: TSESTree.TSExportAssignment) {835 // export = foo836 const exportNode = sourceCode.getFirstToken(node)837 const exprTokens = getFirstAndLastTokens(sourceCode, node.expression)838 const opToken = sourceCode.getTokenBefore(exprTokens.firstToken)839 offsets.setOffsetToken([opToken, exprTokens.firstToken], 1, exportNode)840 },841 TSNamedTupleMember(node: TSESTree.TSNamedTupleMember) {842 // [a: string, ...b: string[]]843 // ^^^^^^^^^844 const labelToken = sourceCode.getFirstToken(node)845 const elementTokens = getFirstAndLastTokens(sourceCode, node.elementType)846 offsets.setOffsetToken(847 [848 ...sourceCode.getTokensBetween(labelToken, elementTokens.firstToken),849 elementTokens.firstToken,850 ],851 1,852 labelToken,853 )854 },855 TSRestType(node: TSESTree.TSRestType) {856 // [a: string, ...b: string[]]857 // ^^^^^^^^^^^^^^858 const firstToken = sourceCode.getFirstToken(node)859 const nextToken = sourceCode.getTokenAfter(firstToken)860 offsets.setOffsetToken(nextToken, 1, firstToken)861 },862 TSNamespaceExportDeclaration(node: TSESTree.TSNamespaceExportDeclaration) {863 const firstToken = sourceCode.getFirstToken(node)864 const idToken = sourceCode.getFirstToken(node.id)865 offsets.setOffsetToken(866 [...sourceCode.getTokensBetween(firstToken, idToken), idToken],867 1,868 firstToken,869 )870 },871 TSTemplateLiteralType(node: TSESTree.TSTemplateLiteralType) {872 const firstToken = sourceCode.getFirstToken(node)873 const quasiTokens = node.quasis874 .slice(1)875 .map((n) => sourceCode.getFirstToken(n))876 const expressionToken = node.quasis877 .slice(0, -1)878 .map((n) => sourceCode.getTokenAfter(n))879 offsets.setOffsetToken(quasiTokens, 0, firstToken)880 offsets.setOffsetToken(expressionToken, 1, firstToken)881 },882 // ----------------------------------------------------------------------883 // NON-STANDARD NODES884 // ----------------------------------------------------------------------885 Decorator(node: TSESTree.Decorator) {886 // @Decorator887 const [atToken, secondToken] = sourceCode.getFirstTokens(node, {888 count: 2,889 includeComments: false,890 })891 offsets.setOffsetToken(secondToken, 0, atToken)892 const parent = node.parent!893 const { decorators } = parent as { decorators?: TSESTree.Decorator[] }894 if (!decorators || decorators.length === 0) {895 return896 }897 if (decorators[0] === node) {898 if (parent.range[0] === node.range[0]) {899 const startParentToken = sourceCode.getTokenAfter(900 decorators[decorators?.length - 1],901 )902 offsets.setOffsetToken(startParentToken, 0, atToken)903 } else {904 const startParentToken = sourceCode.getFirstToken(905 parent.parent &&906 (parent.parent.type === "ExportDefaultDeclaration" ||907 parent.parent.type === "ExportNamedDeclaration") &&908 node.range[0] < parent.parent.range[0]909 ? parent.parent910 : parent,911 )912 offsets.copyOffset(atToken.range[0], startParentToken.range[0])913 }914 } else {915 offsets.setOffsetToken(916 atToken,917 0,918 sourceCode.getFirstToken(decorators[0]),919 )920 }921 },922 StaticBlock(node: TSESTree.StaticBlock) {923 const firstToken = sourceCode.getFirstToken(node)924 let next = sourceCode.getTokenAfter(firstToken)925 while (next && isNotOpeningBraceToken(next)) {926 offsets.setOffsetToken(next, 0, firstToken)927 next = sourceCode.getTokenAfter(next)928 }929 offsets.setOffsetToken(next, 0, firstToken)930 offsets.setOffsetElementList(931 node.body,932 next!,933 sourceCode.getLastToken(node),934 1,935 )936 },937 ImportAttribute(node: TSESTree.ImportAttribute) {938 const firstToken = sourceCode.getFirstToken(node)939 const keyTokens = getFirstAndLastTokens(sourceCode, node.key)940 const prefixTokens = sourceCode.getTokensBetween(941 firstToken,942 keyTokens.firstToken,943 )944 offsets.setOffsetToken(prefixTokens, 0, firstToken)945 offsets.setOffsetToken(keyTokens.firstToken, 0, firstToken)946 const initToken = sourceCode.getFirstToken(node.value)947 offsets.setOffsetToken(948 [949 ...sourceCode.getTokensBetween(keyTokens.lastToken, initToken),950 initToken,951 ],952 1,953 keyTokens.lastToken,954 )955 },956 // ----------------------------------------------------------------------957 // SINGLE TOKEN NODES958 // ----------------------------------------------------------------------959 // VALUES KEYWORD960 TSAnyKeyword() {961 // noop962 },963 TSBigIntKeyword() {964 // noop965 },966 TSBooleanKeyword() {967 // noop968 },969 TSNeverKeyword() {970 // noop971 },972 TSNullKeyword() {973 // noop974 },975 TSNumberKeyword() {976 // noop977 },978 TSObjectKeyword() {979 // noop980 },981 TSStringKeyword() {982 // noop983 },984 TSSymbolKeyword() {985 // noop986 },987 TSUndefinedKeyword() {988 // noop989 },990 TSUnknownKeyword() {991 // noop992 },993 TSVoidKeyword() {994 // noop995 },996 // MODIFIERS KEYWORD997 TSAbstractKeyword() {998 // noop999 },1000 TSAsyncKeyword() {1001 // noop1002 },1003 TSPrivateKeyword() {1004 // noop1005 },1006 TSProtectedKeyword() {1007 // noop1008 },1009 TSPublicKeyword() {1010 // noop1011 },1012 TSReadonlyKeyword() {1013 // noop1014 },1015 TSStaticKeyword() {1016 // noop1017 },1018 // OTHERS KEYWORD1019 TSDeclareKeyword() {1020 // noop1021 },1022 TSExportKeyword() {1023 // noop1024 },1025 TSIntrinsicKeyword() {1026 // noop1027 },1028 // OTHERS1029 TSThisType() {1030 // noop1031 },1032 // ----------------------------------------------------------------------1033 // WRAPPER NODES1034 // ----------------------------------------------------------------------1035 TSLiteralType() {1036 // noop1037 },1038 }1039 // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore1040 const commonsVisitor: any = {1041 // Process semicolons.1042 ["TSTypeAliasDeclaration, TSCallSignatureDeclaration, TSConstructSignatureDeclaration, TSImportEqualsDeclaration," +1043 "TSAbstractMethodDefinition, TSAbstractPropertyDefinition, TSEnumMember," +1044 "TSPropertySignature, TSIndexSignature, TSMethodSignature," +1045 "TSAbstractClassProperty, ClassProperty"](node: ESTree.Node) {1046 const firstToken = sourceCode.getFirstToken(node)1047 const lastToken = sourceCode.getLastToken(node)1048 if (isSemicolonToken(lastToken) && firstToken !== lastToken) {1049 const next = sourceCode.getTokenAfter(lastToken)1050 if (!next || lastToken.loc.start.line < next.loc.start.line) {1051 // End of line semicolons1052 offsets.setOffsetToken(lastToken, 0, firstToken)1053 }1054 }1055 },1056 // eslint-disable-next-line complexity -- ignore1057 "*[type=/^TS/]"(node: TSESTree.Node) {1058 if (1059 node.type !== "TSAnyKeyword" &&1060 node.type !== "TSArrayType" &&1061 node.type !== "TSBigIntKeyword" &&1062 node.type !== "TSBooleanKeyword" &&1063 node.type !== "TSConditionalType" &&1064 node.type !== "TSConstructorType" &&1065 node.type !== "TSFunctionType" &&1066 node.type !== "TSImportType" &&1067 node.type !== "TSIndexedAccessType" &&1068 node.type !== "TSInferType" &&1069 node.type !== "TSIntersectionType" &&1070 node.type !== "TSIntrinsicKeyword" &&1071 node.type !== "TSLiteralType" &&1072 node.type !== "TSMappedType" &&1073 node.type !== "TSNamedTupleMember" &&1074 node.type !== "TSNeverKeyword" &&1075 node.type !== "TSNullKeyword" &&1076 node.type !== "TSNumberKeyword" &&1077 node.type !== "TSObjectKeyword" &&1078 node.type !== "TSOptionalType" &&1079 node.type !== "TSRestType" &&1080 node.type !== "TSStringKeyword" &&1081 node.type !== "TSSymbolKeyword" &&1082 node.type !== "TSTemplateLiteralType" &&1083 node.type !== "TSThisType" &&1084 node.type !== "TSTupleType" &&1085 node.type !== "TSTypeLiteral" &&1086 node.type !== "TSTypeOperator" &&1087 node.type !== "TSTypePredicate" &&1088 node.type !== "TSTypeQuery" &&1089 node.type !== "TSTypeReference" &&1090 node.type !== "TSUndefinedKeyword" &&1091 node.type !== "TSUnionType" &&1092 node.type !== "TSUnknownKeyword" &&1093 node.type !== "TSVoidKeyword"1094 ) {1095 return1096 }1097 const typeNode: TSESTree.TypeNode = node1098 // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore1099 if ((typeNode.parent as any).type === "TSParenthesizedType") {1100 return1101 }1102 // Process parentheses.1103 let leftToken = sourceCode.getTokenBefore(typeNode)1104 let rightToken = sourceCode.getTokenAfter(typeNode)1105 let firstToken = sourceCode.getFirstToken(typeNode)1106 while (1107 leftToken &&1108 isOpeningParenToken(leftToken) &&1109 rightToken &&1110 isClosingParenToken(rightToken)1111 ) {1112 offsets.setOffsetToken(firstToken, 1, leftToken)1113 offsets.setOffsetToken(rightToken, 0, leftToken)1114 firstToken = leftToken1115 leftToken = sourceCode.getTokenBefore(leftToken)1116 rightToken = sourceCode.getTokenAfter(rightToken)1117 }1118 },1119 }1120 // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore1121 const extendsESVisitor: any = {1122 ["ClassDeclaration[implements], ClassDeclaration[typeParameters], ClassDeclaration[superTypeParameters]," +1123 "ClassExpression[implements], ClassExpression[typeParameters], ClassExpression[superTypeParameters]"](1124 node: TSESTree.ClassDeclaration | TSESTree.ClassExpression,1125 ) {1126 if (node.typeParameters != null) {1127 offsets.setOffsetToken(1128 sourceCode.getFirstToken(node.typeParameters),1129 1,1130 sourceCode.getFirstToken(node.id || node),1131 )1132 }1133 if (node.superTypeParameters != null && node.superClass != null) {1134 offsets.setOffsetToken(1135 sourceCode.getFirstToken(node.superTypeParameters),1136 1,1137 sourceCode.getFirstToken(node.superClass),1138 )1139 }1140 if (node.implements != null && node.implements.length) {1141 const classToken = sourceCode.getFirstToken(node)1142 const implementsToken = sourceCode.getTokenBefore(node.implements[0])!1143 offsets.setOffsetToken(implementsToken, 1, classToken)1144 offsets.setOffsetElementList(node.implements, implementsToken, null, 1)1145 }1146 },1147 }1148 // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore1149 const deprecatedVisitor: any = {1150 // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore1151 TSParenthesizedType(node: any) {1152 // (T)1153 offsets.setOffsetElementList(1154 [node.typeAnnotation],1155 sourceCode.getFirstToken(node),1156 sourceCode.getLastToken(node),1157 1,1158 )1159 },1160 // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore1161 ClassProperty(node: any) {1162 visitor.TSAbstractMethodDefinition(node)1163 },1164 // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore1165 TSAbstractClassProperty(node: any) {1166 visitor.TSAbstractMethodDefinition(node)1167 },1168 }1169 const v: NodeListener = visitor1170 return {1171 ...v,1172 ...commonsVisitor,1173 ...extendsESVisitor,1174 ...deprecatedVisitor,1175 }...

Full Screen

Full Screen

eslint-tests.ts

Source:eslint-tests.ts Github

copy

Full Screen

1import { Comment } from 'estree';2import { AST, SourceCode, Rule, Linter, CLIEngine, RuleTester, Scope } from 'eslint';3const SOURCE = `var foo = bar;`;4const AST: AST.Program = {5 type: 'Program',6 sourceType: 'module',7 body: [],8 comments: [],9 tokens: [],10 loc: {11 start: { line: 0, column: 0 },12 end: { line: 0, column: 0 }13 },14 range: [0, 0],15};16const TOKEN: AST.Token = {17 type: 'Identifier',18 value: 'foo',19 loc: {20 start: { line: 0, column: 0 },21 end: { line: 0, column: 3 }22 },23 range: [0, 3]24};25const COMMENT: Comment = {26 type: 'Block',27 value: 'foo',28 loc: {29 start: { line: 0, column: 0 },30 end: { line: 0, column: 0 }31 },32 range: [0, 0],33};34//#region SourceCode35let sourceCode = new SourceCode(SOURCE, AST);36SourceCode.splitLines(SOURCE);37sourceCode.getText();38sourceCode.getText(AST);39sourceCode.getText(AST, 0);40sourceCode.getText(AST, 0, 0);41sourceCode.getLines();42sourceCode.getAllComments();43sourceCode.getComments(AST).leading;44sourceCode.getComments(AST).trailing;45sourceCode.getJSDocComment(AST);46sourceCode.getNodeByRangeIndex(0);47sourceCode.getNodeByRangeIndex(0);48sourceCode.isSpaceBetweenTokens(TOKEN, TOKEN);49const loc = sourceCode.getLocFromIndex(0);50loc.line; // $ExpectType number51loc.column; // $ExpectType number52sourceCode.getIndexFromLoc({ line: 0, column: 0 });53sourceCode.getTokenByRangeStart(0);54sourceCode.getTokenByRangeStart(0, { includeComments: true });55sourceCode.getFirstToken(AST);56sourceCode.getFirstToken(AST, 0);57sourceCode.getFirstToken(AST, { skip: 0 });58sourceCode.getFirstToken(AST, t => t.type === 'Identifier');59sourceCode.getFirstToken(AST, { filter: t => t.type === 'Identifier' });60sourceCode.getFirstToken(AST, { skip: 0, filter: t => t.type === 'Identifier' });61sourceCode.getFirstToken(AST, { includeComments: true });62sourceCode.getFirstToken(AST, { includeComments: true, skip: 0 });63sourceCode.getFirstToken(AST, { includeComments: true, skip: 0, filter: t => t.type === 'Identifier' });64sourceCode.getFirstTokens(AST);65sourceCode.getFirstTokens(AST, 0);66sourceCode.getFirstTokens(AST, { count: 0 });67sourceCode.getFirstTokens(AST, t => t.type === 'Identifier');68sourceCode.getFirstTokens(AST, { filter: t => t.type === 'Identifier' });69sourceCode.getFirstTokens(AST, { count: 0, filter: t => t.type === 'Identifier' });70sourceCode.getFirstTokens(AST, { includeComments: true });71sourceCode.getFirstTokens(AST, { includeComments: true, count: 0 });72sourceCode.getFirstTokens(AST, { includeComments: true, count: 0, filter: t => t.type === 'Identifier' });73sourceCode.getLastToken(AST);74sourceCode.getLastToken(AST, 0);75sourceCode.getLastToken(AST, { skip: 0 });76sourceCode.getLastToken(AST, t => t.type === 'Identifier');77sourceCode.getLastToken(AST, { filter: t => t.type === 'Identifier' });78sourceCode.getLastToken(AST, { skip: 0, filter: t => t.type === 'Identifier' });79sourceCode.getLastToken(AST, { includeComments: true });80sourceCode.getLastToken(AST, { includeComments: true, skip: 0 });81sourceCode.getLastToken(AST, { includeComments: true, skip: 0, filter: t => t.type === 'Identifier' });82sourceCode.getLastTokens(AST);83sourceCode.getLastTokens(AST, 0);84sourceCode.getLastTokens(AST, { count: 0 });85sourceCode.getLastTokens(AST, t => t.type === 'Identifier');86sourceCode.getLastTokens(AST, { filter: t => t.type === 'Identifier' });87sourceCode.getLastTokens(AST, { count: 0, filter: t => t.type === 'Identifier' });88sourceCode.getLastTokens(AST, { includeComments: true });89sourceCode.getLastTokens(AST, { includeComments: true, count: 0 });90sourceCode.getLastTokens(AST, { includeComments: true, count: 0, filter: t => t.type === 'Identifier' });91sourceCode.getTokenBefore(AST);92sourceCode.getTokenBefore(AST, 0);93sourceCode.getTokenBefore(AST, { skip: 0 });94sourceCode.getTokenBefore(AST, t => t.type === 'Identifier');95sourceCode.getTokenBefore(AST, { filter: t => t.type === 'Identifier' });96sourceCode.getTokenBefore(AST, { skip: 0, filter: t => t.type === 'Identifier' });97sourceCode.getTokenBefore(AST, { includeComments: true });98sourceCode.getTokenBefore(AST, { includeComments: true, skip: 0 });99sourceCode.getTokenBefore(AST, { includeComments: true, skip: 0, filter: t => t.type === 'Identifier' });100sourceCode.getTokenBefore(TOKEN, 0);101sourceCode.getTokenBefore(COMMENT, 0);102sourceCode.getTokensBefore(AST);103sourceCode.getTokensBefore(AST, 0);104sourceCode.getTokensBefore(AST, { count: 0 });105sourceCode.getTokensBefore(AST, t => t.type === 'Identifier');106sourceCode.getTokensBefore(AST, { filter: t => t.type === 'Identifier' });107sourceCode.getTokensBefore(AST, { count: 0, filter: t => t.type === 'Identifier' });108sourceCode.getTokensBefore(AST, { includeComments: true });109sourceCode.getTokensBefore(AST, { includeComments: true, count: 0 });110sourceCode.getTokensBefore(AST, { includeComments: true, count: 0, filter: t => t.type === 'Identifier' });111sourceCode.getTokensBefore(TOKEN, 0);112sourceCode.getTokensBefore(COMMENT, 0);113sourceCode.getTokenAfter(AST);114sourceCode.getTokenAfter(AST, 0);115sourceCode.getTokenAfter(AST, { skip: 0 });116sourceCode.getTokenAfter(AST, t => t.type === 'Identifier');117sourceCode.getTokenAfter(AST, { filter: t => t.type === 'Identifier' });118sourceCode.getTokenAfter(AST, { skip: 0, filter: t => t.type === 'Identifier' });119sourceCode.getTokenAfter(AST, { includeComments: true });120sourceCode.getTokenAfter(AST, { includeComments: true, skip: 0 });121sourceCode.getTokenAfter(AST, { includeComments: true, skip: 0, filter: t => t.type === 'Identifier' });122sourceCode.getTokenAfter(TOKEN, 0);123sourceCode.getTokenAfter(COMMENT, 0);124sourceCode.getTokensAfter(AST);125sourceCode.getTokensAfter(AST, 0);126sourceCode.getTokensAfter(AST, { count: 0 });127sourceCode.getTokensAfter(AST, t => t.type === 'Identifier');128sourceCode.getTokensAfter(AST, { filter: t => t.type === 'Identifier' });129sourceCode.getTokensAfter(AST, { count: 0, filter: t => t.type === 'Identifier' });130sourceCode.getTokensAfter(AST, { includeComments: true });131sourceCode.getTokensAfter(AST, { includeComments: true, count: 0 });132sourceCode.getTokensAfter(AST, { includeComments: true, count: 0, filter: t => t.type === 'Identifier' });133sourceCode.getTokensAfter(TOKEN, 0);134sourceCode.getTokensAfter(COMMENT, 0);135sourceCode.getFirstTokenBetween(AST, AST);136sourceCode.getFirstTokenBetween(AST, AST, 0);137sourceCode.getFirstTokenBetween(AST, AST, { skip: 0 });138sourceCode.getFirstTokenBetween(AST, AST, t => t.type === 'Identifier');139sourceCode.getFirstTokenBetween(AST, AST, { filter: t => t.type === 'Identifier' });140sourceCode.getFirstTokenBetween(AST, AST, { skip: 0, filter: t => t.type === 'Identifier' });141sourceCode.getFirstTokenBetween(AST, AST, { includeComments: true });142sourceCode.getFirstTokenBetween(AST, AST, { includeComments: true, skip: 0 });143sourceCode.getFirstTokenBetween(AST, AST, { includeComments: true, skip: 0, filter: t => t.type === 'Identifier' });144sourceCode.getFirstTokensBetween(AST, AST);145sourceCode.getFirstTokensBetween(AST, AST, 0);146sourceCode.getFirstTokensBetween(AST, AST, { count: 0 });147sourceCode.getFirstTokensBetween(AST, AST, t => t.type === 'Identifier');148sourceCode.getFirstTokensBetween(AST, AST, { filter: t => t.type === 'Identifier' });149sourceCode.getFirstTokensBetween(AST, AST, { count: 0, filter: t => t.type === 'Identifier' });150sourceCode.getFirstTokensBetween(AST, AST, { includeComments: true });151sourceCode.getFirstTokensBetween(AST, AST, { includeComments: true, count: 0 });152sourceCode.getFirstTokensBetween(AST, AST, { includeComments: true, count: 0, filter: t => t.type === 'Identifier' });153sourceCode.getLastTokenBetween(AST, AST);154sourceCode.getLastTokenBetween(AST, AST, 0);155sourceCode.getLastTokenBetween(AST, AST, { skip: 0 });156sourceCode.getLastTokenBetween(AST, AST, t => t.type === 'Identifier');157sourceCode.getLastTokenBetween(AST, AST, { filter: t => t.type === 'Identifier' });158sourceCode.getLastTokenBetween(AST, AST, { skip: 0, filter: t => t.type === 'Identifier' });159sourceCode.getLastTokenBetween(AST, AST, { includeComments: true });160sourceCode.getLastTokenBetween(AST, AST, { includeComments: true, skip: 0 });161sourceCode.getLastTokenBetween(AST, AST, { includeComments: true, skip: 0, filter: t => t.type === 'Identifier' });162sourceCode.getLastTokensBetween(AST, AST);163sourceCode.getLastTokensBetween(AST, AST, 0);164sourceCode.getLastTokensBetween(AST, AST, { count: 0 });165sourceCode.getLastTokensBetween(AST, AST, t => t.type === 'Identifier');166sourceCode.getLastTokensBetween(AST, AST, { filter: t => t.type === 'Identifier' });167sourceCode.getLastTokensBetween(AST, AST, { count: 0, filter: t => t.type === 'Identifier' });168sourceCode.getLastTokensBetween(AST, AST, { includeComments: true });169sourceCode.getLastTokensBetween(AST, AST, { includeComments: true, count: 0 });170sourceCode.getLastTokensBetween(AST, AST, { includeComments: true, count: 0, filter: t => t.type === 'Identifier' });171sourceCode.getTokensBetween(AST, AST);172sourceCode.getTokensBetween(AST, AST, 0);173sourceCode.getTokens(AST);174sourceCode.getTokens(AST, 0);175sourceCode.getTokens(AST, 0, 0);176sourceCode.getTokens(AST, t => t.type === 'Identifier');177sourceCode.getTokens(AST, { filter: t => t.type === 'Identifier' });178sourceCode.getTokens(AST, { includeComments: true });179sourceCode.getTokens(AST, { includeComments: true, filter: t => t.type === 'Identifier' });180sourceCode.commentsExistBetween(AST, AST);181sourceCode.commentsExistBetween(TOKEN, TOKEN);182sourceCode.getCommentsBefore(AST);183sourceCode.getCommentsBefore(TOKEN);184sourceCode.getCommentsAfter(AST);185sourceCode.getCommentsAfter(TOKEN);186sourceCode.getCommentsInside(AST);187//#endregion188//#region Scope189const scopeManager: Scope.ScopeManager = {190 scopes: [],191 globalScope: null,192 acquire(node, inner) {193 return scopeManager.scopes[0];194 },195 getDeclaredVariables() {196 return [];197 }198};199const scope = scopeManager.scopes[0];200const variable = scope.variables[0];201variable.name = 'foo';202variable.identifiers[0].type = 'Identifier';203variable.defs[0].name.type = 'Identifier';204variable.defs[0].type;205variable.defs[0].node;206variable.defs[0].parent;207const reference = scope.references[0];208reference.from = scope;209reference.identifier.type = 'Identifier';210reference.resolved = variable;211reference.writeExpr = AST;212reference.init = true;213reference.isRead();214reference.isReadOnly();215reference.isWrite();216reference.isWriteOnly();217reference.isReadWrite();218//#endregion219//#region Rule220let rule: Rule.RuleModule;221rule = { create(context) { return {}; } };222rule = { create(context) { return {}; }, meta: {} };223rule = { create(context) { return {}; }, meta: {224 docs: {225 description: 'disallow the use of `console`',226 category: 'Possible Errors',227 recommended: true,228 url: 'https://eslint.org/docs/rules/no-console',229 }230}};231rule = { create(context) { return {}; }, meta: { fixable: 'whitespace' }};232rule = { create(context) { return {}; }, meta: { fixable: 'code' }};233rule = { create(context) { return {}; }, meta: { schema: [{ enum: ['always', 'never'] }] }};234rule = { create(context) { return {}; }, meta: { deprecated: true }};235rule = {236 create(context) {237 context.getAncestors();238 context.getDeclaredVariables(AST);239 context.getFilename();240 context.getSourceCode();241 context.getScope();242 context.markVariableAsUsed('foo');243 context.report({ message: 'foo', node: AST });244 context.report({ message: 'foo', loc: { line: 0, column: 0 } });245 context.report({ message: 'foo', node: AST, data: { foo: 'bar' } });246 context.report({ message: 'foo', node: AST, fix: () => null });247 context.report({ message: 'foo', node: AST, fix: ruleFixer => ruleFixer.replaceText(AST, 'foo') });248 context.report({249 message: 'foo',250 node: AST,251 fix: ruleFixer => {252 ruleFixer.insertTextAfter(AST, 'foo');253 ruleFixer.insertTextAfter(TOKEN, 'foo');254 ruleFixer.insertTextAfterRange([0, 0], 'foo');255 ruleFixer.insertTextBefore(AST, 'foo');256 ruleFixer.insertTextBefore(TOKEN, 'foo');257 ruleFixer.insertTextBeforeRange([0, 0], 'foo');258 ruleFixer.remove(AST);259 ruleFixer.remove(TOKEN);260 ruleFixer.removeRange([0, 0]);261 ruleFixer.replaceText(AST, 'foo');262 ruleFixer.replaceText(TOKEN, 'foo');263 ruleFixer.replaceTextRange([0, 0], 'foo');264 return null;265 }266 });267 return {268 onCodePathStart(codePath, node) {},269 onCodePathEnd(codePath, node) {},270 onCodePathSegmentStart(segment, node) {},271 onCodePathSegmentEnd(segment, node) {},272 onCodePathSegmentLoop(fromSegment, toSegment, node) {},273 IfStatement(node) {},274 'Program:exit'() {},275 };276 },277};278//#endregion279//#region Linter280const linter = new Linter();281linter.version;282linter.verify(SOURCE, {});283linter.verify(new SourceCode(SOURCE, AST), {});284linter.verify(SOURCE, {}, 'test.js');285linter.verify(SOURCE, {}, {});286linter.verify(SOURCE, {}, { filename: 'test.js' });287linter.verify(SOURCE, {}, { allowInlineConfig: false });288linter.verify(SOURCE, {}, { reportUnusedDisableDirectives: true });289linter.verify(SOURCE, {}, { preprocess: input => input.split(' ') });290linter.verify(SOURCE, {}, { postprocess: problemList => problemList[0] });291linter.verify(SOURCE, { parserOptions: { ecmaVersion: 6 } }, 'test.js');292linter.verify(SOURCE, { parserOptions: { ecmaVersion: 6, ecmaFeatures: { globalReturn: true } } }, 'test.js');293linter.verify(SOURCE, { parserOptions: { ecmaVersion: 6, ecmaFeatures: { experimentalObjectRestSpread: true } } }, 'test.js');294linter.verify(SOURCE, { env: { node: true } }, 'test.js');295linter.verify(SOURCE, { globals: { foo: true } }, 'test.js');296linter.verify(SOURCE, { parser: 'custom-parser' }, 'test.js');297linter.verify(SOURCE, { settings: { info: 'foo' } }, 'test.js');298linter.verify(SOURCE, { rules: {} }, 'test.js');299linter.verify(SOURCE, { rules: { quotes: 2 } }, 'test.js');300linter.verify(SOURCE, { rules: { quotes: [2, 'double'] } }, 'test.js');301linter.verify(SOURCE, { rules: { 'no-unused-vars': [2, { vars: 'all' }] } }, 'test.js');302linter.verify(SOURCE, { rules: { 'no-console': 1 } }, 'test.js');303linter.verify(SOURCE, { rules: { 'no-console': 0 } }, 'test.js');304linter.verify(SOURCE, { rules: { 'no-console': 'error' } }, 'test.js');305linter.verify(SOURCE, { rules: { 'no-console': 'warn' } }, 'test.js');306linter.verify(SOURCE, { rules: { 'no-console': 'off' } }, 'test.js');307const lintingResult = linter.verify(SOURCE, {});308for (const msg of lintingResult) {309 msg.severity = 1;310 msg.severity = 2;311 msg.ruleId = 'foo';312 msg.fatal = true;313 msg.line = 0;314 msg.endLine = 0;315 msg.column = 0;316 msg.endColumn = 0;317 msg.source = SOURCE;318 if (msg.fix) {319 msg.fix.text = 'foo';320 msg.fix.range = [0, 0];321 }322}323linter.verifyAndFix(SOURCE, {});324linter.verifyAndFix(SOURCE, {}, 'test.js');325linter.verifyAndFix(SOURCE, {}, { fix: false });326const fixResult = linter.verifyAndFix(SOURCE, {});327fixResult.fixed = true;328fixResult.output = 'foo';329for (const msg of fixResult.messages) {330 msg.ruleId = 'foo';331}332sourceCode = linter.getSourceCode();333linter.defineRule('test', rule);334linter.defineRules({335 foo: rule,336 bar: rule,337});338linter.getRules();339linter.defineParser('custom-parser', { parse: (src, opts) => AST });340linter.defineParser('custom-parser', {341 parseForESLint(src, opts) {342 return {343 ast: AST,344 visitorKeys: {},345 parserServices: {},346 scopeManager,347 };348 }349});350//#endregion351//#region CLIEngine352let cli: CLIEngine;353cli = new CLIEngine({ allowInlineConfig: false });354cli = new CLIEngine({ baseConfig: false });355cli = new CLIEngine({ baseConfig: { extends: ['lynt'] }});356cli = new CLIEngine({ cache: true });357cli = new CLIEngine({ cacheFile: 'foo' });358cli = new CLIEngine({ configFile: 'foo' });359cli = new CLIEngine({ cwd: 'foo' });360cli = new CLIEngine({ envs: ['browser'] });361cli = new CLIEngine({ extensions: ['js'] });362cli = new CLIEngine({ fix: true });363cli = new CLIEngine({ globals: ['foo'] });364cli = new CLIEngine({ ignore: true });365cli = new CLIEngine({ ignorePath: 'foo' });366cli = new CLIEngine({ ignorePattern: 'foo' });367cli = new CLIEngine({ ignorePattern: ['foo', 'bar'] });368cli = new CLIEngine({ useEslintrc: false });369cli = new CLIEngine({ parserOptions: {} });370cli = new CLIEngine({ plugins: ['foo'] });371cli = new CLIEngine({ rules: { 'test/example-rule': 1 } });372cli = new CLIEngine({ rulePaths: ['foo'] });373cli = new CLIEngine({ reportUnusedDisableDirectives: true });374let cliReport = cli.executeOnFiles(['myfile.js', 'lib/']);375cliReport = cli.executeOnText(SOURCE, 'foo');376cli.resolveFileGlobPatterns(['**/*']);377cli.getConfigForFile('./config.json');378cli.addPlugin('my-fancy-plugin', {});379cli.isPathIgnored('./dist/index.js');380let formatter: CLIEngine.Formatter;381formatter = cli.getFormatter('codeframe');382formatter = cli.getFormatter();383formatter(cliReport.results);384CLIEngine.getErrorResults(cliReport.results);385CLIEngine.outputFixes(cliReport);386cliReport.errorCount = 0;387cliReport.warningCount = 0;388cliReport.fixableErrorCount = 0;389cliReport.fixableWarningCount = 0;390for (const file of cliReport.results) {391 file.filePath = 'foo.js';392 file.errorCount = 0;393 file.warningCount = 0;394 file.fixableErrorCount = 0;395 file.fixableWarningCount = 0;396 file.source = 'foo';397 file.output = 'foo';398 for (const message of file.messages) {399 message.ruleId = 'foo';400 }401}402//#endregion403//#region RuleTester404const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2015 } });405ruleTester.run('my-rule', rule, {406 valid: [407 { code: 'foo' },408 { code: 'foo', options: [{ allowFoo: true }] },409 { code: 'foo', filename: 'test.js' },410 { code: 'foo', parserOptions: {} },411 { code: 'foo', settings: { foo: true } },412 { code: 'foo', parser: 'foo' },413 { code: 'foo', globals: { foo: true } },414 ],415 invalid: [416 { code: 'foo', errors: 1 },417 { code: 'foo', errors: ['foo'] },418 { code: 'foo', errors: [{ message: 'foo' }] },419 { code: 'foo', errors: [{ message: 'foo', type: 'foo' }] },420 { code: 'foo', errors: [{ message: 'foo', data: { foo: true } }] },421 { code: 'foo', errors: [{ message: 'foo', line: 0 }] },422 ]423});424ruleTester.run('simple-valid-test', rule, {425 valid: [426 'foo',427 'bar',428 { code: 'foo', options: [{ allowFoo: true }] },429 ]430});...

Full Screen

Full Screen

generateAndCompileContract.js

Source:generateAndCompileContract.js Github

copy

Full Screen

1import getSolidityUtilities from './getSolidityUtilities'2import getSupportedSolidityVersion from './getSupportedSolidityVersion'3/**4 * Generate and compile a contract5 * @param sourceCode6 * @param lines7 * @param descriptions8 * @param updates9 * @param prefixedLines10 * @param postFixedLines11 * @return {Promise<{sourceCode, selectedContract: *}>}12 */13async function generateAndCompileContract(14 sourceCode,15 lines,16 descriptions,17 updates,18 prefixedLines,19 postFixedLines20) {21 sourceCode = JSON.parse(JSON.stringify(sourceCode))22 let bodyStart = 323 for (let i = 0; i < sourceCode.length; i++) {24 if (sourceCode[i].trim().toLowerCase() === 'function_body') {25 bodyStart = i26 sourceCode.splice(bodyStart, 1)27 break28 }29 }30 if (lines && lines.length) {31 for (let i = lines.length - 1; i >= 0; i--) {32 lines[i] !== 'undefined' &&33 lines[i] !== 'null' &&34 sourceCode.splice(bodyStart, 0, ' ' + lines[i])35 }36 }37 if (prefixedLines && prefixedLines.length) {38 sourceCode.splice(2, 0, '')39 for (let i = prefixedLines.length - 1; i >= 0; i--) {40 prefixedLines[i] !== 'undefined' &&41 prefixedLines[i] !== 'null' &&42 sourceCode.splice(2, 0, ' ' + prefixedLines[i])43 }44 }45 const compilers = (await getSolidityUtilities().getCompilers()).releases46 const version = (await getSupportedSolidityVersion())[0] //Object.keys(compilers)[0];47 sourceCode.unshift('')48 sourceCode.unshift('pragma solidity ^' + version + ';')49 if (updates && updates.length) {50 sourceCode.unshift(' */')51 for (let i = updates.length - 1; i >= 0; i--) {52 sourceCode.unshift(' * ' + updates[i])53 }54 sourceCode.unshift('/* Update:')55 }56 sourceCode.unshift(' */')57 for (let i = descriptions.length - 1; i >= 0; i--) {58 sourceCode.unshift(' * ' + descriptions[i])59 }60 sourceCode.unshift('/* Description:')61 if (postFixedLines && postFixedLines.length) {62 sourceCode.push('')63 postFixedLines.forEach((it) => sourceCode.push(it))64 }65 sourceCode = sourceCode.join('\n')66 return {67 sourceCode,68 selectedContract: (69 await getSolidityUtilities().compile(sourceCode, compilers[version])70 ).optimized.DFOHubGeneratedProposal,71 }72}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var ladle = require('ladle');2var sourceCode = ladle.sourceCode;3var ladle = require('ladle');4var sourceCode = ladle.sourceCode({sourcemap: true});5var ladle = require('ladle');6var sourceCode = ladle.sourceCode({sourcemap: true, minify: true});7var ladle = require('ladle');8var sourceCode = ladle.sourceCode({sourcemap: true, minify: true, uglify: true});9var ladle = require('ladle');10var sourceCode = ladle.sourceCode({sourcemap: true, minify: true, uglify: true, concat: true});11var ladle = require('ladle');12var sourceCode = ladle.sourceCode;13var ladle = require('ladle');14var sourceCode = ladle.sourceCode({sourcemap: true});15var ladle = require('ladle');16var sourceCode = ladle.sourceCode({sourcemap: true, minify: true});17var ladle = require('ladle');18var sourceCode = ladle.sourceCode({sourcemap: true, minify: true, uglify: true});19var ladle = require('ladle');20var sourceCode = ladle.sourceCode({sourcemap: true, minify: true, uglify: true, concat: true});

Full Screen

Using AI Code Generation

copy

Full Screen

1var ladle = require('ladle');2var sourceCode = ladle.sourceCode;3var code = sourceCode('test.js');4console.log(code);5var ladle = require('ladle');6var sourceCodeSync = ladle.sourceCodeSync;7var code = sourceCodeSync('test.js');8console.log(code);9var ladle = require('ladle');10var sourceCode = ladle.sourceCode;11sourceCode('test.js', function(err, code){12 console.log(code);13});14var ladle = require('ladle');15var sourceCodeSync = ladle.sourceCodeSync;16sourceCodeSync('test.js', function(err, code){17 console.log(code);18});19var ladle = require('ladle');20var sourceCode = ladle.sourceCode;21sourceCode('test.js', function(err, code){22 console.log(code);23});24var ladle = require('ladle');25var sourceCodeSync = ladle.sourceCodeSync;26sourceCodeSync('test.js', function(err, code){27 console.log(code);28});29var ladle = require('ladle');30var sourceCode = ladle.sourceCode;31sourceCode('test.js', function(err, code){32 console.log(code);33});34var ladle = require('ladle');35var sourceCodeSync = ladle.sourceCodeSync;36sourceCodeSync('test.js', function(err, code){37 console.log(code);38});39var ladle = require('ladle');40var sourceCode = ladle.sourceCode;41sourceCode('test.js', function(err, code){42 console.log(code);43});44var ladle = require('ladle');45var sourceCodeSync = ladle.sourceCodeSync;46sourceCodeSync('test.js', function

Full Screen

Using AI Code Generation

copy

Full Screen

1var ladle = require('ladle');2var sourceCode = ladle.sourceCode;3var source = sourceCode('test.js');4console.log(source);5var ladle = require('ladle');6var sourceCode = ladle.sourceCode;7var source = sourceCode('test.js');8console.log(source);9var ladle = require('ladle');10var sourceCode = ladle.sourceCode;11var source = sourceCode('test.js');12console.log(source);13var ladle = require('ladle');14var sourceCode = ladle.sourceCode;15var source = sourceCode('test.js');16console.log(source);17var ladle = require('ladle');18var sourceCode = ladle.sourceCode;19var source = sourceCode('test.js');20console.log(source);21var ladle = require('ladle');22var sourceCode = ladle.sourceCode;23var source = sourceCode('test.js');24console.log(source);25var ladle = require('ladle');26var sourceCode = ladle.sourceCode;27var source = sourceCode('test.js');28console.log(source);29var ladle = require('ladle');30var sourceCode = ladle.sourceCode;31var source = sourceCode('test.js');32console.log(source);33var ladle = require('ladle');34var sourceCode = ladle.sourceCode;35var source = sourceCode('test.js');36console.log(source);37var ladle = require('ladle');38var sourceCode = ladle.sourceCode;39var source = sourceCode('test.js');40console.log(source);41var ladle = require('ladle');42var sourceCode = ladle.sourceCode;

Full Screen

Using AI Code Generation

copy

Full Screen

1var ladle = require('ladle');2var ladleObj = ladle.createLadle();3var srcCode = ladleObj.sourceCode();4console.log(srcCode);5var ladle = require('ladle');6var ladleObj = ladle.createLadle();7var srcCode = ladleObj.sourceCode();8console.log(srcCode);9var ladle = require('ladle');10var ladleObj = ladle.createLadle();11var srcCode = ladleObj.sourceCode();12console.log(srcCode);13var ladle = require('ladle');14var ladleObj = ladle.createLadle();15var srcCode = ladleObj.sourceCode();16console.log(srcCode);17var ladle = require('ladle');18var ladleObj = ladle.createLadle();19var srcCode = ladleObj.sourceCode();20console.log(srcCode);21var ladle = require('ladle');22var ladleObj = ladle.createLadle();23var srcCode = ladleObj.sourceCode();24console.log(srcCode);25var ladle = require('ladle');26var ladleObj = ladle.createLadle();27var srcCode = ladleObj.sourceCode();28console.log(srcCode);29var ladle = require('ladle');30var ladleObj = ladle.createLadle();31var srcCode = ladleObj.sourceCode();32console.log(srcCode);33var ladle = require('ladle');34var ladleObj = ladle.createLadle();35var srcCode = ladleObj.sourceCode();36console.log(srcCode);37var ladle = require('ladle');38var ladleObj = ladle.createLadle();39var srcCode = ladleObj.sourceCode();40console.log(srcCode);41var ladle = require('ladle');42var ladleObj = ladle.createLadle();43var srcCode = ladleObj.sourceCode();44console.log(srcCode);

Full Screen

Using AI Code Generation

copy

Full Screen

1var ladle = require('ladle');2var db = ladleObj.db('test');3var doc = db.doc('testDoc');4doc.sourceCode(function(err, data){5 if(err){6 console.log('Error: ', err);7 }8 else{9 console.log('data: ', data);10 }11});12var ladle = require('ladle');13var db = ladleObj.db('test');14var doc = db.doc('testDoc');15doc.getAttachment('testAttachment', function(err, data){16 if(err){17 console.log('Error: ', err);18 }19 else{20 console.log('data: ', data);21 }22});23var ladle = require('ladle');24var db = ladleObj.db('test');25var doc = db.doc('testDoc');26doc.getAttachmentInfo('testAttachment', function(err, data){27 if(err){28 console.log('Error: ', err);29 }30 else{31 console.log('data: ', data);32 }33});34var ladle = require('ladle');35var db = ladleObj.db('test');36var doc = db.doc('testDoc');37doc.saveAttachment('testAttachment', 'testAttachmentData', 'text/plain', function(err, data){38 if(err){39 console.log('Error: ', err);40 }41 else{42 console.log('data: ', data);43 }44});45var ladle = require('ladle');

Full Screen

Using AI Code Generation

copy

Full Screen

1const ladle = require('ladle');2const sourceCode = ladle.sourceCode;3.then(data => {4 console.log(data);5})6.catch(err => {7 console.log(err);8});91. Fork it (<

Full Screen

Using AI Code Generation

copy

Full Screen

1var ladle = require('ladle');2var sourceCode = ladle.sourceCode;3var code = sourceCode(__filename);4console.log(code);5### ladle(sourceCode, options)6### ladle.sourceCode(filename)7### ladle.require(filename)8### ladle.requireWithSourceCode(filename)9### ladle.loadFile(filename)10### ladle.loadFileWithSourceCode(filename)11### ladle.load(filename)12### ladle.loadWithSourceCode(filename)13### ladle.loadFileWithSourceCode(filename)14### ladle.addModule(filename, module)15### ladle.addSourceCode(filename, sourceCode)16### ladle.add(filename, module, sourceCode)

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run ladle 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