'unnecessary qualified references' inspection & 'replace qualified reference with import' intention in Groovy

This commit is contained in:
Maxim Medvedev
2011-09-09 14:41:29 +04:00
parent c7d9f33004
commit b98cbed2ff
19 changed files with 313 additions and 10 deletions
@@ -0,0 +1,7 @@
<html>
<body>
<font face="verdana" size="-1">
This inspection reports fully qualified references in Groovy files which can be replaced with import.
</font>
</body>
</html>
@@ -0,0 +1,5 @@
import java.util.concurrent.Semaphore
def createSemaphore() {
new <spot>Semaphore</spot>();
}
@@ -0,0 +1,3 @@
def createSemaphore() {
new <spot>java.util.concurrent.Semaphore</spot>();
}
@@ -0,0 +1,6 @@
<html>
<body>
<span style="font-family: verdana,serif;">This intention converts selected qualified reference into simple reference
and adds corresponding <b><font color="#000080">import</font></b> for that reference.</span>
</body>
</html>
+5
View File
@@ -562,6 +562,11 @@
<categoryKey>intention.category.groovy/intention.category.groovy.style</categoryKey>
<className>org.jetbrains.plugins.groovy.intentions.style.ImportOnDemandIntention</className>
</intentionAction>
<intentionAction>
<bundleName>org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle</bundleName>
<categoryKey>intention.category.groovy/intention.category.groovy.style</categoryKey>
<className>org.jetbrains.plugins.groovy.intentions.style.ReplaceQualifiedReferenceWithImportIntention</className>
</intentionAction>
<intentionAction>
<bundleName>org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle</bundleName>
<categoryKey>intention.category.groovy/intention.category.groovy.style</categoryKey>
@@ -70,4 +70,5 @@ type.doesnt.implemnt.comparable=Type ''{0}'' doesnt implement Comparable
add.method=Add method ''{0}()'' to class ''{1}''
implement.class=Implement {0}
fix.class=Fix class {0}
check.labeled.statement=Labeled statement inspection
check.labeled.statement=Labeled statement inspection
unnecessary.qualified.reference=Unnecessary qualified reference
@@ -120,6 +120,7 @@ public class GroovyInspectionProvider implements InspectionToolProvider, Applica
GroovyNegatedConditionalInspection.class,
GroovyNegatedIfInspection.class,
GroovyResultOfIncrementOrDecrementUsedInspection.class,
UnnecessaryQualifiedReferenceInspection.class,
GroovyEmptyStatementBodyInspection.class,
GroovyPointlessBooleanInspection.class,
GroovyPointlessArithmeticInspection.class,
@@ -0,0 +1,101 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.codeInspection.confusing;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.codeInspection.BaseInspection;
import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor;
import org.jetbrains.plugins.groovy.codeInspection.GroovyFix;
import org.jetbrains.plugins.groovy.codeInspection.GroovyInspectionBundle;
import org.jetbrains.plugins.groovy.intentions.style.ReplaceQualifiedReferenceWithImportIntention;
import org.jetbrains.plugins.groovy.lang.GrReferenceAdjuster;
import org.jetbrains.plugins.groovy.lang.psi.GrQualifiedReference;
import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement;
/**
* @author Max Medvedev
*/
public class UnnecessaryQualifiedReferenceInspection extends BaseInspection {
private static final Logger LOG = Logger.getInstance(UnnecessaryQualifiedReferenceInspection.class);
@Override
protected BaseInspectionVisitor buildVisitor() {
return new BaseInspectionVisitor() {
@Override
public void visitCodeReferenceElement(GrCodeReferenceElement refElement) {
super.visitCodeReferenceElement(refElement);
if (ReplaceQualifiedReferenceWithImportIntention.canBeReplacedWithImport(refElement)) {
registerError(refElement);
}
}
@Override
public void visitReferenceExpression(GrReferenceExpression referenceExpression) {
super.visitReferenceExpression(referenceExpression);
if (ReplaceQualifiedReferenceWithImportIntention.canBeReplacedWithImport(referenceExpression)) {
registerError(referenceExpression);
}
}
};
}
@Nls
@NotNull
@Override
public String getGroupDisplayName() {
return CONFUSING_CODE_CONSTRUCTS;
}
@Nls
@NotNull
@Override
public String getDisplayName() {
return GroovyInspectionBundle.message("unnecessary.qualified.reference");
}
@Override
protected String buildErrorString(Object... args) {
return GroovyInspectionBundle.message("unnecessary.qualified.reference");
}
@Override
protected GroovyFix buildFix(PsiElement location) {
return new GroovyFix() {
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
final PsiElement startElement = descriptor.getStartElement();
LOG.assertTrue(startElement instanceof GrReferenceElement);
GrReferenceAdjuster.shortenReference((GrQualifiedReference)startElement);
}
@NotNull
@Override
public String getName() {
return GroovyInspectionBundle.message("unnecessary.qualified.reference");
}
};
}
}
@@ -121,5 +121,7 @@ import.static.intention.name=Add static import
import.static.intention.family.name=Add Single-Member Static Import in Groovy
import.on.demand.intention.name=Add import on demand
import.on.demand.intention.family.name=Add On Demand Static Import in Groovy
replace.qualified.reference.with.import.intention.name=Replace with import
replace.qualified.reference.with.import.intention.family.name=Replace qualified reference with import
move.to.correct.dir.family.name=Move File to Correct Package
move.to.correct.dir=Move to ''{0}''
@@ -0,0 +1,97 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.intentions.style;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.intentions.base.Intention;
import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate;
import org.jetbrains.plugins.groovy.lang.GrReferenceAdjuster;
import org.jetbrains.plugins.groovy.lang.psi.GrQualifiedReference;
import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition;
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement;
/**
* @author Max Medvedev
*/
public class ReplaceQualifiedReferenceWithImportIntention extends Intention {
private static final Logger LOG = Logger.getInstance(ReplaceQualifiedReferenceWithImportIntention.class);
@Override
protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException {
LOG.assertTrue(element instanceof GrReferenceElement, element.getClass().getCanonicalName() + " : " + element.getText());
GrReferenceAdjuster.shortenReference((GrQualifiedReference)element);
}
@NotNull
@Override
protected PsiElementPredicate getElementPredicate() {
return new MyPredicate();
}
public static boolean canBeReplacedWithImport(PsiElement element) {
if (element instanceof GrCodeReferenceElement) {
if (PsiTreeUtil.getParentOfType(element, GrImportStatement.class, GrPackageDefinition.class) != null) return false;
}
else if (element instanceof GrReferenceExpression) {
if (!GrReferenceAdjuster.seemsToBeQualifiedClassName((GrReferenceExpression)element)) return false;
}
else {
return false;
}
final GrReferenceElement ref = (GrReferenceElement)element;
if (ref.getQualifier() == null) return false;
final PsiElement resolved = ref.resolve();
if (!(resolved instanceof PsiClass)) return false;
final String name = ((PsiClass)resolved).getName();
if (name == null) return false;
final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(element.getProject());
final GrReferenceExpression shortedRef = factory.createReferenceExpressionFromText(name, element);
final GroovyResolveResult resolveResult = shortedRef.advancedResolve();
if (resolveResult.getElement() == null || !resolveResult.isAccessible() || !resolveResult.isStaticsOK()) {
return true;
}
if (element.getManager().areElementsEquivalent(resolved, resolveResult.getElement())) {
return true;
}
return false;
}
private static class MyPredicate implements PsiElementPredicate {
@Override
public boolean satisfiedBy(PsiElement element) {
return canBeReplacedWithImport(element);
}
}
}
@@ -179,16 +179,16 @@ public class GrReferenceAdjuster {
PsiTreeUtil.getParentOfType(ref, GrImportStatement.class) == null;
}
private static boolean seemsToBeQualifiedClassName(@Nullable GrExpression qualifier) {
if (qualifier == null) return false;
while (qualifier instanceof GrReferenceExpression) {
final PsiElement nameElement = ((GrReferenceExpression)qualifier).getReferenceNameElement();
if (((GrReferenceExpression)qualifier).getTypeArguments().length > 0) return false;
public static boolean seemsToBeQualifiedClassName(@Nullable GrExpression expr) {
if (expr == null) return false;
while (expr instanceof GrReferenceExpression) {
final PsiElement nameElement = ((GrReferenceExpression)expr).getReferenceNameElement();
if (((GrReferenceExpression)expr).getTypeArguments().length > 0) return false;
if (nameElement == null || nameElement.getNode().getElementType() != GroovyTokenTypes.mIDENT) return false;
IElementType dotType = ((GrReferenceExpression)qualifier).getDotTokenType();
IElementType dotType = ((GrReferenceExpression)expr).getDotTokenType();
if (dotType != null && dotType != GroovyTokenTypes.mDOT) return false;
qualifier = ((GrReferenceExpression)qualifier).getQualifierExpression();
expr = ((GrReferenceExpression)expr).getQualifierExpression();
}
return qualifier == null;
return expr == null;
}
}
@@ -35,7 +35,13 @@ public abstract class GrIntentionTestCase extends LightCodeInsightFixtureTestCas
myFixture.checkResultByFile(getTestName(false) + "_after.groovy");
}
else {
assertEquals("Count of enabled intentions: ", 0, list.size());
if (list.size() > 0) {
StringBuilder text = new StringBuilder("available intentions:");
for (IntentionAction intentionAction : list) {
text.append(intentionAction.getFamilyName()).append(", ");
}
fail(text.toString());
}
}
}
}
@@ -0,0 +1,51 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.intentions
import org.jetbrains.plugins.groovy.util.TestUtils
/**
* @author Max Medvedev
*/
public class ReplaceQualifiedReferenceWithImportTest extends GrIntentionTestCase {
@Override
protected String getBasePath() {
"${TestUtils.testDataPath}intentions/replaceQualifiedReferenceWithImport/"
}
private doTest(boolean intentionExists) {
myFixture.addClass('package p1; public class X{}')
myFixture.addClass('package p2; public class X{}')
doTest(GroovyIntentionsBundle.message('replace.qualified.reference.with.import.intention.name'), intentionExists)
}
void testSimple() {
doTest(true)
}
void testCan() {
doTest(true)
}
void testCannot1() {
doTest(false)
}
void testCannot2() {
doTest(false)
}
}
@@ -0,0 +1,3 @@
print p1.X
print p2.<caret>X
@@ -0,0 +1,5 @@
import p2.X
print p1.X
print <caret>X
@@ -0,0 +1,3 @@
import p1.X
print p2.<caret>X
@@ -0,0 +1,3 @@
def X = 5
print p2.<caret>X
@@ -0,0 +1 @@
print p<caret>1.X
@@ -0,0 +1,3 @@
import p1.X
print X