Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix control-character-escape false negatives #327

Merged
merged 1 commit into from
Sep 13, 2021
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
33 changes: 27 additions & 6 deletions lib/rules/control-character-escape.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { PatternRange } from "../utils/ast-utils/pattern-source"
import type { RegExpVisitor } from "regexpp/visitor"
import type { RegExpContext } from "../utils"
import {
Expand All @@ -21,6 +22,26 @@ const CONTROL_CHARS = new Map<number, string>([
[CP_CR, "\\r"],
])

/**
* Returns whether the regex is represented by a RegExp literal in source code
* at the given range.
*/
function isRegExpLiteralAt(
{ node, patternSource }: RegExpContext,
at: PatternRange,
): boolean {
if (isRegexpLiteral(node)) {
return true
}

const replaceRange = patternSource.getReplaceRange(at)
if (replaceRange && replaceRange.type === "RegExp") {
return true
}

return false
}

export default createRule("control-character-escape", {
meta: {
docs: {
Expand All @@ -40,11 +61,11 @@ export default createRule("control-character-escape", {
/**
* Create visitor
*/
function createVisitor({
node,
getRegexpLocation,
fixReplaceNode,
}: RegExpContext): RegExpVisitor.Handlers {
function createVisitor(
regexpContext: RegExpContext,
): RegExpVisitor.Handlers {
const { node, getRegexpLocation, fixReplaceNode } = regexpContext

return {
onCharacterEnter(cNode) {
if (cNode.parent.type === "CharacterClassRange") {
Expand All @@ -62,7 +83,7 @@ export default createRule("control-character-escape", {
return
}
if (
!isRegexpLiteral(node) &&
!isRegExpLiteralAt(regexpContext, cNode) &&
cNode.raw === String.fromCodePoint(cNode.value)
) {
// we allow the direct usage of control characters in
Expand Down
7 changes: 7 additions & 0 deletions tests/lib/rules/control-character-escape.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,5 +108,12 @@ tester.run("control-character-escape", rule as any, {
"Unexpected control character escape '\\u0009' (U+0009). Use '\\t' instead.",
],
},
{
code: String.raw`RegExp("\t\r\n\0" + / /.source)`,
output: String.raw`RegExp("\t\r\n\0" + /\t/.source)`,
errors: [
"Unexpected control character escape '\t' (U+0009). Use '\\t' instead.",
],
},
],
})