2 * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package com
.siyeh
.ig
.bugs
;
18 import com
.intellij
.psi
.PsiExpression
;
19 import com
.intellij
.psi
.PsiExpressionList
;
20 import com
.intellij
.psi
.PsiMethodCallExpression
;
21 import com
.intellij
.psi
.PsiType
;
22 import com
.intellij
.psi
.util
.ConstantExpressionUtil
;
23 import com
.intellij
.psi
.util
.PsiUtil
;
24 import com
.siyeh
.InspectionGadgetsBundle
;
25 import com
.siyeh
.ig
.BaseInspection
;
26 import com
.siyeh
.ig
.BaseInspectionVisitor
;
27 import com
.siyeh
.ig
.psiutils
.MethodCallUtils
;
28 import com
.siyeh
.ig
.psiutils
.TypeUtils
;
29 import org
.jetbrains
.annotations
.NotNull
;
31 import java
.util
.regex
.Pattern
;
32 import java
.util
.regex
.PatternSyntaxException
;
34 public class MalformedRegexInspection
extends BaseInspection
{
37 public String
getDisplayName(){
38 return InspectionGadgetsBundle
.message(
39 "malformed.regular.expression.display.name");
43 public String
buildErrorString(Object
... infos
){
44 if (infos
.length
== 0) {
45 return InspectionGadgetsBundle
.message(
46 "malformed.regular.expression.problem.descriptor1");
48 return InspectionGadgetsBundle
.message(
49 "malformed.regular.expression.problem.descriptor2",
54 public boolean isEnabledByDefault(){
58 public BaseInspectionVisitor
buildVisitor(){
59 return new MalformedRegexVisitor();
62 private static class MalformedRegexVisitor
extends BaseInspectionVisitor
{
64 @Override public void visitMethodCallExpression(
65 @NotNull PsiMethodCallExpression expression
){
66 super.visitMethodCallExpression(expression
);
67 final PsiExpressionList argList
= expression
.getArgumentList();
71 final PsiExpression
[] args
= argList
.getExpressions();
75 final PsiExpression regexArg
= args
[0];
76 if(!TypeUtils
.expressionHasType("java.lang.String", regexArg
)){
79 if(!PsiUtil
.isConstantExpression(regexArg
)){
82 final PsiType regexType
= regexArg
.getType();
84 (String
) ConstantExpressionUtil
.computeCastTo(regexArg
,
89 if(!MethodCallUtils
.isCallToRegexMethod(expression
)){
92 //noinspection UnusedCatchParameter,ProhibitedExceptionCaught
94 Pattern
.compile(value
);
95 } catch(PatternSyntaxException e
){
96 registerError(regexArg
, e
.getDescription());
97 } catch(NullPointerException e
){
98 registerError(regexArg
); // due to a bug in the sun regex code