Skip to content

Commit

Permalink
Fix null and RegExp literal values being allowed (#31)
Browse files Browse the repository at this point in the history
* Fix toString raising runtime error on null

* Add rule for unspecified literals

* Import rule in index/rules

* Update explanation
  • Loading branch information
remo5000 authored and ning-y committed Aug 16, 2018
1 parent 63c7a24 commit 6036e69
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/interop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down
2 changes: 2 additions & 0 deletions src/rules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand All @@ -25,6 +26,7 @@ const rules: Array<Rule<es.Node>> = [
noBlockArrowFunction,
noDeclareReserved,
noDeclareMutable,
noUnspecifiedLiteral,
noUnspecifiedOperator
]

Expand Down
48 changes: 48 additions & 0 deletions src/rules/noUnspecifiedLiteral.ts
Original file line number Diff line number Diff line change
@@ -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<es.Literal> = {
name: 'no-unspecified-literal',
checkers: {
Literal(node: es.Literal) {
if (!specifiedLiterals.includes(typeof node.value)) {
return [new NoUnspecifiedLiteral(node)]
} else {
return []
}
}
}
}

export default noUnspecifiedLiteral

0 comments on commit 6036e69

Please sign in to comment.