Skip to content

Commit 6036e69

Browse files
remo5000ning-y
authored andcommitted
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
1 parent 63c7a24 commit 6036e69

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

src/interop.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,8 @@ export const toString = (value: Value, length = 0): string => {
7777
} else {
7878
return stripBody(value.toString())
7979
}
80+
} else if (value === null) {
81+
return 'null'
8082
} else {
8183
return value.toString()
8284
}

src/rules/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import noIfWithoutElse from './noIfWithoutElse'
1111
import noImplicitDeclareUndefined from './noImplicitDeclareUndefined'
1212
import noImplicitReturnUndefined from './noImplicitReturnUndefined'
1313
import noNonEmptyList from './noNonEmptyList'
14+
import noUnspecifiedLiteral from './noUnspecifiedLiteral'
1415
import noUnspecifiedOperator from './noUnspecifiedOperator'
1516
import singleVariableDeclaration from './singleVariableDeclaration'
1617

@@ -25,6 +26,7 @@ const rules: Array<Rule<es.Node>> = [
2526
noBlockArrowFunction,
2627
noDeclareReserved,
2728
noDeclareMutable,
29+
noUnspecifiedLiteral,
2830
noUnspecifiedOperator
2931
]
3032

src/rules/noUnspecifiedLiteral.ts

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import * as es from 'estree'
2+
3+
import { ErrorSeverity, ErrorType, Rule, SourceError } from '../types'
4+
5+
const specifiedLiterals = ['boolean', 'string', 'number']
6+
7+
export class NoUnspecifiedLiteral implements SourceError {
8+
public type = ErrorType.SYNTAX
9+
public severity = ErrorSeverity.ERROR
10+
11+
constructor(public node: es.Literal) {}
12+
13+
get location() {
14+
return this.node.loc!
15+
}
16+
17+
public explain() {
18+
/**
19+
* A check is used for RegExp to ensure that only null and RegExp are caught.
20+
* Any other unspecified literal value should not be caught.
21+
*/
22+
const literal = this.node.value === null ? 'null'
23+
: this.node.value instanceof RegExp ? 'RegExp'
24+
: ''
25+
return (
26+
`'${literal}' literals are not allowed`
27+
)
28+
}
29+
30+
public elaborate() {
31+
return this.explain()
32+
}
33+
}
34+
35+
const noUnspecifiedLiteral: Rule<es.Literal> = {
36+
name: 'no-unspecified-literal',
37+
checkers: {
38+
Literal(node: es.Literal) {
39+
if (!specifiedLiterals.includes(typeof node.value)) {
40+
return [new NoUnspecifiedLiteral(node)]
41+
} else {
42+
return []
43+
}
44+
}
45+
}
46+
}
47+
48+
export default noUnspecifiedLiteral

0 commit comments

Comments
 (0)