Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

Adds new rule "space-within-parens" #2959

Merged
merged 4 commits into from
Jul 21, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/configs/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ export const rules = {
"method": "never",
"named": "never",
}],
"space-within-parens": [true, 0],
"switch-final-break": true,
"type-literal-delimiter": true,
"variable-name": [
Expand Down
1 change: 1 addition & 0 deletions src/configs/latest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export const rules = {
"check-parameters",
],
"no-this-assignment": true,
"space-within-parens": [true, 0],
};
// tslint:enable object-literal-sort-keys

Expand Down
155 changes: 155 additions & 0 deletions src/rules/spaceWithinParensRule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/**
* @license
* Copyright 2017 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { forEachToken } from "tsutils";

import * as ts from "typescript";
import * as Lint from "../index";

interface Options {
size: number;
}

export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "space-within-parens",
description: "Enforces spaces within parentheses or disallow them.",
hasFix: true,
optionsDescription: Lint.Utils.dedent`
You may enforce the amount of whitespace within parentheses.
`,
options: { type: "number", min: 0 },
type: "style",
typescriptOnly: false,
};
/* tslint:enable:object-literal-sort-keys */

public static FAILURE_NO_SPACE = "Whitespace within parentheses is not allowed";
public static FAILURE_NEEDS_SPACE(count: number): string {
return `Needs ${count} whitespace${count > 1 ? "s" : ""} within parentheses`;
}
public static FAILURE_NO_EXTRA_SPACE(count: number): string {
return `No more than ${count} whitespace${count > 1 ? "s" : ""} within parentheses allowed`;
}

public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new SpaceWithinParensWalker(sourceFile, this.ruleName, parseOptions(this.ruleArguments[0])));
}
}

function parseOptions(whitespaceSize?: any): Options {
let size = 0;
if (typeof whitespaceSize === "number") {
if (whitespaceSize >= 0) {
size = whitespaceSize;
}
} else if (typeof whitespaceSize === "string") {
const parsedSize = parseInt(whitespaceSize, 10);
if (!Number.isNaN(parsedSize) && parsedSize >= 0) {
size = parsedSize;
}
}
return {
size,
};
}

class SpaceWithinParensWalker extends Lint.AbstractWalker<Options> {
public walk(sourceFile: ts.SourceFile) {
forEachToken(sourceFile, (token: ts.Node) => {
if (token.kind === ts.SyntaxKind.OpenParenToken) {
this.checkOpenParenToken(token);
} else if (token.kind === ts.SyntaxKind.CloseParenToken) {
this.checkCloseParenToken(token);
}
});
}

private checkOpenParenToken(tokenNode: ts.Node) {
let currentPos = tokenNode.end;
let currentChar = this.sourceFile.text.charCodeAt(currentPos);
const allowedSpaceCount = this.options.size;

while (ts.isWhiteSpaceSingleLine(currentChar)) {
++currentPos;
currentChar = this.sourceFile.text.charCodeAt(currentPos);
}
if (!ts.isLineBreak(currentChar)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if the rule is configured with 0 spaces, this condition will not show a warning for trailing whitespace right before a line break.
But that will be checked by trailing-whitespace anyway, so it's not strictly necessary here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I though about it too.

const whitespaceCount = currentPos - tokenNode.end;
if (whitespaceCount !== allowedSpaceCount) {
let length = 0;
let pos = tokenNode.end;

if (whitespaceCount > allowedSpaceCount) {
pos += allowedSpaceCount;
length = whitespaceCount - allowedSpaceCount;
} else if (whitespaceCount > 0 && whitespaceCount < allowedSpaceCount) {
pos += allowedSpaceCount - whitespaceCount;
}
this.addFailureAtWithFix(pos, length, whitespaceCount);
}
}
}

private checkCloseParenToken(tokenNode: ts.Node) {
let currentPos = tokenNode.end - 2;
let currentChar = this.sourceFile.text.charCodeAt(currentPos);
const allowedSpaceCount = this.options.size;

while (ts.isWhiteSpaceSingleLine(currentChar)) {
--currentPos;
currentChar = this.sourceFile.text.charCodeAt(currentPos);
}
/**
* Number 40 is open parenthese char code, we skip this cause
* it's already been caught by `checkOpenParenToken`
*/
if (!ts.isLineBreak(currentChar) && currentChar !== 40) {
const whitespaceCount = tokenNode.end - currentPos - 2;
if (whitespaceCount !== allowedSpaceCount) {
let length = 0;
const pos = currentPos + 1;

if (whitespaceCount > allowedSpaceCount) {
length = whitespaceCount - allowedSpaceCount;
}
this.addFailureAtWithFix(pos, length, whitespaceCount);
}
}
}

private addFailureAtWithFix(position: number, length: number, whitespaceCount: number) {
let lintMsg: string;
let lintFix: Lint.Replacement;
const allowedSpaceCount = this.options.size;

if (allowedSpaceCount === 0) {
lintMsg = Rule.FAILURE_NO_SPACE;
lintFix = Lint.Replacement.deleteText(position, length);
} else if (allowedSpaceCount > whitespaceCount) {
lintMsg = Rule.FAILURE_NEEDS_SPACE(allowedSpaceCount - whitespaceCount);
const whitespace = " ".repeat(allowedSpaceCount - whitespaceCount);
lintFix = Lint.Replacement.appendText(position, whitespace);
} else {
lintMsg = Rule.FAILURE_NO_EXTRA_SPACE(allowedSpaceCount);
lintFix = Lint.Replacement.deleteText(position, whitespaceCount - allowedSpaceCount);
}

this.addFailureAt(position, length, lintMsg, lintFix);
}
}
8 changes: 8 additions & 0 deletions test/rules/space-within-parens/force-one-space/test.ts.fix
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// export statement
export function rgb2lab( r : number, g : number, b : number ) : { L : number; a : number; b: number } {
var xyz = Conversion.rgb2xyz( r, g, b );
return Conversion.xyz2lab( xyz.x, xyz.y, xyz.z );
}

foo( /*no param*/ );

18 changes: 18 additions & 0 deletions test/rules/space-within-parens/force-one-space/test.ts.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// export statement
export function rgb2lab(r : number, g : number, b : number) : { L : number; a : number; b: number } {
~nil [0]
~nil [0]
var xyz = Conversion.rgb2xyz(r, g, b );
~nil [0]
~ [1]
return Conversion.xyz2lab( xyz.x, xyz.y, xyz.z);
~~ [1]
~nil [0]
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add a test with comments

foo(/*no param*/);
    ~nil [0]
                ~nil [0]

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch

foo(/*no param*/);
~nil [0]
~nil [0]

[0]: Needs 1 whitespace within parentheses
[1]: No more than 1 whitespace within parentheses allowed
5 changes: 5 additions & 0 deletions test/rules/space-within-parens/force-one-space/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"space-within-parens": [true, 1]
}
}
22 changes: 22 additions & 0 deletions test/rules/space-within-parens/force-two-spaces/test.ts.fix
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// simple expression
var x = [{
a: 1,
b: 2,
d: 34,
c: ( a + b ),
}];

// simple expression on one liner
var b = [{a: 1, b: 2, d: 34, c: ( a + b )}];

// function parameters
function foo( bar: string, baz: string );

// conditional & nested expression
if ( x === y ) {
return ( {result: true, error: ( x + y )} );
}

// be well
new Foo( );

36 changes: 36 additions & 0 deletions test/rules/space-within-parens/force-two-spaces/test.ts.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// simple expression
var x = [{
a: 1,
b: 2,
d: 34,
c: (a + b ),
~nil [1]
~ [2]
}];

// simple expression on one liner
var b = [{a: 1, b: 2, d: 34, c: ( a + b)}];
~ [2]
~nil [1]

// function parameters
function foo( bar: string, baz: string);
~nil [0]
~nil [1]

// conditional & nested expression
if (x === y) {
~nil [1]
~nil [1]
return ({result: true, error: ( x + y )} );
~nil [1]
~ [2]
}

// be well
new Foo();
~nil [1]

[0]: Needs 1 whitespace within parentheses
[1]: Needs 2 whitespaces within parentheses
[2]: No more than 2 whitespaces within parentheses allowed
5 changes: 5 additions & 0 deletions test/rules/space-within-parens/force-two-spaces/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"space-within-parens": [true, 2]
}
}
34 changes: 34 additions & 0 deletions test/rules/space-within-parens/no-space/test.ts.fix
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// simple call
console.clear();

// multiline call, this should be skipped
foo(
first,
second,
);

// conditional
if (process.env === 'production') {
console.log('start');
}

// conditional and nested
if (x === 'string' &&
y === 'object') {

// skip this conditional
if (
true === true && false !=== false
) {
// load
foo();
}
console.log('test');
}

// other expresions
switch (typeof x) {
default:
break;
}

47 changes: 47 additions & 0 deletions test/rules/space-within-parens/no-space/test.ts.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// simple call
console.clear( );
~ [0]

// multiline call, this should be skipped
foo(
first,
second,
);

// conditional
if ( process.env === 'production' ) {
~ [0]
~ [0]
console.log( 'start' );
~ [0]
~ [0]
}

// conditional and nested
if ( x === 'string' &&
~~ [0]
y === 'object' ) {
~~ [0]

// skip this conditional
if (
true === true && false !=== false
) {
// load
foo( );
~ [0]
}
console.log( 'test' );
~ [0]
~~ [0]
}

// other expresions
switch ( typeof x ) {
~~ [0]
~ [0]
default:
break;
}

[0]: Whitespace within parentheses is not allowed
5 changes: 5 additions & 0 deletions test/rules/space-within-parens/no-space/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"space-within-parens": [true, 0]
}
}