Merge remote-tracking branch 'origin/master'

This commit is contained in:
Yann Cébron
2012-09-13 15:22:21 +02:00
34 changed files with 606 additions and 278 deletions
+4
View File
@@ -578,6 +578,10 @@
<inspection_tool class="UnnecessaryLabelOnBreakStatementJS" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="UnnecessaryLabelOnContinueStatement" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="UnnecessaryLabelOnContinueStatementJS" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="UnnecessaryLocalVariable" enabled="true" level="WARNING" enabled_by_default="true">
<option name="m_ignoreImmediatelyReturnedVariables" value="false" />
<option name="m_ignoreAnnotatedVariables" value="true" />
</inspection_tool>
<inspection_tool class="UnnecessaryLocalVariableJS" enabled="false" level="WARNING" enabled_by_default="false">
<option name="m_ignoreImmediatelyReturnedVariables" value="false" />
<option name="m_ignoreAnnotatedVariables" value="false" />
@@ -780,6 +780,10 @@
<inspection_tool class="UnnecessaryLabelOnBreakStatementJS" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="UnnecessaryLabelOnContinueStatement" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="UnnecessaryLabelOnContinueStatementJS" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="UnnecessaryLocalVariable" enabled="true" level="WARNING" enabled_by_default="true">
<option name="m_ignoreImmediatelyReturnedVariables" value="false" />
<option name="m_ignoreAnnotatedVariables" value="true" />
</inspection_tool>
<inspection_tool class="UnnecessaryLocalVariableJS" enabled="false" level="WARNING" enabled_by_default="false">
<option name="m_ignoreImmediatelyReturnedVariables" value="false" />
<option name="m_ignoreAnnotatedVariables" value="false" />
@@ -533,7 +533,19 @@ public class OverrideImplementUtil {
ApplicationManager.getApplication().assertReadAccessAllowed();
Collection<CandidateInfo> candidates = getMethodsToOverrideImplement(aClass, toImplement);
Collection<CandidateInfo> secondary = toImplement || aClass.isInterface() ? Collections.<CandidateInfo>emptyList() : getMethodsToOverrideImplement(aClass, true);
Collection<CandidateInfo> secondary = toImplement || aClass.isInterface() ?
ContainerUtil.<CandidateInfo>newArrayList() : getMethodsToOverrideImplement(aClass, true);
if (toImplement && PsiUtil.isLanguageLevel8OrHigher(aClass)) {
for (Iterator<CandidateInfo> iterator = candidates.iterator(); iterator.hasNext(); ) {
CandidateInfo candidate = iterator.next();
PsiElement element = candidate.getElement();
if (element instanceof PsiMethod && PsiUtil.isExtensionMethod((PsiMethod)element)) {
iterator.remove();
secondary.add(candidate);
}
}
}
final MemberChooser<PsiMethodMember> chooser = showOverrideImplementChooser(editor, aClass, toImplement, candidates, secondary);
if (chooser == null) return;
@@ -563,7 +575,7 @@ public class OverrideImplementUtil {
final Ref<Boolean> merge = Ref.create(PropertiesComponent.getInstance(project).isTrueValue(PROP_COMBINED_OVERRIDE_IMPLEMENT));
final MemberChooser<PsiMethodMember> chooser =
new MemberChooser<PsiMethodMember>(merge.get() ? all : onlyPrimary, false, true, project, PsiUtil.isLanguageLevel5OrHigher(aClass)) {
new MemberChooser<PsiMethodMember>(toImplement || merge.get() ? all : onlyPrimary, false, true, project, PsiUtil.isLanguageLevel5OrHigher(aClass)) {
@Override
protected void fillToolbarActions(DefaultActionGroup group) {
super.fillToolbarActions(group);
@@ -597,11 +609,13 @@ public class OverrideImplementUtil {
chooser.setCopyJavadocVisible(true);
if (toImplement) {
chooser.selectElements((boolean)merge.get() ? all : onlyPrimary);
chooser.selectElements(onlyPrimary);
}
if (ApplicationManager.getApplication().isUnitTestMode()) {
chooser.selectElements(all);
if (!toImplement) {
chooser.selectElements(all);
}
chooser.close(DialogWrapper.OK_EXIT_CODE);
return chooser;
}
@@ -32,6 +32,10 @@ public class TypesDistinctProver {
}
public static boolean provablyDistinct(PsiType type1, PsiType type2) {
return provablyDistinct(type1, type2, 0);
}
private static boolean provablyDistinct(PsiType type1, PsiType type2, int level) {
if (type1 instanceof PsiClassType && ((PsiClassType)type1).resolve() instanceof PsiTypeParameter) return false;
if (type2 instanceof PsiClassType && ((PsiClassType)type2).resolve() instanceof PsiTypeParameter) return false;
if (type1 instanceof PsiWildcardType) {
@@ -40,7 +44,7 @@ public class TypesDistinctProver {
}
if (type2 instanceof PsiCapturedWildcardType) {
return ((PsiWildcardType)type1).isExtends() ||
return ((PsiWildcardType)type1).isExtends() && level > 0 ||
provablyDistinct((PsiWildcardType)type1, ((PsiCapturedWildcardType)type2).getWildcard());
}
@@ -75,9 +79,9 @@ public class TypesDistinctProver {
return proveArrayTypeDistinct(((PsiWildcardType)type1).getManager().getProject(), (PsiArrayType)type2, type1);
}
}
if (type1 instanceof PsiCapturedWildcardType) return provablyDistinct(((PsiCapturedWildcardType)type1).getWildcard(), type2);
if (type1 instanceof PsiCapturedWildcardType) return provablyDistinct(((PsiCapturedWildcardType)type1).getWildcard(), type2, level +1);
if (type2 instanceof PsiWildcardType || type2 instanceof PsiCapturedWildcardType) return provablyDistinct(type2, type1);
if (type2 instanceof PsiWildcardType || type2 instanceof PsiCapturedWildcardType) return provablyDistinct(type2, type1, level +1);
final PsiClassType.ClassResolveResult classResolveResult1 = PsiUtil.resolveGenericsClassInType(type1);
@@ -94,7 +98,7 @@ public class TypesDistinctProver {
if (!TypeConversionUtil.isAssignable(type, substitutedType1 != null ? substitutedType1 : substitutedType2, false)) return true;
}
} else {
if (provablyDistinct(substitutedType1, substitutedType2)) return true;
if (provablyDistinct(substitutedType1, substitutedType2, level + 1)) return true;
if (substitutedType1 instanceof PsiWildcardType && !((PsiWildcardType)substitutedType1).isBounded()) return true;
}
}
@@ -121,7 +125,7 @@ public class TypesDistinctProver {
if (boundClass1 != null && boundClass2 != null) {
return proveExtendsBoundsDistinct(type1, type2, boundClass1, boundClass2);
}
return provablyDistinct(extendsBound1, extendsBound2);
return provablyDistinct(extendsBound1, extendsBound2, 1);
}
if (type2.isExtends()) return provablyDistinct(type2, type1);
if (type1.isExtends() && type2.isSuper()) {
@@ -216,4 +216,19 @@ class IDEA73377 {
//noinspection unchecked
return <error descr="Inconvertible types; cannot cast 'java.util.Iterator<java.util.Map.Entry<capture<?>,capture<?>>>' to 'java.util.Iterator<java.util.Map.Entry<java.util.Map.Entry<?,?>,?>>'">(Iterator<Map.Entry<Map.Entry<?, ?>, ?>>)map.entrySet().iterator()</error>;
}
}
class IDEA91481 {
void bar(){
BeanBuilder<? extends DirectBean> builder = <warning descr="Unchecked cast: 'IDEA91481.BeanBuilder<capture<? extends IDEA91481.Bean>>' to 'IDEA91481.BeanBuilder<? extends IDEA91481.DirectBean>'">(BeanBuilder<? extends DirectBean>) builder()</warning>;
System.out.println(builder);
}
BeanBuilder<? extends Bean> builder() {
return null;
}
class BeanBuilder<<warning descr="Type parameter 'T' is never used">T</warning>> {}
class Bean {}
class DirectBean extends Bean {}
}
@@ -0,0 +1,17 @@
class Test {
interface A<T> {
void m1(T t);
void m2();
}
interface B<T> extends A<T> {
void m1(T t) default { }
}
class MyClass<T> implements B<T> {
@Override
public void m2() {
<selection>//To change body of implemented methods use File | Settings | File Templates.</selection>
}
}
}
@@ -0,0 +1,14 @@
class Test {
interface A<T> {
void m1(T t);
void m2();
}
interface B<T> extends A<T> {
void m1(T t) default { }
}
class MyClass<T> implements B<T> {
<caret>
}
}
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2012 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 com.intellij.codeInsight;
import com.intellij.codeInsight.generation.OverrideImplementUtil;
@@ -13,45 +28,47 @@ import com.intellij.psi.util.MethodSignature;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.util.Function;
import com.intellij.util.FunctionUtil;
import com.intellij.util.containers.ContainerUtil;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* @author ven
*/
public class OverrideImplementTest extends LightCodeInsightTestCase {
private static final String BASE_DIR = "/codeInsight/overrideImplement/";
@Override
protected void setUp() throws Exception {
super.setUp();
setLanguageLevel(LanguageLevel.JDK_1_5);
}
public void testSimple() throws Exception { doTest(true); }
public void testAnnotation() throws Exception { doTest(true); }
public void testIncomplete() throws Exception { doTest(false); }
public void testSubstitutionInTypeParametersList() throws Exception { doTest(false); }
public void testTestMissed() throws Exception { doTest(false); }
public void testWildcard() throws Exception { doTest(false); }
public void testTypeParam() throws Exception { doTest(false); }
public void testInterfaceAndAbstractClass() throws Exception { doTest(false); }
public void testRawSuper() throws Exception { doTest(false); }
public void testSubstituteBoundInMethodTypeParam() throws Exception { doTest(false); }
public void testSimple() { doTest(true); }
public void testAnnotation() { doTest(true); }
public void testIncomplete() { doTest(false); }
public void testSubstitutionInTypeParametersList() { doTest(false); }
public void testTestMissed() { doTest(false); }
public void testWildcard() { doTest(false); }
public void testTypeParam() { doTest(false); }
public void testInterfaceAndAbstractClass() { doTest(false); }
public void testRawSuper() { doTest(false); }
public void testSubstituteBoundInMethodTypeParam() { doTest(false); }
public void testClone() { doTest(false); }
public void testOnTheLineWithExistingExpression() { doTest(false); }
public void testLongFinalParameterList() throws Exception {
public void testLongFinalParameterList() {
CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(getProject()).clone();
try {
CommonCodeStyleSettings javaSettings = codeStyleSettings.getCommonSettings(JavaLanguage.INSTANCE);
codeStyleSettings.RIGHT_MARGIN = 80;
javaSettings.KEEP_LINE_BREAKS = true;
codeStyleSettings.GENERATE_FINAL_PARAMETERS = true;
javaSettings.METHOD_PARAMETERS_WRAP = CommonCodeStyleSettings.WRAP_ON_EVERY_ITEM;
CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(codeStyleSettings);
doTest(false);
}
finally {
@@ -59,9 +76,8 @@ public class OverrideImplementTest extends LightCodeInsightTestCase {
}
}
public void testLongParameterList() throws Exception {
public void testLongParameterList() {
CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(getProject()).clone();
try {
CommonCodeStyleSettings javaSettings = codeStyleSettings.getCommonSettings(JavaLanguage.INSTANCE);
codeStyleSettings.RIGHT_MARGIN = 80;
@@ -69,7 +85,6 @@ public class OverrideImplementTest extends LightCodeInsightTestCase {
codeStyleSettings.GENERATE_FINAL_PARAMETERS = false;
javaSettings.METHOD_PARAMETERS_WRAP = CommonCodeStyleSettings.WRAP_ON_EVERY_ITEM;
CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(codeStyleSettings);
doTest(false);
}
finally {
@@ -77,34 +92,23 @@ public class OverrideImplementTest extends LightCodeInsightTestCase {
}
}
public void testClone() throws Exception {
doTest(false);
}
public void testOnTheLineWithExistingExpression() throws Exception {
doTest(false);
}
public void testImplementedConstructorsExcluded() throws Exception {
String name = getTestName(false);
configureByFile("/codeInsight/overrideImplement/" + name + ".java");
public void testImplementedConstructorsExcluded() {
configureByFile(BASE_DIR + getTestName(false) + ".java");
int offset = getEditor().getCaretModel().getOffset();
PsiElement context = getFile().findElementAt(offset);
PsiClass psiClass = PsiTreeUtil.getParentOfType(context, PsiClass.class);
assert psiClass != null;
final Collection<MethodSignature> signatures = OverrideImplementUtil.getMethodSignaturesToOverride(psiClass);
final Collection<String> strings = ContainerUtil.map(signatures, new Function<MethodSignature, String>() {
public String fun(MethodSignature signature) { return signature.toString(); }
});
final Collection<String> strings = ContainerUtil.map(signatures, FunctionUtil.string());
assertTrue(strings.toString(), strings.contains("HierarchicalMethodSignatureImpl: A([PsiType:String])"));
assertFalse(strings.toString(), strings.contains("HierarchicalMethodSignatureImpl: A([])"));
}
public void testEnumConstant() throws Exception {
public void testEnumConstant() {
String name = getTestName(false);
configureByFile("/codeInsight/overrideImplement/before" + name + ".java");
configureByFile(BASE_DIR + "before" + name + ".java");
int offset = getEditor().getCaretModel().getOffset();
PsiElement context = getFile().findElementAt(offset);
PsiMethod psiMethod = PsiTreeUtil.getParentOfType(context, PsiMethod.class);
@@ -113,12 +117,24 @@ public class OverrideImplementTest extends LightCodeInsightTestCase {
assert aClass != null && aClass.isEnum();
final PsiField[] fields = aClass.getFields();
new ImplementAbstractMethodHandler(getProject(), getEditor(), psiMethod).implementInClass(fields);
checkResultByFile("/codeInsight/overrideImplement/after" + name + ".java");
checkResultByFile(BASE_DIR + "after" + name + ".java");
}
private void doTest(boolean copyJavadoc) throws Exception {
public void testImplementExtensionMethods() {
setLanguageLevel(LanguageLevel.JDK_1_8);
String name = getTestName(false);
configureByFile("/codeInsight/overrideImplement/before" + name + ".java");
configureByFile(BASE_DIR + "before" + name + ".java");
int offset = getEditor().getCaretModel().getOffset();
PsiElement context = getFile().findElementAt(offset);
PsiClass psiClass = PsiTreeUtil.getParentOfType(context, PsiClass.class);
assert psiClass != null;
OverrideImplementUtil.chooseAndOverrideOrImplementMethods(getProject(), getEditor(), psiClass, true);
checkResultByFile(BASE_DIR + "after" + name + ".java");
}
private void doTest(boolean copyJavadoc) {
String name = getTestName(false);
configureByFile(BASE_DIR + "before" + name + ".java");
int offset = getEditor().getCaretModel().getOffset();
PsiElement context = getFile().findElementAt(offset);
PsiClass psiClass = PsiTreeUtil.getParentOfType(context, PsiClass.class);
@@ -126,12 +142,10 @@ public class OverrideImplementTest extends LightCodeInsightTestCase {
PsiClassType[] implement = psiClass.getImplementsListTypes();
final PsiClass superClass = implement.length == 0 ? psiClass.getSuperClass() : implement[0].resolve();
assert superClass != null;
PsiMethod method = superClass.getMethods()[0];
final PsiMethodMember member2Override = new PsiMethodMember(method,
TypeConversionUtil.getSuperClassSubstitutor(superClass, psiClass,
PsiSubstitutor.EMPTY));
OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(getEditor(), psiClass, Collections.singletonList(member2Override),
copyJavadoc, true);
checkResultByFile("/codeInsight/overrideImplement/after" + name + ".java");
}
PsiMethod method = superClass.getMethods()[0];
final PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, psiClass, PsiSubstitutor.EMPTY);
final List<PsiMethodMember> candidates = Collections.singletonList(new PsiMethodMember(method, substitutor));
OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(getEditor(), psiClass, candidates, copyJavadoc, true);
checkResultByFile(BASE_DIR + "after" + name + ".java");
}
}
@@ -173,6 +173,10 @@ public class HyperlinkLabel extends HighlightableComponent {
}
}
public void doClick() {
fireHyperlinkEvent();
}
public void setHtmlText(String text) {
HTMLEditorKit.Parser parse = new ParserDelegator();
final HighlightedText highlightedText = new HighlightedText();
@@ -41,6 +41,9 @@ import javax.swing.event.HyperlinkEvent;
import java.io.*;
import java.util.*;
import static com.intellij.util.containers.ContainerUtil.newArrayList;
import static com.intellij.util.containers.ContainerUtil.newArrayListWithExpectedSize;
/**
* @author max
*/
@@ -63,17 +66,17 @@ public class FileWatcher {
private final Object LOCK = new Object();
private List<String> myDirtyPaths = new ArrayList<String>();
private List<String> myDirtyRecursivePaths = new ArrayList<String>();
private List<String> myDirtyDirs = new ArrayList<String>();
private List<String> myManualWatchRoots = new ArrayList<String>();
private List<String> myDirtyPaths = newArrayList();
private List<String> myDirtyRecursivePaths = newArrayList();
private List<String> myDirtyDirs = newArrayList();
private final List<Pair<String, String>> myMapping = new ArrayList<Pair<String, String>>();
private List<String> myRecursiveWatchRoots = new ArrayList<String>();
private List<String> myFlatWatchRoots = new ArrayList<String>();
private List<String> myManualWatchRoots = newArrayList();
private List<String> myRecursiveWatchRoots = newArrayList();
private List<String> myFlatWatchRoots = newArrayList();
private final Collection<String> myAllPaths = new ArrayList<String>(2);
private final Collection<String> myWatchedPaths = new ArrayList<String>(2);
private final List<Pair<String, String>> myMapping = newArrayList();
private final Collection<String> myAllPaths = newArrayListWithExpectedSize(2);
private final Collection<String> myWatchedPaths = newArrayListWithExpectedSize(2);
private File executable;
private volatile Process notifierProcess;
@@ -24,7 +24,6 @@ import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileVisitor;
import com.intellij.testFramework.LightPlatformLangTestCase;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashSet;
@@ -37,29 +36,8 @@ import java.util.Set;
import static com.intellij.openapi.util.io.FileUtil.createTempDirectory;
import static com.intellij.openapi.util.io.FileUtil.createTempFile;
import static com.intellij.openapi.util.io.IoTestUtil.createTempLink;
import static com.intellij.openapi.util.io.IoTestUtil.createTestDir;
public class SymlinkHandlingTest extends LightPlatformLangTestCase {
private LocalFileSystem myFileSystem;
private File myTempDir;
@Override
protected void setUp() throws Exception {
super.setUp();
myFileSystem = LocalFileSystem.getInstance();
myTempDir = createTestDir("temp");
}
@Override
protected void runTest() throws Throwable {
if (SystemInfo.areSymLinksSupported) {
super.runTest();
}
else {
System.err.println("Skipped: " + getName());
}
}
public class SymlinkHandlingTest extends SymlinkTestCase {
public void testMissingLink() throws Exception {
final File missingFile = new File(myTempDir, "missing_file");
assertTrue(missingFile.getPath(), !missingFile.exists() || missingFile.delete());
@@ -357,13 +335,6 @@ public class SymlinkHandlingTest extends LightPlatformLangTestCase {
return myFileSystem.findFileByPath(ioFile.getPath());
}
private void refresh() {
final String tempPath = FileUtil.getTempDirectory();
final VirtualFile tempDir = myFileSystem.findFileByPath(tempPath);
assertNotNull(tempPath, tempDir);
tempDir.refresh(false, true);
}
private static void assertBrokenLink(@NotNull final VirtualFile link) {
assertTrue(link.isSymLink());
assertEquals(0, link.getLength());
@@ -0,0 +1,74 @@
/*
* Copyright 2000-2012 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 com.intellij.openapi.vfs.local;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.IoTestUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileVisitor;
import com.intellij.testFramework.LightPlatformLangTestCase;
import java.io.File;
import static com.intellij.openapi.util.io.IoTestUtil.createTestDir;
public abstract class SymlinkTestCase extends LightPlatformLangTestCase {
protected LocalFileSystem myFileSystem;
protected File myTempDir;
@Override
protected void setUp() throws Exception {
super.setUp();
myFileSystem = LocalFileSystem.getInstance();
myTempDir = createTestDir("temp");
}
@Override
protected void tearDown() throws Exception {
try {
IoTestUtil.delete(myTempDir);
}
finally {
super.tearDown();
}
}
@Override
protected void runTest() throws Throwable {
if (SystemInfo.areSymLinksSupported) {
super.runTest();
}
else {
System.err.println("Skipped: " + getName());
}
}
protected void refresh() {
refresh(false);
}
protected void refresh(boolean recursive) {
final VirtualFile tempDir = myFileSystem.findFileByIoFile(myTempDir);
assertNotNull(myTempDir.getPath(), tempDir);
tempDir.getChildren();
tempDir.refresh(false, true);
if (recursive) {
VfsUtilCore.visitChildrenRecursively(tempDir, new VirtualFileVisitor() { });
}
}
}
@@ -25,19 +25,21 @@ import java.util.Collection;
public interface Function<Param, Result> {
Result fun(Param param);
/**
* @see FunctionUtil#id()
*/
Function ID = new Function() {
public Object fun(final Object o) {
return o;
}
};
/**
* @see FunctionUtil#nullConstant()
*/
Function NULL = NullableFunction.NULL;
Function TO_STRING = new Function() {
@Override
public Object fun(Object o) {
return String.valueOf(o);
}
};
final class Self<P, R> implements Function<P, R> {
@Override
public R fun(P p) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -21,20 +21,27 @@ import org.jetbrains.annotations.NotNull;
* @author nik
*/
public class FunctionUtil {
private FunctionUtil() {
}
private FunctionUtil() { }
@NotNull
public static <T> Function<T, T> id() {
//noinspection unchecked
return Function.ID;
@SuppressWarnings("unchecked") Function<T, T> id = Function.ID;
return id;
}
@NotNull
public static <A, B> NullableFunction<A, B> nullConstant() {
//noinspection unchecked
return NullableFunction.NULL;
@SuppressWarnings("unchecked") NullableFunction<A, B> function = NullableFunction.NULL;
return function;
}
@NotNull
public static <T> Function<T, String> string() {
@SuppressWarnings("unchecked") Function<T, String> function = Function.TO_STRING;
return function;
}
@NotNull
public static <A, B> Function<A, B> constant(final B b) {
return new Function<A, B>() {
@Override
@@ -54,5 +61,4 @@ public class FunctionUtil {
}
};
}
}
@@ -231,4 +231,12 @@ public class IoTestUtil {
assertTrue(file.getPath(), file.createNewFile());
return file;
}
public static void delete(final File... files) {
for (File file : files) {
if (file != null) {
FileUtil.delete(file);
}
}
}
}
@@ -37,6 +37,7 @@ import com.intellij.openapi.vcs.changes.conflicts.ChangelistConflictTracker;
import com.intellij.openapi.vcs.changes.ui.CommitHelper;
import com.intellij.openapi.vcs.checkin.CheckinEnvironment;
import com.intellij.openapi.vcs.checkin.CheckinHandler;
import com.intellij.openapi.vcs.impl.AbstractVcsHelperImpl;
import com.intellij.openapi.vcs.impl.ContentRevisionCache;
import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl;
import com.intellij.openapi.vcs.impl.VcsInitObject;
@@ -631,21 +632,7 @@ public class ChangeListManagerImpl extends ChangeListManagerEx implements Projec
changeProvider.getChanges(scope, builder, myUpdateChangesProgressIndicator, gate);
}
catch (final VcsException e) {
LOG.info(e);
if (e instanceof VcsConnectionProblem) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
((VcsConnectionProblem)e).attemptQuickFix(false);
}
});
}
if (myUpdateException == null) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
e.printStackTrace();
}
myUpdateException = e;
}
handleUpdateException(e);
}
}
} catch (Throwable t) {
@@ -658,6 +645,31 @@ public class ChangeListManagerImpl extends ChangeListManagerEx implements Projec
}
}
private void handleUpdateException(final VcsException e) {
LOG.info(e);
if (e instanceof VcsConnectionProblem) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
((VcsConnectionProblem)e).attemptQuickFix(false);
}
});
}
if (myUpdateException == null) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
AbstractVcsHelper helper = AbstractVcsHelper.getInstance(myProject);
if (helper instanceof AbstractVcsHelperImpl && ((AbstractVcsHelperImpl)helper).handleCustom(e)) {
return;
}
//noinspection CallToPrintStackTrace
e.printStackTrace();
}
myUpdateException = e;
}
}
private void checkIfDisposed() {
if (myUpdater.isStopped()) throw new DisposedException();
}
@@ -15,6 +15,7 @@
*/
package com.intellij.openapi.vcs.changes.committed;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
@@ -30,6 +31,10 @@ import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager;
* Time: 4:53 PM
*/
public class ClearCommittedAction extends AnAction implements DumbAware {
public ClearCommittedAction() {
super("Clear", "Clears cached revisions", AllIcons.Vcs.Remove);
}
public void actionPerformed(AnActionEvent e) {
Project project = e.getData(PlatformDataKeys.PROJECT);
CommittedChangesPanel panel = ChangesViewContentManager.getInstance(project).getActiveComponent(CommittedChangesPanel.class);
@@ -193,7 +193,7 @@ public class CommittedChangesPanel extends JPanel implements TypeSafeDataProvide
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
updateFilteredModel(Collections.<CommittedChangeList>emptyList());
updateFilteredModel(Collections.<CommittedChangeList>emptyList(), true);
}
}, ModalityState.NON_MODAL, myProject.getDisposed());
}
@@ -214,7 +214,7 @@ public class CommittedChangesPanel extends JPanel implements TypeSafeDataProvide
cache.getProjectChangesAsync(mySettings, myMaxCount, cacheOnly,
new Consumer<List<CommittedChangeList>>() {
public void consume(final List<CommittedChangeList> committedChangeLists) {
updateFilteredModel(committedChangeLists);
updateFilteredModel(committedChangeLists, false);
}
},
new Consumer<List<VcsException>>() {
@@ -254,11 +254,17 @@ public class CommittedChangesPanel extends JPanel implements TypeSafeDataProvide
}
}
private void updateFilteredModel(List<CommittedChangeList> committedChangeLists) {
private void updateFilteredModel(List<CommittedChangeList> committedChangeLists, final boolean reset) {
if (committedChangeLists == null) {
return;
}
myBrowser.getEmptyText().setText(VcsBundle.message("committed.changes.empty.message"));
final String emptyText;
if (reset) {
emptyText = VcsBundle.message("committed.changes.not.loaded.message");
} else {
emptyText = VcsBundle.message("committed.changes.empty.message");
}
myBrowser.getEmptyText().setText(emptyText);
myBrowser.setItems(committedChangeLists, CommittedChangesBrowserUseCase.COMMITTED);
}
@@ -92,12 +92,7 @@ public class AbstractVcsHelperImpl extends AbstractVcsHelper {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.impl.AbstractVcsHelperImpl");
private final Project myProject;
private Consumer<VcsException> myCustomHandler = new Consumer<VcsException>() {
@Override
public void consume(VcsException e) {
throw new RuntimeException(e);
}
};
private Consumer<VcsException> myCustomHandler = null;
public AbstractVcsHelperImpl(Project project) {
myProject = project;
@@ -256,7 +251,10 @@ public class AbstractVcsHelperImpl extends AbstractVcsHelper {
final Consumer<VcsErrorViewPanel> viewFiller) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
if (!isEmpty) {
myCustomHandler.consume(firstGetter.get());
VcsException exception = firstGetter.get();
if (!handleCustom(exception)) {
throw new RuntimeException(exception);
}
}
return;
}
@@ -276,6 +274,14 @@ public class AbstractVcsHelperImpl extends AbstractVcsHelper {
});
}
public boolean handleCustom(VcsException exception) {
if (myCustomHandler != null) {
myCustomHandler.consume(exception);
return true;
}
return false;
}
@Override
public void showErrors(final Map<HotfixData, List<VcsException>> exceptionGroups, @NotNull final String tabDisplayName) {
showErrorsImpl(exceptionGroups.isEmpty(), new Getter<VcsException>() {
@@ -24,7 +24,10 @@ import org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle;
import org.jetbrains.plugins.groovy.intentions.base.Intention;
import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrTupleDeclaration;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
@@ -35,40 +38,84 @@ import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringUtil;
* @author Max Medvedev
*/
public class GrSplitDeclarationIntention extends Intention {
@Override
protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException {
if (element instanceof GrVariableDeclaration) {
GrVariable[] variables = ((GrVariableDeclaration)element).getVariables();
if (variables.length == 1) {
GrVariable var = variables[0];
GrExpression initializer = var.getInitializerGroovy();
if (initializer != null) {
GrExpression assignment = GroovyPsiElementFactory.getInstance(project)
.createExpressionFromText(var.getName() + " = " + initializer.getText());
initializer.delete();
element = GroovyRefactoringUtil.addBlockIntoParent(element);
element.getParent().addAfter(assignment, element);
}
if (!(element instanceof GrVariableDeclaration)) return;
GrVariableDeclaration declaration = (GrVariableDeclaration)element;
GrVariable[] variables = declaration.getVariables();
if (variables.length == 1) {
processSingleVar(project, declaration, variables[0]);
}
else if (variables.length > 1) {
GrTupleDeclaration tuple = declaration.getTupleDeclaration();
if (tuple == null || tuple.getInitializerGroovy() instanceof GrListOrMap) {
processMultipleVars(project, declaration);
}
else if (variables.length > 1) {
String modifiers = ((GrVariableDeclaration)element).getModifierList().getText();
GrStatement[] sts = new GrStatement[variables.length];
for (int i = 0; i < variables.length; i++) {
sts[i] = createVarDeclaration(project, variables[i], modifiers);
}
element = GroovyRefactoringUtil.addBlockIntoParent(element);
for (int i = sts.length - 1; i >= 0; i--) {
element.getParent().addAfter(sts[i], element);
}
element.delete();
else {
processTuple(project, declaration);
}
}
}
private static GrStatement createVarDeclaration(Project project, GrVariable variable, String modifiers) {
private static void processTuple(Project project, GrVariableDeclaration declaration) {
GrTupleDeclaration tuple = declaration.getTupleDeclaration();
assert tuple != null;
GrExpression initializer = tuple.getInitializerGroovy();
assert initializer != null;
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
GrVariable[] variables = declaration.getVariables();
StringBuilder assignmentBuilder = new StringBuilder();
assignmentBuilder.append('(');
for (GrVariable variable : variables) {
assignmentBuilder.append(variable.getName()).append(',');
}
assignmentBuilder.replace(assignmentBuilder.length() - 1, assignmentBuilder.length(), ")=");
assignmentBuilder.append(initializer.getText());
GrStatement assignment = factory.createStatementFromText(assignmentBuilder.toString());
declaration = GroovyRefactoringUtil.addBlockIntoParent(declaration);
declaration.getParent().addAfter(assignment, declaration);
initializer.delete();
}
private static void processMultipleVars(Project project, GrVariableDeclaration declaration) {
GrVariable[] variables = declaration.getVariables();
String modifiers = declaration.getModifierList().getText();
GrStatement[] sts = new GrStatement[variables.length];
for (int i = 0; i < variables.length; i++) {
sts[i] = createVarDeclaration(project, variables[i], modifiers, declaration.getTupleDeclaration() != null);
}
declaration = GroovyRefactoringUtil.addBlockIntoParent(declaration);
for (int i = sts.length - 1; i >= 0; i--) {
declaration.getParent().addAfter(sts[i], declaration);
}
declaration.delete();
}
private static void processSingleVar(Project project, GrVariableDeclaration declaration, GrVariable variable) {
GrExpression initializer = variable.getInitializerGroovy();
if (initializer != null) {
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
GrExpression assignment = factory.createExpressionFromText(variable.getName() + " = " + initializer.getText());
initializer.delete();
declaration = GroovyRefactoringUtil.addBlockIntoParent(declaration);
declaration.getParent().addAfter(assignment, declaration);
}
}
private static GrStatement createVarDeclaration(Project project, GrVariable variable, String modifiers, boolean isTuple) {
StringBuilder builder = new StringBuilder();
builder.append(modifiers).append(' ');
GrTypeElement typeElement = variable.getTypeElementGroovy();
@@ -80,7 +127,12 @@ public class GrSplitDeclarationIntention extends Intention {
if (initializer != null) {
builder.append('=').append(initializer.getText());
}
return GroovyPsiElementFactory.getInstance(project).createStatementFromText(builder.toString());
GrVariableDeclaration var =
(GrVariableDeclaration)GroovyPsiElementFactory.getInstance(project).createStatementFromText(builder.toString());
if (isTuple && (variable.getDeclaredType() != null || var.getModifierList().getModifiers().length > 1)) {
((GrVariableDeclaration)var).getModifierList().setModifierProperty(GrModifier.DEF, false);
}
return var;
}
private String myText = "";
@@ -100,7 +152,13 @@ public class GrSplitDeclarationIntention extends Intention {
if (element instanceof GrVariableDeclaration) {
GrVariable[] variables = ((GrVariableDeclaration)element).getVariables();
if (variables.length > 1 && GroovyRefactoringUtil.isLocalVariable(variables[0])) {
myText = GroovyIntentionsBundle.message("split.into.separate.declaration");
GrTupleDeclaration tuple = ((GrVariableDeclaration)element).getTupleDeclaration();
if (tuple == null || tuple.getInitializerGroovy() instanceof GrListOrMap) {
myText = GroovyIntentionsBundle.message("split.into.separate.declaration");
}
else {
myText = GroovyIntentionsBundle.message("split.into.declaration.and.assignment");
}
return true;
}
else if (variables.length == 1 &&
@@ -48,8 +48,8 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAn
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement;
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction;
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil;
import org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeInferenceHelper;
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil;
import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames;
@@ -443,13 +443,24 @@ public class GroovyExpectedTypesProvider {
public void visitAssignmentExpression(GrAssignmentExpression expression) {
GrExpression rValue = expression.getRValue();
GrExpression lValue = expression.getLValue();
if (myExpression.equals(rValue)) {
PsiType lType = expression.getLValue().getType();
PsiType lType = lValue.getNominalType();
if (lType != null) {
myResult = new TypeConstraint[]{SubtypeConstraint.create(lType)};
}
else if (lValue instanceof GrReferenceExpression) {
GroovyResolveResult result = ((GrReferenceExpression)lValue).advancedResolve();
PsiElement resolved = result.getElement();
if (resolved instanceof GrVariable) {
PsiType type = ((GrVariable)resolved).getTypeGroovy();
if (type != null) {
myResult = new TypeConstraint[]{SubtypeConstraint.create(result.getSubstitutor().substitute(type))};
}
}
}
}
else if (myExpression.equals(expression.getLValue())) {
else if (myExpression.equals(lValue)) {
if (rValue != null) {
PsiType rType = rValue.getType();
if (rType != null) {
@@ -317,7 +317,7 @@ public abstract class GrVariableBaseImpl<T extends StubElement> extends GrStubEl
public void deleteChildInternal(@NotNull ASTNode child) {
final PsiElement psi = child.getPsi();
if (psi == getInitializerGroovy()) {
deleteChildInternal(findChildByType(GroovyTokenTypes.mASSIGN).getNode());
deleteChildInternal(findNotNullChildByType(GroovyTokenTypes.mASSIGN).getNode());
}
super.deleteChildInternal(child);
}
@@ -14,6 +14,7 @@ import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.GrReferenceAdjuster;
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes;
import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
@@ -111,6 +112,16 @@ public abstract class GrVariableDeclarationBase extends GrStubElementBase<EmptyS
return findChildByClass(GrTupleDeclaration.class);
}
@Override
public void deleteChildInternal(@NotNull ASTNode child) {
final PsiElement psi = child.getPsi();
GrTupleDeclaration tuple = getTupleDeclaration();
if (tuple != null && psi == tuple.getInitializerGroovy()) {
deleteChildInternal(findNotNullChildByType(GroovyTokenTypes.mASSIGN).getNode());
}
super.deleteChildInternal(child);
}
@Override
public GrTypeElement getTypeElementGroovyForVariable(GrVariable var) {
if (!isTuple()) {
@@ -26,11 +26,12 @@ import org.jetbrains.plugins.groovy.util.TestUtils
public class AddConstructorMatchingSuperTest extends GrIntentionTestCase {
private static final String HINT = "Create constructor matching super"
@Override
protected String getBasePath() {
return "${TestUtils.testDataPath}intentions/constructorMatchingSuper/"
AddConstructorMatchingSuperTest() {
super(HINT)
}
final String basePath = TestUtils.testDataPath + 'intentions/constructorMatchingSuper/'
void testGroovyToGroovy() {
doTextTest('''\
class Base {
@@ -39,7 +40,7 @@ class Base {
class Derived exten<caret>ds Base {
}
''', HINT, '''\
''', '''\
class Base {
Base(int p, @Anno int x) throws Exception {}
}
@@ -61,7 +62,7 @@ class Base {
doTextTest('''\
class Derived exten<caret>ds Base {
}
''', HINT, '''\
''', '''\
class Derived extends Base {
<caret>def Derived(int p, @Anno int x) throws Exception {
super(p, x)
@@ -21,24 +21,25 @@ import org.jetbrains.plugins.groovy.util.TestUtils;
* @author Max Medvedev
*/
public class AddReturnTypeFixTest extends GrIntentionTestCase {
@Override
protected String getBasePath() {
return "${TestUtils.testDataPath}intentions/addReturnType/";
AddReturnTypeFixTest() {
super('Add return type')
}
final String basePath = TestUtils.testDataPath + 'intentions/addReturnType/'
void testSimple() {
doTextTest('def f<caret>oo() {}', 'Add return type', 'def void f<caret>oo() {}')
doTextTest('def f<caret>oo() {}', 'def void f<caret>oo() {}')
}
void testTypePrams() {
doTextTest('def <T> f<caret>oo() {}', 'Add return type', 'def <T> void f<caret>oo() {}')
doTextTest('def <T> f<caret>oo() {}', 'def <T> void f<caret>oo() {}')
}
void testReturnPrimitive() {
doTextTest('def foo() {re<caret>turn 2}', 'Add return type', 'def int foo() {re<caret>turn 2}')
doTextTest('def foo() {re<caret>turn 2}', 'def int foo() {re<caret>turn 2}')
}
void testReturn() {
doTextTest('def foo() {re<caret>turn "2"}', 'Add return type', 'def String foo() {re<caret>turn "2"}')
doTextTest('def foo() {re<caret>turn "2"}', 'def String foo() {re<caret>turn "2"}')
}
}
@@ -33,49 +33,44 @@ import org.jetbrains.plugins.groovy.util.TestUtils
* @author Maxim.Medvedev
*/
public class ConvertConcatenationToGstringTest extends GrIntentionTestCase {
private static final String CONVERT_TO_GSTRING = "Convert to GString";
ConvertConcatenationToGstringTest() {
super("Convert to GString")
}
@NotNull
@Override
protected LightProjectDescriptor getProjectDescriptor() {
return new DefaultLightProjectDescriptor() {
@Override
public void configureModule(Module module, ModifiableRootModel model, ContentEntry contentEntry) {
final Library.ModifiableModel modifiableModel = model.moduleLibraryTable.createLibrary("GROOVY").modifiableModel;
final VirtualFile groovyJar = JarFileSystem.instance.refreshAndFindFileByPath(TestUtils.mockGroovy1_7LibraryName + "!/");
modifiableModel.addRoot(groovyJar, OrderRootType.CLASSES);
modifiableModel.commit();
}
};
final LightProjectDescriptor projectDescriptor = new DefaultLightProjectDescriptor() {
@Override
public void configureModule(Module module, ModifiableRootModel model, ContentEntry contentEntry) {
final Library.ModifiableModel modifiableModel = model.moduleLibraryTable.createLibrary("GROOVY").modifiableModel;
final VirtualFile groovyJar = JarFileSystem.instance.refreshAndFindFileByPath(TestUtils.mockGroovy1_7LibraryName + "!/");
modifiableModel.addRoot(groovyJar, OrderRootType.CLASSES);
modifiableModel.commit();
}
}
final String basePath = TestUtils.testDataPath + 'intentions/convertConcatenationToGstring/'
public void testSimpleCase() {
doTest(true);
}
@Override
protected String getBasePath() {
return "${TestUtils.testDataPath}intentions/convertConcatenationToGstring/";
public void testVeryComplicatedCase() {
doTest(true);
}
public void testSimpleCase() throws Exception {
doTest(CONVERT_TO_GSTRING, true);
public void testQuotes() {
doTest(true);
}
public void testVeryComplicatedCase() throws Exception {
doTest(CONVERT_TO_GSTRING, true);
public void testQuotes2() {
doTest(true);
}
public void testQuotes() throws Exception {
doTest(CONVERT_TO_GSTRING, true);
}
public void testQuotes2() throws Exception {
doTest(CONVERT_TO_GSTRING, true);
}
public void testQuotesInMultilineString() throws Exception {
doTest(CONVERT_TO_GSTRING, true);
public void testQuotesInMultilineString() {
doTest(true);
}
public void testDot() {
doTest(CONVERT_TO_GSTRING, true);
doTest(true);
}
}
@@ -64,7 +64,7 @@ public class ConvertMapToClassTest extends GrIntentionTestCase {
doTest(true);
}
private void doTest(boolean exists) {
protected void doTest(boolean exists) {
myFixture.configureByFile(getTestName(true) + "/Test.groovy");
String hint = GroovyIntentionsBundle.message("convert.map.to.class.intention.name");
final List<IntentionAction> list = myFixture.filterAvailableIntentions(hint);
@@ -24,8 +24,7 @@ import org.jetbrains.plugins.groovy.intentions.conversions.strings.ConvertString
* @author Max Medvedev
*/
public class ConvertStringToMultilineTest extends LightGroovyTestCase {
@Override
protected String getBasePath() {''}
final String basePath = ''
void testPlainString() {
doTest("print 'ab<caret>c'", "print '''abc'''")
@@ -22,18 +22,20 @@ import org.jetbrains.plugins.groovy.util.TestUtils
* @author Max Medvedev
*/
public class GrBreakStringOnLineBreaksTest extends GrIntentionTestCase {
private static final String message = GroovyIntentionsBundle.message('gr.break.string.on.line.breaks.intention.name')
GrBreakStringOnLineBreaksTest() {
super(GroovyIntentionsBundle.message('gr.break.string.on.line.breaks.intention.name'))
}
final String basePath = TestUtils.testDataPath + "intentions/breakStringOnLineBreaks/"
void testSimple() {
doTextTest('''print 'ab<caret>c\\ncde\'''', message, '''\
doTextTest('''print 'ab<caret>c\\ncde\'''', '''\
print 'abc\\n' +
'cde\'''')
}
void testGString() {
doTextTest('''print "a<caret>\\n$x bc\\n"''', message, '''\
doTextTest('''print "a<caret>\\n$x bc\\n"''', '''\
print "a\\n" +
"$x bc\\n"''')
}
@@ -19,14 +19,27 @@ package org.jetbrains.plugins.groovy.intentions;
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.impl.source.PostprocessReformattingAspect
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import com.intellij.util.Function
import org.jetbrains.annotations.NotNull
import org.jetbrains.annotations.Nullable
/**
* @author Maxim.Medvedev
*/
public abstract class GrIntentionTestCase extends LightCodeInsightFixtureTestCase {
protected void doTest(String hint, boolean intentionExists) {
@Nullable
protected final String myHint;
GrIntentionTestCase(@Nullable String hint = null) {
myHint = hint
}
protected void doTest(@NotNull String hint = myHint, boolean intentionExists) {
assertNotNull(hint)
myFixture.configureByFile(getTestName(false) + ".groovy");
final List<IntentionAction> list = myFixture.filterAvailableIntentions(hint);
if (intentionExists) {
@@ -34,18 +47,13 @@ public abstract class GrIntentionTestCase extends LightCodeInsightFixtureTestCas
PostprocessReformattingAspect.getInstance(project).doPostponedFormatting();
myFixture.checkResultByFile(getTestName(false) + "_after.groovy");
}
else {
if (list.size() > 0) {
StringBuilder text = new StringBuilder("available intentions:");
for (IntentionAction intentionAction : list) {
text.append(intentionAction.familyName).append(", ");
}
fail(text.toString());
}
else if (list.size() > 0) {
fail StringUtil.join(list, {it.familyName} as Function<IntentionAction, String>, ',')
}
}
protected void doTextTest(String before, String hint, String after, Class<? extends LocalInspectionTool>... inspections) {
protected void doTextTest(String before, String hint = myHint, String after, Class<? extends LocalInspectionTool>... inspections) {
assertNotNull(hint)
myFixture.configureByText("a.groovy", before);
myFixture.enableInspections(inspections)
final List<IntentionAction> list = myFixture.filterAvailableIntentions(hint);
@@ -54,7 +62,8 @@ public abstract class GrIntentionTestCase extends LightCodeInsightFixtureTestCas
myFixture.checkResult(after);
}
protected void doAntiTest(String before, String hint, Class<? extends LocalInspectionTool>... inspections) {
protected void doAntiTest(String before, String hint = myHint, Class<? extends LocalInspectionTool>... inspections) {
assertNotNull(hint)
myFixture.configureByText("a.groovy", before);
myFixture.enableInspections(inspections)
assertEmpty(myFixture.filterAvailableIntentions(hint));
@@ -0,0 +1,68 @@
/*
* Copyright 2000-2012 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;
/**
* @author Max Medvedev
*/
public class GrSplitDeclarationTest extends GrIntentionTestCase {
void testSingleVar() {
doTextTest('''\
def abc = 5
''', GroovyIntentionsBundle.message('split.into.declaration.and.assignment'), '''\
def abc
abc = 5
''')
}
void testMultiVar() {
doTextTest('''\
def abc = 5, cde = 7
''', GroovyIntentionsBundle.message('split.into.separate.declaration'), '''\
def abc = 5
def cde = 7
''')
}
void testTupleAssignment() {
doTextTest('''\
def (abc, cde) = foo()
''', GroovyIntentionsBundle.message('split.into.declaration.and.assignment'), '''\
def (abc, cde)
(abc, cde) = foo()
''')
}
void testSimpleTupleAssignment() {
doTextTest('''\
def (abc, cde) = [1, 2]
''', GroovyIntentionsBundle.message('split.into.separate.declaration'), '''\
def abc = 1
def cde = 2
''')
}
void testSimpleTupleAssignmentWithExplicitTypes() {
doTextTest('''\
def (int abc, int cde) = [1, 2]
''', GroovyIntentionsBundle.message('split.into.separate.declaration'), '''\
int abc = 1
int cde = 2
''')
}
}
@@ -5,27 +5,23 @@ package org.jetbrains.plugins.groovy.intentions
*/
class InvertIfTest extends GrIntentionTestCase {
String intentionName = GroovyIntentionsBundle.message("invert.if.intention.name")
InvertIfTest() {
super(GroovyIntentionsBundle.message("invert.if.intention.name"))
}
public void testDoNotTriggerOnIncompleteIf() throws Exception {
public void testDoNotTriggerOnIncompleteIf() {
doAntiTest '''
i<caret>f () {
succes
} else {
no_succes
}
''', intentionName
'''
}
private void doTest(String before, String after) {
doTextTest before, intentionName, after
}
public void testSimpleCondition() throws Exception {
doTest '''
public void testSimpleCondition() {
doTextTest '''
i<caret>f (a) {
succes
} else {
@@ -39,9 +35,9 @@ i<caret>f (a) {
'''
}
public void testCallCondition() throws Exception {
public void testCallCondition() {
doTest '''
doTextTest '''
i<caret>f (func()) {
succes
} else {
@@ -55,8 +51,8 @@ i<caret>f (func()) {
'''
}
public void testComplexCondition() throws Exception {
doTest '''
public void testComplexCondition() {
doTextTest '''
i<caret>f (a && b) {
succes
} else {
@@ -70,8 +66,8 @@ i<caret>f (a && b) {
'''
}
public void testNegatedComplexCondition() throws Exception {
doTest '''
public void testNegatedComplexCondition() {
doTextTest '''
i<caret>f (!(a && b)) {
succes
} else {
@@ -85,8 +81,8 @@ i<caret>f (!(a && b)) {
'''
}
public void testNegatedSimpleCondition() throws Exception {
doTest '''
public void testNegatedSimpleCondition() {
doTextTest '''
i<caret>f (!a) {
succes
} else {
@@ -100,8 +96,8 @@ i<caret>f (!a) {
'''
}
public void testNoElseBlock() throws Exception {
doTest '''
public void testNoElseBlock() {
doTextTest '''
i<caret>f (a) {
succes
}
@@ -112,8 +108,8 @@ i<caret>f (a) {
'''
}
public void testEmptyThenBlockIsRemoved() throws Exception {
doTest '''
public void testEmptyThenBlockIsRemoved() {
doTextTest '''
i<caret>f (a) {
} else {
no_succes
@@ -25,10 +25,7 @@ import org.jetbrains.plugins.groovy.util.TestUtils
class RemoveUnnecessarySemicolonTest extends LightCodeInsightFixtureTestCase {
private static final String hint = GroovyIntentionsBundle.message('remove.unnecessary.semicolons.name');
@Override
protected String getBasePath() {
return "${TestUtils.testDataPath}intentions/removeUnnecessaryBraces/";
}
final String basePath = TestUtils.testDataPath + 'intentions/removeUnnecessaryBraces/'
void testSimpleCase1() {
doTest('print 2;<caret>\nprint 3', 'print 2\nprint 3')
@@ -19,10 +19,11 @@ package org.jetbrains.plugins.groovy.intentions
* @author Andreas Arledal
*/
class ReplaceTernaryWithIfElseTest extends GrIntentionTestCase {
ReplaceTernaryWithIfElseTest() {
super(GroovyIntentionsBundle.message("replace.ternary.with.if.else.intention.name"))
}
String intentionName = GroovyIntentionsBundle.message("replace.ternary.with.if.else.intention.name")
// public void testDoNotTriggerOnIncompleteIf() throws Exception {
// public void testDoNotTriggerOnIncompleteIf() {
// doAntiTest '''
//i<caret>f () {
// succes
@@ -33,20 +34,16 @@ class ReplaceTernaryWithIfElseTest extends GrIntentionTestCase {
//
// }
public void testDoNotTriggerOnIncompleteTernary() throws Exception {
public void testDoNotTriggerOnIncompleteTernary() {
doAntiTest '''
return aaa ? <caret>bbb
''', intentionName
'''
}
private void doTest(String before, String after) {
public void testSimpleCondition() {
doTextTest before, intentionName, after
}
public void testSimpleCondition() throws Exception {
doTest '''
doTextTest '''
return aaa <caret>? bbb : ccc
''', '''\
if (aaa)<caret> {
@@ -57,9 +54,9 @@ if (aaa)<caret> {
'''
}
public void testCaretAfterQuestionMark() throws Exception {
public void testCaretAfterQuestionMark() {
doTest '''
doTextTest '''
return aaa ?<caret> bbb : ccc
''', '''\
if (aaa)<caret> {
@@ -70,9 +67,9 @@ if (aaa)<caret> {
'''
}
public void testCaretInfrontOfConditional() throws Exception {
public void testCaretInfrontOfConditional() {
doTest '''
doTextTest '''
return <caret>aaa ? bbb : ccc
''', '''\
if (aaa)<caret> {
@@ -83,9 +80,9 @@ if (aaa)<caret> {
'''
}
public void testCaretInfrontOfElse() throws Exception {
public void testCaretInfrontOfElse() {
doTest '''
doTextTest '''
return aaa ? bbb <caret>: ccc
''', '''\
if (aaa)<caret> {
@@ -96,9 +93,9 @@ if (aaa)<caret> {
'''
}
public void testCaretAfterElse() throws Exception {
public void testCaretAfterElse() {
doTest '''
doTextTest '''
return aaa ? bbb :<caret> ccc
''', '''\
if (aaa)<caret> {
@@ -109,9 +106,9 @@ if (aaa)<caret> {
'''
}
public void testCaretBeforeElseReturn() throws Exception {
public void testCaretBeforeElseReturn() {
doTest '''
doTextTest '''
return aaa ? bbb : <caret>ccc
''', '''\
if (aaa)<caret> {
@@ -122,9 +119,9 @@ if (aaa)<caret> {
'''
}
public void testCaretBeforeReturnStatement() throws Exception {
public void testCaretBeforeReturnStatement() {
doTest '''
doTextTest '''
<caret>return aaa ? bbb : ccc
''', '''\
if (aaa)<caret> {