diff --git a/src/rules/numberLiteralFormatRule.ts b/src/rules/numberLiteralFormatRule.ts index 4c4ecc08c7a..0d3c9bbf620 100644 --- a/src/rules/numberLiteralFormatRule.ts +++ b/src/rules/numberLiteralFormatRule.ts @@ -19,6 +19,7 @@ import { isNumericLiteral } from "tsutils"; import * as ts from "typescript"; import * as Lint from "../index"; +import { isUpperCase } from "./variableNameRule"; export class Rule extends Lint.Rules.AbstractRule { /* tslint:disable:object-literal-sort-keys */ @@ -33,10 +34,11 @@ export class Rule extends Lint.Rules.AbstractRule { }; /* tslint:enable:object-literal-sort-keys */ - public static FAILURE_STRING_LEADING_0 = "Exponent should not have a leading '0'."; + public static FAILURE_STRING_LEADING_0 = "Number literal should not have a leading '0'."; public static FAILURE_STRING_TRAILING_0 = "Number literal should not have a trailing '0'."; public static FAILURE_STRING_TRAILING_DECIMAL = "Number literal should not end in '.'."; public static FAILURE_STRING_LEADING_DECIMAL = "Number literal should begin with '0.' and not just '.'."; + public static FAILURE_STRING_NOT_UPPERCASE = "Hexadecimal number literal should be uppercase."; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { return this.applyWithFunction(sourceFile, walk); @@ -55,6 +57,24 @@ function walk(ctx: Lint.WalkContext): void { function check(node: ts.NumericLiteral): void { // Apparently the number literal '0.0' has a '.text' of '0', so use '.getText()' instead. const text = node.getText(sourceFile); + + if (text.startsWith("0")) { + switch (text[1]) { + case "x": + if (!isUpperCase(text.slice(2))) { + fail(Rule.FAILURE_STRING_NOT_UPPERCASE); + } + break; + case "o": + case "b": + break; + default: + fail(Rule.FAILURE_STRING_LEADING_0); + } + // Hex/octal/binary number can't have decimal point or exponent, so no other errors possible. + return; + } + const [num, exp] = text.split(/e/i); if (exp !== undefined && (exp.startsWith("-0") || exp.startsWith("0"))) { ctx.addFailureAt(node.getEnd() - exp.length, exp.length, Rule.FAILURE_STRING_LEADING_0); diff --git a/test/rules/number-literal-format/test.ts.lint b/test/rules/number-literal-format/test.ts.lint index fa9aca43076..ef58dbea6b9 100644 --- a/test/rules/number-literal-format/test.ts.lint +++ b/test/rules/number-literal-format/test.ts.lint @@ -3,6 +3,9 @@ 10; 1.1e10; +01; +~~ [leading-0] + 1. ~~ [trailing-decimal] @@ -27,7 +30,11 @@ 1.0e10; ~~~ [trailing-0] -[leading-0]: Exponent should not have a leading '0'. +0xDEAdBEEF; +~~~~~~~~~~ [0] + +[leading-0]: Number literal should not have a leading '0'. [trailing-0]: Number literal should not have a trailing '0'. [trailing-decimal]: Number literal should not end in '.'. [leading-decimal]: Number literal should begin with '0.' and not just '.'. +[uppercase]: Hexadecimal number literal should be uppercase.