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

Add regexp/no-extra-lookaround-assertions rule #482

Merged
merged 8 commits into from
Nov 21, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ The rules with the following star :star: are included in the `plugin:regexp/reco
| [regexp/no-useless-character-class](https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-character-class.html) | disallow character class with one character | :star::wrench: |
| [regexp/no-useless-flag](https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-flag.html) | disallow unnecessary regex flags | :star::wrench: |
| [regexp/no-useless-lazy](https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-lazy.html) | disallow unnecessarily non-greedy quantifiers | :star::wrench: |
| [regexp/no-useless-lookaround-assertions](https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-lookaround-assertions.html) | disallow useless nested lookaround assertions | :wrench: |
| [regexp/no-useless-quantifier](https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-quantifier.html) | disallow quantifiers that can be removed | :star::wrench: |
| [regexp/no-useless-range](https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-range.html) | disallow unnecessary range of characters by using a hyphen | :star::wrench: |
| [regexp/no-useless-two-nums-quantifier](https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-two-nums-quantifier.html) | disallow unnecessary `{n,m}` quantifier | :star::wrench: |
Expand Down
1 change: 1 addition & 0 deletions docs/rules/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ The rules with the following star :star: are included in the `plugin:regexp/reco
| [regexp/no-useless-character-class](./no-useless-character-class.md) | disallow character class with one character | :star::wrench: |
| [regexp/no-useless-flag](./no-useless-flag.md) | disallow unnecessary regex flags | :star::wrench: |
| [regexp/no-useless-lazy](./no-useless-lazy.md) | disallow unnecessarily non-greedy quantifiers | :star::wrench: |
| [regexp/no-useless-lookaround-assertions](./no-useless-lookaround-assertions.md) | disallow useless nested lookaround assertions | :wrench: |
| [regexp/no-useless-quantifier](./no-useless-quantifier.md) | disallow quantifiers that can be removed | :star::wrench: |
| [regexp/no-useless-range](./no-useless-range.md) | disallow unnecessary range of characters by using a hyphen | :star::wrench: |
| [regexp/no-useless-two-nums-quantifier](./no-useless-two-nums-quantifier.md) | disallow unnecessary `{n,m}` quantifier | :star::wrench: |
Expand Down
53 changes: 53 additions & 0 deletions docs/rules/no-useless-lookaround-assertions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
---
pageClass: "rule-details"
sidebarDepth: 0
title: "regexp/no-useless-lookaround-assertions"
description: "disallow useless nested lookaround assertions"
---
# regexp/no-useless-lookaround-assertions

> disallow useless nested lookaround assertions

- :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> ***This rule has not been released yet.*** </badge>
- :wrench: The `--fix` option on the [command line](https://eslint.org/docs/user-guide/command-line-interface#fixing-problems) can automatically fix some of the problems reported by this rule.

## :book: Rule Details

The last positive lookahead assertion within a lookahead assertion is the same without the assertion.

```js
/Foo(?=Ba(?=r))/u; /* -> */ /Foo(?=Bar)/u;
```

Also, The first positive lookbehind assertion within a lookbehind assertion is the same without the assertion.

```js
/(?<=(?<=F)oo)Bar/u; /* -> */ /(?<=Foo)Bar/u;
```

This rule aims to report and fix these useless lookaround assertions.

<eslint-code-block fix>

```js
/* eslint regexp/no-useless-lookaround-assertions: "error" */

/* ✓ GOOD */
var s = 'JavaScript'.replace(/Java(?=Script)/u, 'Type');
var s = 'JavaScript'.replace(/(?<=Java)Script/u, '');

/* ✗ BAD */
var s = 'JavaScript'.replace(/Java(?=Scrip(?=t))/u, 'Type')
var s = 'JavaScript'.replace(/(?<=(?<=J)ava)Script/u, '')
```

</eslint-code-block>

## :wrench: Options

Nothing.

## :mag: Implementation

- [Rule source](https://github.com/ota-meshi/eslint-plugin-regexp/blob/master/lib/rules/no-useless-lookaround-assertions.ts)
- [Test source](https://github.com/ota-meshi/eslint-plugin-regexp/blob/master/tests/lib/rules/no-useless-lookaround-assertions.ts)
115 changes: 115 additions & 0 deletions lib/rules/no-useless-lookaround-assertions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import type {
LookaheadAssertion,
LookaroundAssertion,
LookbehindAssertion,
} from "regexpp/ast"
import type { RegExpVisitor } from "regexpp/visitor"
import type { RegExpContext } from "../utils"
import { createRule, defineRegexpVisitor } from "../utils"

export default createRule("no-useless-lookaround-assertions", {
meta: {
docs: {
description: "disallow useless nested lookaround assertions",
category: "Best Practices",
// TODO Switch to recommended in the major version.
// recommended: true,
recommended: false,
},
fixable: "code",
schema: [],
messages: {
unexpected: "This {{kind}} assertion is useless.",
},
type: "suggestion",
},
create(context) {
/**
* Create visitor
*/
function createVisitor(
regexpContext: RegExpContext,
): RegExpVisitor.Handlers {
return {
onAssertionEnter(aNode) {
if (aNode.kind === "lookahead") {
verifyForLookahead(regexpContext, aNode)
} else if (aNode.kind === "lookbehind") {
verifyForLookbehind(regexpContext, aNode)
}
},
}
}

/** Verify for lookahead assertion */
function verifyForLookahead(
RunDevelopment marked this conversation as resolved.
Show resolved Hide resolved
regexpContext: RegExpContext,
assertion: LookaheadAssertion,
) {
for (const alternative of assertion.alternatives) {
const last =
alternative.elements[alternative.elements.length - 1]
if (
last?.type !== "Assertion" ||
last.kind !== "lookahead" ||
last.negate
) {
continue
}
// The last lookahead positive assertion within
// a lookahead assertion is the same without the assertion.
reportLookaroundAssertion(regexpContext, last)
}
}

/** Verify for lookbehind assertion */
function verifyForLookbehind(
regexpContext: RegExpContext,
assertion: LookbehindAssertion,
) {
for (const alternative of assertion.alternatives) {
const first = alternative.elements[0]
if (
first?.type !== "Assertion" ||
RunDevelopment marked this conversation as resolved.
Show resolved Hide resolved
first.kind !== "lookbehind" ||
first.negate
) {
continue
}
// The first lookbehind positive assertion within
// a lookbehind assertion is the same without the assertion.
reportLookaroundAssertion(regexpContext, first)
}
}

/** Report */
function reportLookaroundAssertion(
{ node, getRegexpLocation, fixReplaceNode }: RegExpContext,
assertion: LookaroundAssertion,
) {
context.report({
node,
loc: getRegexpLocation(assertion),
messageId: "unexpected",
data: {
kind: assertion.kind,
},
fix: fixReplaceNode(assertion, () => {
const alternatives = assertion.alternatives.map(
(alt) => alt.raw,
)
if (alternatives.length <= 1) {
ota-meshi marked this conversation as resolved.
Show resolved Hide resolved
// unwrap `(?=` and `)`
return alternatives[0]
}
// replace `?=` with `?:`
return `(?:${alternatives.join("|")})`
}),
})
}

return defineRegexpVisitor(context, {
createVisitor,
})
},
})
2 changes: 2 additions & 0 deletions lib/utils/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import noUselessEscape from "../rules/no-useless-escape"
import noUselessExactlyQuantifier from "../rules/no-useless-exactly-quantifier"
import noUselessFlag from "../rules/no-useless-flag"
import noUselessLazy from "../rules/no-useless-lazy"
import noUselessLookaroundAssertions from "../rules/no-useless-lookaround-assertions"
import noUselessNonCapturingGroup from "../rules/no-useless-non-capturing-group"
import noUselessNonGreedy from "../rules/no-useless-non-greedy"
import noUselessQuantifier from "../rules/no-useless-quantifier"
Expand Down Expand Up @@ -120,6 +121,7 @@ export const rules = [
noUselessExactlyQuantifier,
noUselessFlag,
noUselessLazy,
noUselessLookaroundAssertions,
noUselessNonCapturingGroup,
noUselessNonGreedy,
noUselessQuantifier,
Expand Down
118 changes: 118 additions & 0 deletions tests/lib/rules/no-useless-lookaround-assertions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import { RuleTester } from "eslint"
import rule from "../../../lib/rules/no-useless-lookaround-assertions"

const tester = new RuleTester({
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
},
})

tester.run("no-useless-lookaround-assertions", rule as any, {
valid: [
`console.log('JavaScript'.replace(/Java(?=Script)/u, 'Type'))`,
`console.log('JavaScript'.replace(/(?<=Java)Script/u, ''))`,
],
invalid: [
{
code: `console.log('JavaScript'.replace(/Java(?=Scrip(?=t))/u, 'Type'))`,
output: `console.log('JavaScript'.replace(/Java(?=Script)/u, 'Type'))`,
errors: [
{
message: "This lookahead assertion is useless.",
column: 47,
},
],
},
{
code: `console.log('JavaScript'.replace(/(?<=(?<=J)ava)Script/u, ''))`,
output: `console.log('JavaScript'.replace(/(?<=Java)Script/u, ''))`,
errors: [
{
message: "This lookbehind assertion is useless.",
column: 39,
},
],
},
// Within negate
{
code: `console.log('JavaScript Java JavaRuntime'.replace(/Java(?!Scrip(?=t))/gu, 'Python'))`,
output: `console.log('JavaScript Java JavaRuntime'.replace(/Java(?!Script)/gu, 'Python'))`,
errors: [
{
message: "This lookahead assertion is useless.",
column: 64,
},
],
},
{
code: `console.log('JavaScript TypeScript ActionScript'.replace(/(?<!(?<=J)ava)Script/gu, 'ScriptCompiler'))`,
output: `console.log('JavaScript TypeScript ActionScript'.replace(/(?<!Java)Script/gu, 'ScriptCompiler'))`,
errors: [
{
message: "This lookbehind assertion is useless.",
column: 63,
},
],
},
// Multiple alternatives
{
code: `console.log('JavaScriptChecker JavaScriptLinter'.replace(/Java(?=Script(?=Checker|Linter))/gu, 'Type'))`,
output: `console.log('JavaScriptChecker JavaScriptLinter'.replace(/Java(?=Script(?:Checker|Linter))/gu, 'Type'))`,
errors: [
{
message: "This lookahead assertion is useless.",
column: 72,
},
],
},
{
code: `console.log('JavaScriptChecker JavaScriptLinter'.replace(/Java(?=Script(?=(?:Check|Lint)er))/gu, 'Type'))`,
output: `console.log('JavaScriptChecker JavaScriptLinter'.replace(/Java(?=Script(?:Check|Lint)er)/gu, 'Type'))`,
errors: [
{
message: "This lookahead assertion is useless.",
column: 72,
},
],
},
{
code: `console.log('ESLint JSLint TSLint'.replace(/(?<=(?<=J|T)S)Lint/gu, '-Runtime'))`,
output: `console.log('ESLint JSLint TSLint'.replace(/(?<=(?:J|T)S)Lint/gu, '-Runtime'))`,
errors: [
{
message: "This lookbehind assertion is useless.",
column: 49,
},
],
},
{
code: `console.log('JavaScriptChecker JavaScriptLinter'.replace(/Java(?=Script(?=Checker)|Script(?=Linter))/gu, 'Type'))`,
output: `console.log('JavaScriptChecker JavaScriptLinter'.replace(/Java(?=ScriptChecker|ScriptLinter)/gu, 'Type'))`,
errors: [
{
message: "This lookahead assertion is useless.",
column: 72,
},
{
message: "This lookahead assertion is useless.",
column: 90,
},
],
},
{
code: `console.log('ESLint JSLint TSLint'.replace(/(?<=(?<=J)S|(?<=T)S)Lint/gu, '-Runtime'))`,
output: `console.log('ESLint JSLint TSLint'.replace(/(?<=JS|TS)Lint/gu, '-Runtime'))`,
errors: [
{
message: "This lookbehind assertion is useless.",
column: 49,
},
{
message: "This lookbehind assertion is useless.",
column: 57,
},
],
},
],
})