RegExp: don't warn about non-capturing group when it's empty (WEB-56936)

GitOrigin-RevId: 2ec8e8568e9ba85d31b17a3976ca1f5fd684b071
This commit is contained in:
Bas Leijdekkers
2022-08-15 10:39:52 +00:00
committed by intellij-monorepo-bot
parent 96437153d5
commit 94dbcba6d2
2 changed files with 14 additions and 8 deletions
@@ -1,4 +1,4 @@
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.intellij.lang.regexp.inspection;
import com.intellij.codeInspection.LocalInspectionTool;
@@ -38,14 +38,20 @@ public class UnnecessaryNonCapturingGroupInspection extends LocalInspectionTool
return;
}
final PsiElement parent = group.getParent();
final RegExpAtom atom = getSingleAtom(group.getPattern());
final RegExpPattern pattern = group.getPattern();
final RegExpAtom atom = getSingleAtom(pattern);
if (atom != null) {
if (!(parent instanceof RegExpClosure) || !(atom instanceof RegExpClosure)) {
registerProblem(group);
}
}
else if (parent instanceof RegExpBranch) {
if (hasOneBranch(group.getPattern())) {
final RegExpBranch[] branches = pattern.getBranches();
if (branches.length == 1) {
if (branches[0].getAtoms().length == 0) {
// don't warn on empty group because those already get an empty group warning
return;
}
registerProblem(group);
}
else {
@@ -64,10 +70,6 @@ public class UnnecessaryNonCapturingGroupInspection extends LocalInspectionTool
}
}
private static boolean hasOneBranch(RegExpPattern pattern) {
return pattern != null && pattern.getBranches().length == 1;
}
private static RegExpAtom getSingleAtom(RegExpPattern pattern) {
if (pattern == null) return null;
final RegExpBranch[] branches = pattern.getBranches();
@@ -1,4 +1,4 @@
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.intellij.lang.regexp.inspection;
import com.intellij.codeInspection.LocalInspectionTool;
@@ -24,6 +24,10 @@ public class UnnecessaryNonCapturingGroupInspectionTest extends RegExpInspection
highlightTest("aa(?:bb|bbb)cccc");
}
public void testNoNonCapturingGroupWarnOnEmptyGroup() {
highlightTest("<warning descr=\"Empty group\">(?:)</warning>");
}
public void testNoWarnOnNestedClosure() {
highlightTest("\\d{2}(?:\\d{3})?");
highlightTest("\\d{2}(?:\\d{3}){2}");