From 6036e69e5dffb3fccd4e23574212b3b293901628 Mon Sep 17 00:00:00 2001 From: Vignesh Date: Thu, 16 Aug 2018 12:04:14 +0800 Subject: [PATCH] Fix null and RegExp literal values being allowed (#31) * Fix toString raising runtime error on null * Add rule for unspecified literals * Import rule in index/rules * Update explanation --- src/interop.ts | 2 ++ src/rules/index.ts | 2 ++ src/rules/noUnspecifiedLiteral.ts | 48 +++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 src/rules/noUnspecifiedLiteral.ts diff --git a/src/interop.ts b/src/interop.ts index 816a1c7cc..e55db7cea 100644 --- a/src/interop.ts +++ b/src/interop.ts @@ -77,6 +77,8 @@ export const toString = (value: Value, length = 0): string => { } else { return stripBody(value.toString()) } + } else if (value === null) { + return 'null' } else { return value.toString() } diff --git a/src/rules/index.ts b/src/rules/index.ts index 460ec68b6..7ef3213fa 100644 --- a/src/rules/index.ts +++ b/src/rules/index.ts @@ -11,6 +11,7 @@ import noIfWithoutElse from './noIfWithoutElse' import noImplicitDeclareUndefined from './noImplicitDeclareUndefined' import noImplicitReturnUndefined from './noImplicitReturnUndefined' import noNonEmptyList from './noNonEmptyList' +import noUnspecifiedLiteral from './noUnspecifiedLiteral' import noUnspecifiedOperator from './noUnspecifiedOperator' import singleVariableDeclaration from './singleVariableDeclaration' @@ -25,6 +26,7 @@ const rules: Array> = [ noBlockArrowFunction, noDeclareReserved, noDeclareMutable, + noUnspecifiedLiteral, noUnspecifiedOperator ] diff --git a/src/rules/noUnspecifiedLiteral.ts b/src/rules/noUnspecifiedLiteral.ts new file mode 100644 index 000000000..9d7219c1b --- /dev/null +++ b/src/rules/noUnspecifiedLiteral.ts @@ -0,0 +1,48 @@ +import * as es from 'estree' + +import { ErrorSeverity, ErrorType, Rule, SourceError } from '../types' + +const specifiedLiterals = ['boolean', 'string', 'number'] + +export class NoUnspecifiedLiteral implements SourceError { + public type = ErrorType.SYNTAX + public severity = ErrorSeverity.ERROR + + constructor(public node: es.Literal) {} + + get location() { + return this.node.loc! + } + + public explain() { + /** + * A check is used for RegExp to ensure that only null and RegExp are caught. + * Any other unspecified literal value should not be caught. + */ + const literal = this.node.value === null ? 'null' + : this.node.value instanceof RegExp ? 'RegExp' + : '' + return ( + `'${literal}' literals are not allowed` + ) + } + + public elaborate() { + return this.explain() + } +} + +const noUnspecifiedLiteral: Rule = { + name: 'no-unspecified-literal', + checkers: { + Literal(node: es.Literal) { + if (!specifiedLiterals.includes(typeof node.value)) { + return [new NoUnspecifiedLiteral(node)] + } else { + return [] + } + } + } +} + +export default noUnspecifiedLiteral