How to use the tslint.AbstractWalker function in tslint

To help you get started, we’ve selected a few tslint examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github palantir / tslint-react / src / rules / jsxWrapMultilineRule.ts View on Github external
};
    /* tslint:enable:object-literal-sort-keys */

    public static FAILURE_NOT_WRAPPED =
        "Multiline JSX elements must be wrapped in parentheses";
    public static FAILURE_MISSING_NEW_LINE_AFTER_OPEN =
        "New line required after open parenthesis when wrapping multiline JSX elements";
    public static FAILURE_MISSING_NEW_LINE_BEFORE_CLOSE =
        "New line required before close parenthesis when wrapping multiline JSX elements";

    public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
        return this.applyWithWalker(new JsxWrapMultilineWalker(sourceFile, this.ruleName, undefined));
    }
}

class JsxWrapMultilineWalker extends Lint.AbstractWalker {
    private scanner?: ts.Scanner;

    public walk(sourceFile: ts.SourceFile) {
        const cb = (node: ts.Node): void => {
            if (isJsxElement(node) || isJsxSelfClosingElement(node) || isJsxFragment(node)) {
                this.checkNode(node, sourceFile);
            }
            return ts.forEachChild(node, cb);
        };

        return ts.forEachChild(sourceFile, cb);
    }

    private checkNode(node: ts.JsxElement | ts.JsxSelfClosingElement | ts.JsxFragment, sourceFile: ts.SourceFile) {
        const startLine = this.getLine(node.getStart(this.sourceFile));
        const endLine = this.getLine(node.getEnd());
github 0xProject / 0x-monorepo / packages / tslint-config / rules / customNoMagicNumbersRule.ts View on Github external
ts.SyntaxKind.Parameter,
    ]);

    public static DEFAULT_ALLOWED = [-1, 0, 1];

    public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
        const allowedNumbers = this.ruleArguments.length > 0 ? this.ruleArguments : Rule.DEFAULT_ALLOWED;
        return this.applyWithWalker(
            // tslint:disable-next-line:no-inferred-empty-object-type
            new CustomNoMagicNumbersWalker(sourceFile, this.ruleName, new Set(allowedNumbers.map(String))),
        );
    }
}

// tslint:disable-next-line:max-classes-per-file
class CustomNoMagicNumbersWalker extends Lint.AbstractWalker> {
    public static FAILURE_STRING = "'magic numbers' are not allowed";
    private static _isNegativeNumberLiteral(
        node: ts.Node,
    ): node is ts.PrefixUnaryExpression & { operand: ts.NumericLiteral } {
        return (
            isPrefixUnaryExpression(node) &&
            node.operator === ts.SyntaxKind.MinusToken &&
            node.operand.kind === ts.SyntaxKind.NumericLiteral
        );
    }
    public walk(sourceFile: ts.SourceFile): void {
        const cb = (node: ts.Node): void => {
            if (node.kind === ts.SyntaxKind.NumericLiteral) {
                return this.checkNumericLiteral(node, (node as ts.NumericLiteral).text);
            }
            if (CustomNoMagicNumbersWalker._isNegativeNumberLiteral(node)) {
github buzinas / tslint-eslint-rules / src / rules / terNewlineAfterVarRule.ts View on Github external
};

  private formatOptions ([alwaysOrNever]: string[]): ITerNewlineAfterVarOptions {
    return {
      always: alwaysOrNever !== 'never'
    };
  }

  public apply (sourceFile: ts.SourceFile): Lint.RuleFailure[] {
    const opt = this.formatOptions(this.ruleArguments);
    const walker = new RuleWalker(sourceFile, this.ruleName, opt);
    return this.applyWithWalker(walker);
  }
}

class RuleWalker extends Lint.AbstractWalker {
  // last variable statement node
  private lastVariableStatementNode: ts.Node|undefined;
  private sourceFileText: string;

  public walk (sourceFile: ts.SourceFile) {
    this.sourceFileText = sourceFile.getFullText();

    const onNode = (node: ts.Node): void => {
      const { lastVariableStatementNode, sourceFileText } = this;

      // save the variable statement
      if (node.kind === ts.SyntaxKind.VariableStatement) {
        this.lastVariableStatementNode = node;
        return;
      }
github intershop / intershop-pwa / tslint-rules / src / ishOrderedImportsRule.ts View on Github external
if (sourcePath.startsWith('ish-')) {
      return ImportType.ParentDirectoryImport;
    }
    if (sourcePath.charAt(0) === '.') {
      if (sourcePath.charAt(1) === '.') {
        return ImportType.ParentDirectoryImport;
      } else {
        return ImportType.CurrentDirectoryImport;
      }
    } else {
      return ImportType.LibraryImport;
    }
  }
}

class Walker extends Lint.AbstractWalker {
  private readonly importsBlocks = [new ImportsBlock()];
  // keep a reference to the last Fix object so when the entire block is replaced, the replacement can be added
  private lastFix: Lint.Replacement[] | undefined;
  private nextType = ImportType.LibraryImport;

  private get currentImportsBlock(): ImportsBlock {
    return this.importsBlocks[this.importsBlocks.length - 1];
  }

  walk(sourceFile: ts.SourceFile): void {
    for (const statement of sourceFile.statements) {
      this.checkStatement(statement);
    }
    this.endBlock();
    if (this.options.groupedImports) {
      this.checkBlocksGrouping();
github ajafff / tslint-consistent-codestyle / rules / oddnessCheckRule.ts View on Github external
import * as ts from 'typescript';
import * as Lint from 'tslint';
import * as utils from 'tsutils';

const FAILURE_STRING = 'Modulus 2 can be replaced with & 1';

export class Rule extends Lint.Rules.AbstractRule {
    public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
        return this.applyWithWalker(new ReturnWalker(sourceFile, this.ruleName, undefined));
    }
}

class ReturnWalker extends Lint.AbstractWalker {
    public walk(sourceFile: ts.SourceFile) {
        const cb = (node: ts.Node): void => {
            if (utils.isBinaryExpression(node) &&
                node.operatorToken.kind === ts.SyntaxKind.PercentToken &&
                utils.isNumericLiteral(node.right) &&
                node.right.text === '2') {
                // TODO if this is part of a comparison with a negative value, this failure would be a false positive
                const start = node.operatorToken.getStart(sourceFile);
                this.addFailure(start, node.right.end, FAILURE_STRING, [
                    new Lint.Replacement(start, 1, '&'),
                    new Lint.Replacement(node.right.end - 1, 1, '1'),
                ]);
            }
            return ts.forEachChild(node, cb);
        };
        return ts.forEachChild(sourceFile, cb);
github hmil / tslint-override / rules / explicitOverrideRule.ts View on Github external
usePascalCase: hasPascalCaseParameter,
                newLineAfter: hasNewLineAfterParameter
            }, program.getTypeChecker()));
    }
}

const OVERRIDE_KEYWORD_CAMEL = 'override';
const OVERRIDE_KEYWORD_PASCAL = 'Override';
const OVERRIDE_DECORATOR_MATCHER = /^@[oO]verride(\(\s*\))?$/;

type HeritageChainCheckResult = {
    baseClass?: ts.Type;
    baseInterface?: ts.Type;
} | undefined;

class Walker extends Lint.AbstractWalker {

    constructor(
            sourceFile: ts.SourceFile,
            ruleName: string,
            private readonly _options: IOptions,
            private readonly checker: ts.TypeChecker) {
        super(sourceFile, ruleName, _options);
    }

    /** @override */
    public walk(sourceFile: ts.SourceFile) {
        const cb = (node: ts.Node): void => {
            if (isSomeClassElement(node)) {
                this.checkClassElement(node);
            }
            return ts.forEachChild(node, cb);
github intershop / intershop-pwa / tslint-rules / dist / ishOrderedImportsRule.js View on Github external
};
    Walker.prototype.getEolChar = function () {
        var lineEnd = this.sourceFile.getLineEndOfPosition(0);
        var newLine;
        if (lineEnd > 0) {
            if (lineEnd > 1 && this.sourceFile.text[lineEnd - 1] === '\r') {
                newLine = '\r\n';
            }
            else if (this.sourceFile.text[lineEnd] === '\n') {
                newLine = '\n';
            }
        }
        return newLine === undefined ? ts.sys.newLine : newLine;
    };
    return Walker;
}(Lint.AbstractWalker));
var Rule = (function (_super) {
    __extends(Rule, _super);
    function Rule() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Rule.prototype.apply = function (sourceFile) {
        return this.applyWithWalker(new Walker(sourceFile, this.ruleName, parseOptions()));
    };
    Rule.metadata = {
        ruleName: 'ish-ordered-imports',
        description: 'Requires that import statements be alphabetized and grouped.',
        descriptionDetails: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n            Enforce a consistent ordering for ES6 imports:\n            - Named imports must be alphabetized (i.e. \"import {A, B, C} from \"foo\";\")\n            - Import sources must be alphabetized within groups, i.e.:\n                    import * as foo from \"a\";\n                    import * as bar from \"b\";\n            - Groups of imports are delineated by blank lines."], ["\n            Enforce a consistent ordering for ES6 imports:\n            - Named imports must be alphabetized (i.e. \"import {A, B, C} from \"foo\";\")\n            - Import sources must be alphabetized within groups, i.e.:\n                    import * as foo from \"a\";\n                    import * as bar from \"b\";\n            - Groups of imports are delineated by blank lines."]))),
        hasFix: true,
        optionsDescription: Lint.Utils.dedent(templateObject_2 || (templateObject_2 = __makeTemplateObject([""], [""]))),
        options: {
            type: 'object',
github Gelio / tslint-import-group-ordering / src / import-groups-ordering-walker / import-groups-ordering-walker.ts View on Github external
import * as Lint from 'tslint';
import * as ts from 'typescript';

import {
  getBoundingTextRange,
  stringifyNodesContainers
} from '../nodes-containers/nodes-containers-utils';
import { NodesContainer } from '../nodes-containers';
import { WalkerOptions } from './walker-options';
import { ImportsGroup } from '../options/types';

export class ImportGroupsOrderingWalker extends Lint.AbstractWalker<
  WalkerOptions
> {
  private currentImportsGroupOrderNumber = 1;
  private allowNextImportsGroup = true;
  private foundUnmatchedImportDeclaration = false;

  private possiblyMisplacedNonImportStatements = new NodesContainer<
    ts.Statement
  >(this.getSourceFile());

  public walk(sourceFile: ts.SourceFile) {
    for (const statement of sourceFile.statements) {
      this.checkStatement(statement);
    }

    if (this.failures.length > 0 && !this.foundUnmatchedImportDeclaration) {
github buzinas / tslint-eslint-rules / src / rules / terFuncCallSpacingRule.ts View on Github external
if (userOptions[0] === ALWAYS) {
      options.expectSpace = true;
      if (userOptions[1] !== undefined && userOptions[1].allowNewlines) {
        options.spacePattern = /[ \t\r\n\u2028\u2029]/;
      }
      else {
        options.spacePattern = /[ \t]/;
      }
    }
    
    const walker = new RuleWalker(sourceFile, RULE_NAME, options);
    return this.applyWithWalker(walker);
  }
}

class RuleWalker extends Lint.AbstractWalker {
  sourceText: string;
  
  constructor(sourceFile: ts.SourceFile, ruleName: string, options: WalkerOptions) {
    super(sourceFile, ruleName, options);
    this.sourceText = sourceFile.getFullText();
  }
  
  public walk(sourceFile: ts.SourceFile) {
    const cb = (node: ts.Node) => {
      if (node.kind === ts.SyntaxKind.NewExpression) {
        this.visitNewExpression(node as ts.NewExpression);
      }
      else if(node.kind === ts.SyntaxKind.CallExpression) {
        this.visitCallExpression(node as ts.CallExpression);
      }
      else if (node.kind >= ts.SyntaxKind.FirstTypeNode && node.kind <= ts.SyntaxKind.LastTypeNode) {
github buzinas / tslint-eslint-rules / src / rules / terPaddedBlocksRule.ts View on Github external
return {
        blocks: config['blocks'] && config['blocks'] === OPTION_ALWAYS,
        classes: config['classes'] && config['classes'] === OPTION_ALWAYS,
        switches: config['switches'] && config['switches'] === OPTION_ALWAYS
      };
    }
  }

  public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
    const opt = this.formatOptions(this.ruleArguments);
    const walker = new RuleWalker(sourceFile, this.ruleName, opt);
    return this.applyWithWalker(walker);
  }
}

class RuleWalker extends Lint.AbstractWalker {
  public walk(sourceFile: ts.SourceFile) {
    sourceFile.forEachChild(node => this.processNode(node));
  }

  private processNode(node: ts.Node): void {
    switch (node.kind) {
      case ts.SyntaxKind.Block:
      case ts.SyntaxKind.ClassDeclaration:
      case ts.SyntaxKind.CaseBlock:
        this.checkPadding(node);
    }

    node.forEachChild(child => this.processNode(child));
  }

  private getParts(node: ts.Node): { openBrace: ts.Node, body: ts.Node, closeBrace: ts.Node } {