Merge remote-tracking branch 'origin/master'

This commit is contained in:
Ekaterina Tuzova
2014-02-24 13:30:49 +04:00
332 changed files with 2657 additions and 2277 deletions
+5
View File
@@ -193,6 +193,11 @@
<module fileurl="file://$PROJECT_DIR$/plugins/xslt-debugger/engine/xslt-debugger-engine.iml" filepath="$PROJECT_DIR$/plugins/xslt-debugger/engine/xslt-debugger-engine.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/plugins/xslt-debugger/engine/impl/xslt-debugger-engine-impl.iml" filepath="$PROJECT_DIR$/plugins/xslt-debugger/engine/impl/xslt-debugger-engine-impl.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/plugins/xpath/xslt-rt/xslt-rt.iml" filepath="$PROJECT_DIR$/plugins/xpath/xslt-rt/xslt-rt.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/platform/structure-view-api/structure-view-api.iml" filepath="$PROJECT_DIR$/platform/structure-view-api/structure-view-api.iml" group="platform" />
<module fileurl="file://$PROJECT_DIR$/platform/structure-view-impl/structure-view-impl.iml" filepath="$PROJECT_DIR$/platform/structure-view-impl/structure-view-impl.iml" group="platform" />
<module fileurl="file://$PROJECT_DIR$/java/java-structure-view/java-structure-view.iml" filepath="$PROJECT_DIR$/java/java-structure-view/java-structure-view.iml" group="java"/>
<module fileurl="file://$PROJECT_DIR$/xml/xml-structure-view-api/xml-structure-view-api.iml" filepath="$PROJECT_DIR$/xml/xml-structure-view-api/xml-structure-view-api.iml" group="xml" />
<module fileurl="file://$PROJECT_DIR$/xml/xml-structure-view-impl/xml-structure-view-impl.iml" filepath="$PROJECT_DIR$/xml/xml-structure-view-impl/xml-structure-view-impl.iml" group="xml" />
</modules>
</component>
</project>
+2 -1
View File
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -75,6 +75,7 @@ def layoutFull(String home, String targetDirectory, String patchedDescriptorDir
"java-indexing-impl",
"java-impl",
"java-psi-impl",
"java-structure-view",
"jsp-spi",
"manifest",
"platform-main",
+4
View File
@@ -255,6 +255,7 @@ binding.setVariable("platformApiModules", [
"lvcs-api",
"projectModel-api",
"platform-api",
"structure-view-api",
"usageView",
"vcs-api",
"vcs-log-api",
@@ -262,6 +263,7 @@ binding.setVariable("platformApiModules", [
"xml-analysis-api",
"xml-openapi",
"xml-psi-api",
"xml-structure-view-api",
])
@@ -278,6 +280,7 @@ binding.setVariable("platformImplementationModules", [
"lvcs-impl",
"projectModel-impl",
"platform-impl",
"structure-view-impl",
"vcs-impl",
"vcs-log-graph",
"vcs-log-impl",
@@ -290,6 +293,7 @@ binding.setVariable("platformImplementationModules", [
"xml",
"xml-analysis-impl",
"xml-psi-impl",
"xml-structure-view-impl",
])
binding.setVariable("layoutMacApp", { String path, String ch, Map args ->
+1
View File
@@ -52,6 +52,7 @@
<orderEntry type="library" name="Xerces" level="project" />
<orderEntry type="library" name="Velocity" level="project" />
<orderEntry type="module" module-name="testFramework-java" scope="TEST" />
<orderEntry type="module" module-name="java-structure-view" exported="" />
</component>
<component name="copyright">
<Base>
@@ -32,7 +32,11 @@ import org.jetbrains.annotations.Nullable;
public class ExcludeFromCompletionLookupActionProvider implements LookupActionProvider {
@Override
public void fillActions(LookupElement element, Lookup lookup, Consumer<LookupElementAction> consumer) {
final Object o = element.getObject();
Object o = element.getObject();
if (o instanceof PsiClassObjectAccessExpression) {
o = PsiUtil.resolveClassInType(((PsiClassObjectAccessExpression)o).getOperand().getType());
}
if (o instanceof PsiClass) {
PsiClass clazz = (PsiClass)o;
addExcludes(consumer, clazz, clazz.getQualifiedName());
@@ -23,6 +23,7 @@ import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.DefaultParameterTypeInferencePolicy;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Function;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
@@ -57,7 +58,7 @@ public class RedundantLambdaParameterTypeIntention extends PsiElementBaseIntenti
if (parameter.getTypeElement() == null) return false;
}
if (parameters.length == 0) return false;
final PsiType functionalInterfaceType = LambdaUtil.getFunctionalInterfaceType(expression, false);
final PsiType functionalInterfaceType = LambdaUtil.getFunctionalInterfaceType(expression, true);
if (functionalInterfaceType != null) {
final PsiElement lambdaParent = expression.getParent();
if (lambdaParent instanceof PsiExpressionList) {
@@ -84,11 +85,12 @@ public class RedundantLambdaParameterTypeIntention extends PsiElementBaseIntenti
for (PsiTypeParameter parameter : typeParameters) {
final PsiType psiType = substitutor.substitute(parameter);
if (psiType == null || LambdaUtil.dependsOnTypeParams(psiType, expression, parameter)) return false;
if (psiType == null || dependsOnTypeParams(psiType, expression, parameter)) return false;
}
return functionalInterfaceType.isAssignableFrom(substitutor.substitute(method.getParameterList().getParameters()[idx].getType()));
}
}
else if (!LambdaUtil.isLambdaFullyInferred(expression, functionalInterfaceType)) {
if (!LambdaUtil.isLambdaFullyInferred(expression, functionalInterfaceType)) {
return false;
}
return true;
@@ -122,4 +124,11 @@ public class RedundantLambdaParameterTypeIntention extends PsiElementBaseIntenti
lambdaExpression.getParameterList().replace(expression.getParameterList());
}
}
private static boolean dependsOnTypeParams(PsiType type,
PsiLambdaExpression expr,
PsiTypeParameter param2Check) {
return LambdaUtil.depends(type, new LambdaUtil.TypeParamsChecker(expr, PsiUtil
.resolveGenericsClassInType(LambdaUtil.getFunctionalInterfaceType(expr, false)).getElement()), param2Check);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -29,6 +29,7 @@ import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes;
@@ -42,8 +43,9 @@ public class ClassesTreeStructureProvider implements SelectableTreeStructureProv
myProject = project;
}
@NotNull
@Override
public Collection<AbstractTreeNode> modify(AbstractTreeNode parent, Collection<AbstractTreeNode> children, ViewSettings settings) {
public Collection<AbstractTreeNode> modify(@NotNull AbstractTreeNode parent, @NotNull Collection<AbstractTreeNode> children, ViewSettings settings) {
ArrayList<AbstractTreeNode> result = new ArrayList<AbstractTreeNode>();
for (final AbstractTreeNode child : children) {
Object o = child.getValue();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -58,6 +58,7 @@ public final class PackageElement implements Queryable, RootsProvider {
return myElement;
}
@NotNull
@Override
public Collection<VirtualFile> getRoots() {
Set<VirtualFile> roots= new HashSet<VirtualFile>();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -26,13 +26,15 @@ import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMember;
import com.intellij.ui.ColoredTreeCellRenderer;
import com.intellij.ui.SimpleTextAttributes;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
public class StructureNodeRenderer extends ColoredTreeCellRenderer {
public void customizeCellRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
@Override
public void customizeCellRenderer(@NotNull JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
forNodeDescriptorInTree(value, expanded).customize(this);
}
@@ -1,62 +0,0 @@
/*
* Copyright 2000-2009 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.ide.structureView.impl.java;
import com.intellij.icons.AllIcons;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.util.FileStructureFilter;
import com.intellij.ide.util.treeView.smartTree.ActionPresentation;
import com.intellij.ide.util.treeView.smartTree.ActionPresentationData;
import com.intellij.ide.util.treeView.smartTree.TreeElement;
import com.intellij.openapi.actionSystem.Shortcut;
import com.intellij.openapi.keymap.KeymapManager;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
public class InheritedMembersFilter implements FileStructureFilter {
@NonNls public static final String ID = "SHOW_INHERITED";
public boolean isVisible(TreeElement treeNode) {
if (treeNode instanceof JavaClassTreeElementBase) {
return !((JavaClassTreeElementBase)treeNode).isInherited();
}
else {
return true;
}
}
@NotNull
public ActionPresentation getPresentation() {
return new ActionPresentationData(IdeBundle.message("action.structureview.show.inherited"), null, AllIcons.Hierarchy.Supertypes);
}
@NotNull
public String getName() {
return ID;
}
public boolean isReverted() {
return true;
}
public String getCheckBoxText() {
return IdeBundle.message("file.structure.toggle.show.inherited");
}
public Shortcut[] getShortcut() {
return KeymapManager.getInstance().getActiveKeymap().getShortcuts("FileStructurePopup");
}
}
@@ -1,64 +0,0 @@
/*
* 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 com.intellij.ide.structureView.impl.java;
import com.intellij.ide.util.FileStructureFilter;
import com.intellij.ide.util.treeView.smartTree.ActionPresentation;
import com.intellij.ide.util.treeView.smartTree.ActionPresentationData;
import com.intellij.ide.util.treeView.smartTree.TreeElement;
import com.intellij.openapi.actionSystem.Shortcut;
import com.intellij.util.PlatformIcons;
import org.jetbrains.annotations.NotNull;
/**
* @author Konstantin Bulenkov
*/
public class JavaAnonymousMembersFilter implements FileStructureFilter {
private static final String ID = "SHOW_ANONYMOUS";
@Override
public String getCheckBoxText() {
return "Show Anonymous Classes";
}
@Override
public Shortcut[] getShortcut() {
return new Shortcut[0];
}
@Override
public boolean isVisible(TreeElement treeNode) {
return !(treeNode instanceof JavaAnonymousClassTreeElement);
}
@Override
public boolean isReverted() {
return true;
}
@NotNull
@Override
public ActionPresentation getPresentation() {
return new ActionPresentationData(getCheckBoxText(), null, PlatformIcons.ANONYMOUS_CLASS_ICON);
}
@NotNull
@Override
public String getName() {
return ID;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -28,6 +28,7 @@ public class SourceComparator implements Comparator<NodeDescriptor>{
private SourceComparator() {
}
@Override
public int compare(NodeDescriptor nodeDescriptor1, NodeDescriptor nodeDescriptor2) {
int weight1 = getWeight(nodeDescriptor1);
int weight2 = getWeight(nodeDescriptor2);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -17,6 +17,7 @@ package com.intellij.lang.java;
import com.intellij.navigation.AnonymousElementProvider;
import com.intellij.psi.*;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
@@ -25,8 +26,9 @@ import java.util.List;
* @author Konstantin Bulenkov
*/
public class JavaAnonymousClassesProvider implements AnonymousElementProvider {
@NotNull
@Override
public PsiElement[] getAnonymousElements(PsiElement parent) {
public PsiElement[] getAnonymousElements(@NotNull PsiElement parent) {
if (suite(parent)) {
if (parent instanceof PsiCompiledElement) {
parent = parent.getNavigationElement();
@@ -180,12 +180,14 @@ public class JavaRearranger implements Rearranger<JavaElementArrangementEntry>,
private static void setupBreadthFirstDependency(@NotNull ArrangementEntryDependencyInfo info) {
Deque<ArrangementEntryDependencyInfo> toProcess = new ArrayDeque<ArrangementEntryDependencyInfo>();
toProcess.add(info);
JavaElementArrangementEntry prev = info.getAnchorEntry();
while (!toProcess.isEmpty()) {
ArrangementEntryDependencyInfo current = toProcess.removeFirst();
for (ArrangementEntryDependencyInfo dependencyInfo : current.getDependentEntriesInfos()) {
JavaElementArrangementEntry dependencyMethod = dependencyInfo.getAnchorEntry();
if (dependencyMethod.getDependencies() == null) {
dependencyMethod.addDependency(current.getAnchorEntry());
dependencyMethod.addDependency(prev);
prev = dependencyMethod;
}
toProcess.addLast(dependencyInfo);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -13,10 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @author max
*/
package com.intellij.psi.impl.source.codeStyle;
import com.intellij.lang.ASTNode;
@@ -47,6 +43,9 @@ import org.jetbrains.annotations.Nullable;
import java.beans.Introspector;
import java.util.*;
/**
* @author max
*/
public class JavaCodeStyleManagerImpl extends JavaCodeStyleManager {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.codeStyle.JavaCodeStyleManagerImpl");
@@ -87,8 +86,7 @@ public class JavaCodeStyleManagerImpl extends JavaCodeStyleManager {
}
@Override
public void shortenClassReferences(@NotNull PsiElement element, int startOffset, int endOffset)
throws IncorrectOperationException {
public void shortenClassReferences(@NotNull PsiElement element, int startOffset, int endOffset) throws IncorrectOperationException {
CheckUtil.checkWritable(element);
if (SourceTreeToPsiMap.hasTreeElement(element)) {
final ReferenceAdjuster adjuster = ReferenceAdjuster.Extension.getReferenceAdjuster(element.getLanguage());
@@ -164,7 +162,7 @@ public class JavaCodeStyleManagerImpl extends JavaCodeStyleManager {
ContainerUtil.addAll(redundant, imports);
redundant.removeAll(allImports);
for (PsiImportStatementBase importStatement : imports) {
if (importStatement instanceof JspxImportStatement && ((JspxImportStatement)importStatement).isForeignFileImport()) {
if (importStatement instanceof JspxImportStatement && importStatement.isForeignFileImport()) {
redundant.remove(importStatement);
}
}
@@ -481,7 +479,7 @@ public class JavaCodeStyleManagerImpl extends JavaCodeStyleManager {
if (fromLiterals != null) {
ContainerUtil.addAll(names, fromLiterals);
}
ContainerUtil.addAll(names, suggestVariableNameByExpressionOnly(expr, variableKind, correctKeywords, false).names);
ContainerUtil.addAll(names, suggestVariableNameByExpressionPlace(expr, variableKind, correctKeywords).names);
@@ -17,6 +17,7 @@ package com.intellij.refactoring.changeSignature;
import com.intellij.codeInsight.ExceptionUtil;
import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil;
import com.intellij.codeInspection.dataFlow.ControlFlowAnalyzer;
import com.intellij.lang.StdLanguages;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
@@ -884,7 +885,7 @@ public class JavaChangeSignatureUsageProcessor implements ChangeSignatureUsagePr
private static class ConflictSearcher {
private final JavaChangeInfo myChangeInfo;
private ConflictSearcher(JavaChangeInfo changeInfo) {
private ConflictSearcher(@NotNull JavaChangeInfo changeInfo) {
this.myChangeInfo = changeInfo;
}
@@ -901,6 +902,8 @@ public class JavaChangeSignatureUsageProcessor implements ChangeSignatureUsagePr
LOG.error(e);
}
}
checkContract(conflictDescriptions, myChangeInfo.getMethod());
for (UsageInfo usageInfo : usagesSet) {
final PsiElement element = usageInfo.getElement();
@@ -914,6 +917,8 @@ public class JavaChangeSignatureUsageProcessor implements ChangeSignatureUsagePr
conflictDescriptions.putValue(baseMethod, "Implicit last parameter should not be deleted");
}
}
checkContract(conflictDescriptions, method);
} else if (element instanceof PsiMethodReferenceExpression) {
conflictDescriptions.putValue(element, "Changed method is used in method reference");
}
@@ -922,6 +927,12 @@ public class JavaChangeSignatureUsageProcessor implements ChangeSignatureUsagePr
return conflictDescriptions;
}
private static void checkContract(MultiMap<PsiElement, String> conflictDescriptions, PsiMethod method) {
if (ControlFlowAnalyzer.findContractAnnotation(method) != null) {
conflictDescriptions.putValue(method, "@Contract annotation will have to be changed manually");
}
}
private boolean needToChangeCalls() {
return myChangeInfo.isNameChanged() || myChangeInfo.isParameterSetOrOrderChanged() || myChangeInfo.isExceptionSetOrOrderChanged();
}
@@ -964,9 +975,6 @@ public class JavaChangeSignatureUsageProcessor implements ChangeSignatureUsagePr
private void addMethodConflicts(MultiMap<PsiElement, String> conflicts) {
String newMethodName = myChangeInfo.getNewName();
if (!(myChangeInfo instanceof JavaChangeInfo)) {
return;
}
try {
PsiMethod prototype;
final PsiMethod method = myChangeInfo.getMethod();
@@ -239,12 +239,6 @@ public class LambdaUtil {
return -1;
}
public static boolean dependsOnTypeParams(PsiType type,
PsiLambdaExpression expr,
PsiTypeParameter param2Check) {
return depends(type, new TypeParamsChecker(expr), param2Check);
}
public static boolean dependsOnTypeParams(PsiType type,
PsiType functionalInterfaceType,
PsiElement lambdaExpression,
@@ -253,13 +247,7 @@ public class LambdaUtil {
PsiUtil.resolveClassInType(functionalInterfaceType)), param2Check);
}
public static boolean dependsOnTypeParams(PsiType type,
PsiClass aClass,
PsiMethod aMethod) {
return depends(type, new TypeParamsChecker(aMethod, aClass));
}
static boolean depends(PsiType type, TypeParamsChecker visitor, PsiTypeParameter... param2Check) {
public static boolean depends(PsiType type, TypeParamsChecker visitor, PsiTypeParameter... param2Check) {
if (!visitor.startedInference()) return false;
final Boolean accept = type.accept(visitor);
if (param2Check.length > 0) {
@@ -268,79 +256,8 @@ public class LambdaUtil {
return accept != null && accept.booleanValue();
}
public static boolean isFreeFromTypeInferenceArgs(final PsiParameter[] methodParameters,
final PsiLambdaExpression lambdaExpression,
final PsiExpression expression,
final PsiSubstitutor subst,
final PsiType functionalInterfaceType,
final PsiTypeParameter typeParam) {
if (expression instanceof PsiCallExpression && ((PsiCallExpression)expression).getTypeArguments().length > 0) return true;
if (expression instanceof PsiNewExpression) {
final PsiJavaCodeReferenceElement classReference = ((PsiNewExpression)expression).getClassOrAnonymousClassReference();
if (classReference != null) {
final PsiReferenceParameterList parameterList = classReference.getParameterList();
if (parameterList != null) {
final PsiTypeElement[] typeParameterElements = parameterList.getTypeParameterElements();
if (typeParameterElements.length > 0) {
if (!(typeParameterElements[0].getType() instanceof PsiDiamondType)) {
return true;
}
}
}
}
}
final PsiParameter[] lambdaParams = lambdaExpression.getParameterList().getParameters();
if (lambdaParams.length != methodParameters.length) return false;
final boolean[] independent = {true};
final PsiMethod interfaceMethod = getFunctionalInterfaceMethod(functionalInterfaceType);
if (interfaceMethod == null) return false;
final TypeParamsChecker paramsChecker = new TypeParamsChecker(lambdaExpression);
for (PsiParameter parameter : interfaceMethod.getParameterList().getParameters()) {
subst.substitute(parameter.getType()).accept(paramsChecker);
}
paramsChecker.myUsedTypeParams.add(typeParam);
expression.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitConditionalExpression(PsiConditionalExpression expression) {
final PsiExpression thenExpression = expression.getThenExpression();
if (thenExpression != null) {
thenExpression.accept(this);
}
final PsiExpression elseExpression = expression.getElseExpression();
if (elseExpression != null) {
elseExpression.accept(this);
}
}
@Override
public void visitReferenceExpression(PsiReferenceExpression expression) {
super.visitReferenceExpression(expression);
int usedParamIdx = -1;
for (int i = 0; i < lambdaParams.length; i++) {
PsiParameter param = lambdaParams[i];
if (expression.isReferenceTo(param)) {
usedParamIdx = i;
break;
}
}
if (usedParamIdx > -1 && dependsOnTypeParams(subst.substitute(methodParameters[usedParamIdx].getType()), functionalInterfaceType,
lambdaExpression, paramsChecker.myUsedTypeParams.toArray(new PsiTypeParameter[paramsChecker.myUsedTypeParams.size()]))) {
independent[0] = false;
}
}
});
return independent[0];
}
@Nullable
public static PsiType getFunctionalInterfaceType(PsiElement expression, final boolean tryToSubstitute) {
return getFunctionalInterfaceType(expression, tryToSubstitute, -1);
}
@Nullable
public static PsiType getFunctionalInterfaceType(PsiElement expression, final boolean tryToSubstitute, int paramIdx) {
PsiElement parent = expression.getParent();
PsiElement element = expression;
while (parent instanceof PsiParenthesizedExpression || parent instanceof PsiConditionalExpression) {
@@ -376,14 +293,6 @@ public class LambdaUtil {
final int lambdaIdx = getLambdaIdx(expressionList, expression);
if (lambdaIdx > -1) {
PsiType cachedType = null;
final Pair<PsiMethod, PsiSubstitutor> method = MethodCandidateInfo.getCurrentMethod(parent);
if (method != null) {
final PsiParameter[] parameters = method.first.getParameterList().getParameters();
cachedType = lambdaIdx < parameters.length ? method.second.substitute(getNormalizedType(parameters[adjustLambdaIdx(lambdaIdx, method.first, parameters)])) : null;
if (!tryToSubstitute) return cachedType;
}
PsiElement gParent = expressionList.getParent();
if (gParent instanceof PsiAnonymousClass) {
@@ -399,22 +308,6 @@ public class LambdaUtil {
final int finalLambdaIdx = adjustLambdaIdx(lambdaIdx, (PsiMethod)resolve, parameters);
if (finalLambdaIdx < parameters.length) {
if (!tryToSubstitute) return getNormalizedType(parameters[finalLambdaIdx]);
if (cachedType != null) {
final PsiMethod interfaceMethod = getFunctionalInterfaceMethod(cachedType);
if (interfaceMethod != null) {
final PsiClassType.ClassResolveResult cachedResult = PsiUtil.resolveGenericsClassInType(cachedType);
if (paramIdx == -1) {
if (!dependsOnTypeParams(cachedType, cachedType, expression) && !dependsOnTypeParams(getFunctionalInterfaceReturnType(cachedType), cachedType, expression)) {
return cachedType;
}
}
else {
if (!dependsOnTypeParams(cachedResult.getSubstitutor().substitute(interfaceMethod.getParameterList().getParameters()[paramIdx].getType()), cachedType, expression)) {
return cachedType;
}
}
}
}
return PsiResolveHelper.ourGuard.doPreventingRecursion(expression, true, new Computable<PsiType>() {
@Override
public PsiType compute() {
@@ -467,53 +360,6 @@ public class LambdaUtil {
return type;
}
public static PsiType getLambdaParameterType(PsiParameter param) {
final PsiElement paramParent = param.getParent();
if (paramParent instanceof PsiParameterList) {
final int parameterIndex = ((PsiParameterList)paramParent).getParameterIndex(param);
if (parameterIndex > -1) {
final PsiLambdaExpression lambdaExpression = PsiTreeUtil.getParentOfType(param, PsiLambdaExpression.class);
if (lambdaExpression != null) {
PsiType type = getFunctionalInterfaceType(lambdaExpression, true, parameterIndex);
if (type == null) {
type = getFunctionalInterfaceType(lambdaExpression, false);
}
if (type instanceof PsiIntersectionType) {
final PsiType[] conjuncts = ((PsiIntersectionType)type).getConjuncts();
for (PsiType conjunct : conjuncts) {
final PsiType lambdaParameterFromType = getLambdaParameterFromType(parameterIndex, lambdaExpression, conjunct);
if (lambdaParameterFromType != null) return lambdaParameterFromType;
}
} else {
final PsiType lambdaParameterFromType = getLambdaParameterFromType(parameterIndex, lambdaExpression, type);
if (lambdaParameterFromType != null) {
return lambdaParameterFromType;
}
}
}
}
}
return new PsiLambdaParameterType(param);
}
private static PsiType getLambdaParameterFromType(int parameterIndex, PsiLambdaExpression lambdaExpression, PsiType conjunct) {
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(conjunct);
if (resolveResult != null) {
final PsiMethod method = getFunctionalInterfaceMethod(conjunct);
if (method != null) {
final PsiParameter[] parameters = method.getParameterList().getParameters();
if (parameterIndex < parameters.length) {
final PsiType psiType = getSubstitutor(method, resolveResult).substitute(parameters[parameterIndex].getType());
if (!dependsOnTypeParams(psiType, conjunct, lambdaExpression)) {
return GenericsUtil.eliminateWildcards(psiType);
}
}
}
}
return null;
}
public static boolean notInferredType(PsiType typeByExpression) {
return typeByExpression instanceof PsiMethodReferenceType || typeByExpression instanceof PsiLambdaExpressionType || typeByExpression instanceof PsiLambdaParameterType;
}
@@ -584,19 +430,10 @@ public class LambdaUtil {
return true;
}
static class TypeParamsChecker extends PsiTypeVisitor<Boolean> {
public static class TypeParamsChecker extends PsiTypeVisitor<Boolean> {
private PsiMethod myMethod;
private final PsiClass myClass;
private final Set<PsiTypeParameter> myUsedTypeParams = new HashSet<PsiTypeParameter>();
private TypeParamsChecker(PsiMethod method, PsiClass aClass) {
myMethod = method;
myClass = aClass;
}
public TypeParamsChecker(PsiElement expression) {
this(expression, PsiUtil.resolveGenericsClassInType(getFunctionalInterfaceType(expression, false)).getElement());
}
public final Set<PsiTypeParameter> myUsedTypeParams = new HashSet<PsiTypeParameter>();
public TypeParamsChecker(PsiElement expression, PsiClass aClass) {
myClass = aClass;
@@ -1065,11 +1065,11 @@ public final class PsiUtil extends PsiUtilCore {
return className + "." + member.getName();
}
static boolean checkSameExpression(PsiExpression templateExpr, final PsiExpression expression) {
static boolean checkSameExpression(PsiElement templateExpr, final PsiExpression expression) {
return templateExpr.equals(skipParenthesizedExprDown(expression));
}
public static boolean isCondition(PsiExpression expr, PsiElement parent) {
public static boolean isCondition(PsiElement expr, PsiElement parent) {
if (parent instanceof PsiIfStatement) {
if (checkSameExpression(expr, ((PsiIfStatement)parent).getCondition())) {
return true;
@@ -31,8 +31,8 @@ public class ClassFileViewProvider extends SingleRootFileViewProvider {
super(manager, file);
}
public ClassFileViewProvider(@NotNull final PsiManager manager, @NotNull final VirtualFile virtualFile, final boolean physical) {
super(manager, virtualFile, physical);
public ClassFileViewProvider(@NotNull final PsiManager manager, @NotNull final VirtualFile virtualFile, final boolean eventSystemEnabled) {
super(manager, virtualFile, eventSystemEnabled);
}
@Override
@@ -29,20 +29,20 @@ import static com.intellij.psi.compiled.ClassFileDecompilers.Full;
*/
public class ClassFileViewProviderFactory implements FileViewProviderFactory {
@Override
public FileViewProvider createFileViewProvider(@NotNull VirtualFile file, Language language, @NotNull PsiManager manager, boolean physical) {
public FileViewProvider createFileViewProvider(@NotNull VirtualFile file, Language language, @NotNull PsiManager manager, boolean eventSystemEnabled) {
ClassFileDecompilers.Decompiler decompiler = ClassFileDecompilers.find(file);
if (decompiler instanceof Full) {
return ((Full)decompiler).createFileViewProvider(file, manager, physical);
return ((Full)decompiler).createFileViewProvider(file, manager, eventSystemEnabled);
}
for (ContentBasedFileSubstitutor processor : Extensions.getExtensions(ContentBasedFileSubstitutor.EP_NAME)) {
Language lang = processor.obtainLanguageForFile(file);
if (lang != null) {
FileViewProviderFactory factory = LanguageFileViewProviders.INSTANCE.forLanguage(language);
return factory.createFileViewProvider(file, language, manager, physical);
return factory.createFileViewProvider(file, language, manager, eventSystemEnabled);
}
}
return new ClassFileViewProvider(manager, file, physical);
return new ClassFileViewProvider(manager, file, eventSystemEnabled);
}
}
@@ -32,6 +32,7 @@ import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.reference.SoftReference;
import com.intellij.ui.RowIcon;
import com.intellij.util.IncorrectOperationException;
@@ -59,6 +60,53 @@ public class PsiParameterImpl extends JavaStubPsiElement<PsiParameterStub> imple
super(node);
}
public static PsiType getLambdaParameterType(PsiParameter param) {
final PsiElement paramParent = param.getParent();
if (paramParent instanceof PsiParameterList) {
final int parameterIndex = ((PsiParameterList)paramParent).getParameterIndex(param);
if (parameterIndex > -1) {
final PsiLambdaExpression lambdaExpression = PsiTreeUtil.getParentOfType(param, PsiLambdaExpression.class);
if (lambdaExpression != null) {
PsiType type = LambdaUtil.getFunctionalInterfaceType(lambdaExpression, true);
if (type == null) {
type = LambdaUtil.getFunctionalInterfaceType(lambdaExpression, false);
}
if (type instanceof PsiIntersectionType) {
final PsiType[] conjuncts = ((PsiIntersectionType)type).getConjuncts();
for (PsiType conjunct : conjuncts) {
final PsiType lambdaParameterFromType = getLambdaParameterFromType(parameterIndex, lambdaExpression, conjunct);
if (lambdaParameterFromType != null) return lambdaParameterFromType;
}
} else {
final PsiType lambdaParameterFromType = getLambdaParameterFromType(parameterIndex, lambdaExpression, type);
if (lambdaParameterFromType != null) {
return lambdaParameterFromType;
}
}
}
}
}
return new PsiLambdaParameterType(param);
}
private static PsiType getLambdaParameterFromType(int parameterIndex, PsiLambdaExpression lambdaExpression, PsiType conjunct) {
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(conjunct);
if (resolveResult != null) {
final PsiMethod method = LambdaUtil.getFunctionalInterfaceMethod(conjunct);
if (method != null) {
final PsiParameter[] parameters = method.getParameterList().getParameters();
if (parameterIndex < parameters.length) {
final PsiType psiType = LambdaUtil.getSubstitutor(method, resolveResult).substitute(parameters[parameterIndex].getType());
if (!LambdaUtil.dependsOnTypeParams(psiType, conjunct, lambdaExpression)) {
return GenericsUtil.eliminateWildcards(psiType);
}
}
}
}
return null;
}
@Override
public void subtreeChanged() {
super.subtreeChanged();
@@ -138,7 +186,7 @@ public class PsiParameterImpl extends JavaStubPsiElement<PsiParameterStub> imple
PsiTypeElement typeElement = getTypeElement();
if (typeElement == null) {
assert isLambdaParameter() : this;
return LambdaUtil.getLambdaParameterType(this);
return getLambdaParameterType(this);
}
else {
return JavaSharedImplUtil.getType(typeElement, getParameterIdentifier());
@@ -1,114 +0,0 @@
/*
* Copyright 2000-2013 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.psi.impl.source.resolve;
import com.intellij.psi.*;
import com.intellij.psi.scope.MethodProcessorSetupFailedException;
import com.intellij.psi.scope.processor.MethodCandidatesProcessor;
import com.intellij.psi.scope.util.PsiScopesUtil;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* User: anna
* Date: 2/14/13
*/
public class GraphInferencePolicy extends ProcessCandidateParameterTypeInferencePolicy {
private static final ThreadLocal<Map<PsiExpression, Map<JavaResolveResult, PsiSubstitutor>>> ourResults = new ThreadLocal<Map<PsiExpression, Map<JavaResolveResult, PsiSubstitutor>>>() {
@Override
protected Map<PsiExpression, Map<JavaResolveResult, PsiSubstitutor>> initialValue() {
return new WeakHashMap<PsiExpression, Map<JavaResolveResult, PsiSubstitutor>>();
}
};
@Override
protected List<PsiExpression> getExpressions(PsiExpression[] expressions, int i) {
final List<PsiExpression> list = Arrays.asList(expressions);
list.set(i, null);
return list;
}
@Override
protected PsiSubstitutor getSubstitutor(PsiCallExpression contextCall, PsiExpression[] expressions, int i, JavaResolveResult result) {
Map<JavaResolveResult, PsiSubstitutor> map = ourResults.get().get(contextCall);
if (map != null) {
final PsiSubstitutor substitutor = map.get(result);
if (substitutor != PsiSubstitutor.UNKNOWN && substitutor != null && substitutor.isValid()) return substitutor;
}
final PsiSubstitutor substitutor = super.getSubstitutor(contextCall, expressions, i, result);
if (map != null) {
map.put(result, substitutor);
}
return substitutor;
}
@NotNull
@Override
protected JavaResolveResult[] getResults(@NotNull PsiCallExpression contextCall, final int exprIdx)
throws MethodProcessorSetupFailedException {
Map<JavaResolveResult, PsiSubstitutor> map = ourResults.get().get(contextCall);
if (map != null) {
final Set<JavaResolveResult> results = map.keySet();
return results.toArray(new JavaResolveResult[results.size()]);
}
PsiFile containingFile = contextCall.getContainingFile();
final MethodCandidatesProcessor processor = new MethodCandidatesProcessor(contextCall, containingFile) {
@Override
protected PsiType[] getExpressionTypes(PsiExpressionList argumentList) {
if (argumentList != null) {
final PsiExpression[] expressions = argumentList.getExpressions();
final PsiType[] types = PsiType.createArray(expressions.length);
for (int i = 0; i < expressions.length; i++) {
if (i != exprIdx) {
types[i] = expressions[i].getType();
}
else {
types[i] = PsiType.NULL;
}
}
return types;
}
else {
return null;
}
}
};
PsiScopesUtil.setupAndRunProcessor(processor, contextCall, false);
final JavaResolveResult[] results = processor.getResult();
map = new WeakHashMap<JavaResolveResult, PsiSubstitutor>();
ourResults.get().put(contextCall, map);
for (JavaResolveResult result : results) {
map.put(result, PsiSubstitutor.UNKNOWN);
}
return results;
}
public static void forget(PsiElement parent) {
if (parent instanceof PsiExpression) {
PsiElement gParent = PsiUtil.skipParenthesizedExprUp(parent.getParent());
if (gParent instanceof PsiExpressionList) {
final PsiElement ggParent = gParent.getParent();
if (ggParent instanceof PsiCallExpression) {
ourResults.get().remove(ggParent);
}
}
}
}
}
@@ -15,29 +15,22 @@
*/
package com.intellij.psi.impl.source.resolve;
import com.intellij.codeInsight.ExceptionUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.JavaVersionService;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.RecursionGuard;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.*;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Map;
/**
* User: anna
*/
@@ -50,7 +43,7 @@ public class PsiOldInferenceHelper implements PsiInferenceHelper {
myManager = manager;
}
private Pair<PsiType, ConstraintType> inferTypeForMethodTypeParameterInner(@NotNull PsiTypeParameter typeParameter,
private Pair<PsiType, ConstraintType> inferTypeForMethodTypeParameterInner(@NotNull PsiTypeParameter typeParameter,
@NotNull PsiParameter[] parameters,
@NotNull PsiExpression[] arguments,
@NotNull PsiSubstitutor partialSubstitutor,
@@ -98,10 +91,6 @@ public class PsiOldInferenceHelper implements PsiInferenceHelper {
PsiType lowerBound = PsiType.NULL;
PsiType upperBound = PsiType.NULL;
if (paramTypes.length > 0) {
sortLambdaExpressionsLast(paramTypes, argTypes);
boolean rawType = false;
boolean nullPassed = false;
boolean lambdaRaw = false;
for (int j = 0; j < argTypes.length; j++) {
PsiType argumentType = argTypes[j];
if (argumentType == null) continue;
@@ -109,8 +98,6 @@ public class PsiOldInferenceHelper implements PsiInferenceHelper {
PsiType parameterType = paramTypes[j];
if (parameterType == null) break;
rawType |= parameterType instanceof PsiClassType && ((PsiClassType)parameterType).isRaw();
nullPassed |= argumentType == PsiType.NULL;
if (parameterType instanceof PsiEllipsisType) {
parameterType = ((PsiEllipsisType)parameterType).getComponentType();
@@ -119,26 +106,8 @@ public class PsiOldInferenceHelper implements PsiInferenceHelper {
}
}
final Pair<PsiType,ConstraintType> currentSubstitution;
if (argumentType instanceof PsiLambdaExpressionType) {
currentSubstitution = inferSubstitutionFromLambda(typeParameter, (PsiLambdaExpressionType)argumentType, lowerBound, partialSubstitutor);
if (rawType) {
if (currentSubstitution == FAILED_INFERENCE || currentSubstitution == null && lowerBound == PsiType.NULL) return RAW_INFERENCE;
}
if (nullPassed && currentSubstitution == null) return RAW_INFERENCE;
if (currentSubstitution != null && currentSubstitution.first == null) {
lambdaRaw = true;
}
if (currentSubstitution == null && lambdaRaw) {
return new Pair<PsiType, ConstraintType>(PsiType.getJavaLangObject(myManager, typeParameter.getResolveScope()), ConstraintType.EQUALS);
}
} else if (argumentType instanceof PsiMethodReferenceType) {
final PsiMethodReferenceExpression referenceExpression = ((PsiMethodReferenceType)argumentType).getExpression();
currentSubstitution = inferConstraintFromFunctionalInterfaceMethod(typeParameter, referenceExpression, partialSubstitutor.substitute(parameterType), partialSubstitutor, policy);
}
else {
currentSubstitution = getSubstitutionForTypeParameterConstraint(typeParameter, parameterType,
argumentType, true, PsiUtil.getLanguageLevel(typeParameter));
}
currentSubstitution = getSubstitutionForTypeParameterConstraint(typeParameter, parameterType,
argumentType, true, PsiUtil.getLanguageLevel(typeParameter));
if (currentSubstitution == null) continue;
if (currentSubstitution == FAILED_INFERENCE) {
return getFailedInferenceConstraint(typeParameter);
@@ -210,23 +179,6 @@ public class PsiOldInferenceHelper implements PsiInferenceHelper {
return null;
}
private static void sortLambdaExpressionsLast(@NotNull PsiType[] paramTypes, @NotNull PsiType[] argTypes) {
for (int i = 0; i < argTypes.length; i++) {
PsiType argType = argTypes[i];
if ((argType instanceof PsiLambdaExpressionType || argType instanceof PsiMethodReferenceType) && i < argTypes.length - 1) {
int k = i + 1;
while((argTypes[k] instanceof PsiLambdaExpressionType || argTypes[k] instanceof PsiMethodReferenceType) && k < argTypes.length - 1) {
k++;
}
if (!(argTypes[k] instanceof PsiLambdaExpressionType || argTypes[k] instanceof PsiMethodReferenceType)) {
ArrayUtil.swap(paramTypes, i, k);
ArrayUtil.swap(argTypes, i, k);
i = k;
}
}
}
}
private static Pair<PsiType, ConstraintType> getFailedInferenceConstraint(@NotNull PsiTypeParameter typeParameter) {
return new Pair<PsiType, ConstraintType>(JavaPsiFacade.getInstance(typeParameter.getProject()).getElementFactory().createType(typeParameter), ConstraintType.EQUALS);
}
@@ -321,41 +273,36 @@ public class PsiOldInferenceHelper implements PsiInferenceHelper {
}
}
try {
for (int i = 0; i < typeParameters.length; i++) {
PsiTypeParameter typeParameter = typeParameters[i];
PsiType substitution = substitutions[i];
if (substitution != null) continue;
for (int i = 0; i < typeParameters.length; i++) {
PsiTypeParameter typeParameter = typeParameters[i];
PsiType substitution = substitutions[i];
if (substitution != null) continue;
Pair<PsiType, ConstraintType> constraint = constraints[i];
if (constraint == null) {
constraint = inferMethodTypeParameterFromParent(typeParameter, partialSubstitutor, parent, policy);
}
else if (constraint.getSecond() == ConstraintType.SUBTYPE) {
Pair<PsiType, ConstraintType> otherConstraint =
inferMethodTypeParameterFromParent(typeParameter, partialSubstitutor, parent, policy);
if (otherConstraint != null) {
if (otherConstraint.getSecond() == ConstraintType.EQUALS || otherConstraint.getSecond() == ConstraintType.SUPERTYPE) {
constraint = otherConstraint;
}
Pair<PsiType, ConstraintType> constraint = constraints[i];
if (constraint == null) {
constraint = inferMethodTypeParameterFromParent(typeParameter, partialSubstitutor, parent, policy);
}
else if (constraint.getSecond() == ConstraintType.SUBTYPE) {
Pair<PsiType, ConstraintType> otherConstraint =
inferMethodTypeParameterFromParent(typeParameter, partialSubstitutor, parent, policy);
if (otherConstraint != null) {
if (otherConstraint.getSecond() == ConstraintType.EQUALS || otherConstraint.getSecond() == ConstraintType.SUPERTYPE) {
constraint = otherConstraint;
}
}
if (constraint != null) {
substitution = constraint.getFirst();
}
if (substitution == null) {
PsiElementFactory factory = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory();
return factory.createRawSubstitutor(partialSubstitutor, typeParameters);
}
if (substitution != PsiType.NULL) {
partialSubstitutor = partialSubstitutor.put(typeParameter, substitution);
}
}
}
finally {
GraphInferencePolicy.forget(parent);
if (constraint != null) {
substitution = constraint.getFirst();
}
if (substitution == null) {
PsiElementFactory factory = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory();
return factory.createRawSubstitutor(partialSubstitutor, typeParameters);
}
if (substitution != PsiType.NULL) {
partialSubstitutor = partialSubstitutor.put(typeParameter, substitution);
}
}
return partialSubstitutor;
}
@@ -544,222 +491,6 @@ public class PsiOldInferenceHelper implements PsiInferenceHelper {
return getSubstitutionForTypeParameterInner(param, arg, patternType, ConstraintType.SUPERTYPE, 0);
}
@Nullable
private Pair<PsiType, ConstraintType> inferSubstitutionFromLambda(PsiTypeParameter typeParam,
PsiLambdaExpressionType arg,
PsiType lowerBound,
PsiSubstitutor partialSubstitutor) {
final PsiLambdaExpression lambdaExpression = arg.getExpression();
if (PsiUtil.getLanguageLevel(lambdaExpression).isAtLeast(LanguageLevel.JDK_1_8)) {
final PsiElement parent = PsiUtil.skipParenthesizedExprUp(lambdaExpression.getParent());
if (parent instanceof PsiExpressionList) {
final PsiExpressionList expressionList = (PsiExpressionList)parent;
final Map<PsiElement, Pair<PsiMethod, PsiSubstitutor>> methodMap = MethodCandidateInfo.CURRENT_CANDIDATE.get();
final Pair<PsiMethod, PsiSubstitutor> pair = methodMap != null ? methodMap.get(expressionList) : null;
if (pair != null) {
final int i = LambdaUtil.getLambdaIdx(expressionList, lambdaExpression);
if (i < 0) return null;
final PsiParameter[] parameters = pair.first.getParameterList().getParameters();
if (parameters.length <= i) return null;
final PsiSubstitutor combinedSubst = pair.second.putAll(partialSubstitutor);
methodMap.put(expressionList, Pair.create(pair.first, combinedSubst));
return inferConstraintFromFunctionalInterfaceMethod(typeParam, lambdaExpression, combinedSubst.substitute(parameters[i].getType()), lowerBound);
}
}
else {
return inferConstraintFromFunctionalInterfaceMethod(typeParam, lambdaExpression,
partialSubstitutor.substitute(lambdaExpression.getFunctionalInterfaceType()), lowerBound);
}
}
return null;
}
@Nullable
private Pair<PsiType, ConstraintType> inferConstraintFromFunctionalInterfaceMethod(final PsiTypeParameter typeParam,
final PsiMethodReferenceExpression methodReferenceExpression,
final PsiType functionalInterfaceType,
final PsiSubstitutor partialSubstitutor,
final ParameterTypeInferencePolicy policy) {
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType);
final PsiMethod functionalInterfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(resolveResult);
if (functionalInterfaceMethod != null) {
final PsiSubstitutor subst = LambdaUtil.getSubstitutor(functionalInterfaceMethod, resolveResult);
final PsiParameter[] methodParameters = functionalInterfaceMethod.getParameterList().getParameters();
PsiType[] methodParamTypes = PsiType.createArray(methodParameters.length);
for (int i = 0; i < methodParameters.length; i++) {
methodParamTypes[i] = GenericsUtil.eliminateWildcards(subst.substitute(methodParameters[i].getType()));
}
if (methodParamsDependOn(typeParam, methodReferenceExpression, functionalInterfaceType, methodParameters, subst)) {
return null;
}
final PsiType[] args = PsiType.createArray(methodParameters.length);
Map<PsiMethodReferenceExpression,PsiType> map = PsiMethodReferenceUtil.ourRefs.get();
if (map == null) {
map = new HashMap<PsiMethodReferenceExpression, PsiType>();
PsiMethodReferenceUtil.ourRefs.set(map);
}
final PsiType added = map.put(methodReferenceExpression, functionalInterfaceType);
final JavaResolveResult methReferenceResolveResult;
try {
methReferenceResolveResult = methodReferenceExpression.advancedResolve(false);
}
finally {
if (added == null) {
map.remove(methodReferenceExpression);
}
}
final PsiElement resolved = methReferenceResolveResult.getElement();
if (resolved instanceof PsiMethod) {
final PsiMethod method = (PsiMethod)resolved;
final PsiParameter[] parameters = method.getParameterList().getParameters();
boolean hasReceiver = false;
if (methodParamTypes.length == parameters.length + 1) {
if (!PsiMethodReferenceUtil
.isReceiverType(methodParamTypes[0], method.getContainingClass(), methReferenceResolveResult.getSubstitutor())) return null;
hasReceiver = true;
} else if (parameters.length != methodParameters.length) {
return null;
}
for (int i = 0; i < parameters.length; i++) {
args[i] = methReferenceResolveResult.getSubstitutor().substitute(subst.substitute(parameters[i].getType()));
}
final PsiType[] typesToInfer = hasReceiver ? ArrayUtil.remove(methodParamTypes, 0) : methodParamTypes;
final Pair<PsiType, ConstraintType> constraint = inferTypeForMethodTypeParameterInner(typeParam, typesToInfer, args, subst, null, DefaultParameterTypeInferencePolicy.INSTANCE);
if (constraint != null){
return constraint;
}
PsiType functionalInterfaceReturnType = functionalInterfaceMethod.getReturnType();
if (functionalInterfaceReturnType != null && functionalInterfaceReturnType != PsiType.VOID) {
functionalInterfaceReturnType = GenericsUtil.eliminateWildcards(subst.substitute(functionalInterfaceReturnType));
final PsiType argType;
if (method.isConstructor()) {
argType = JavaPsiFacade.getElementFactory(functionalInterfaceMethod.getProject()).createType(method.getContainingClass(), methReferenceResolveResult.getSubstitutor());
} else {
argType = methReferenceResolveResult.getSubstitutor().substitute(subst.substitute(method.getReturnType()));
}
final Pair<PsiType, ConstraintType> typeParameterConstraint =
getSubstitutionForTypeParameterConstraint(typeParam, functionalInterfaceReturnType, argType, true, PsiUtil.getLanguageLevel(functionalInterfaceMethod));
if (typeParameterConstraint != null && typeParameterConstraint.getSecond() != ConstraintType.EQUALS && method.isConstructor()) {
final Pair<PsiType, ConstraintType> constraintFromParent =
inferMethodTypeParameterFromParent(typeParam, partialSubstitutor, methodReferenceExpression.getParent().getParent(), policy);
if (constraintFromParent != null && constraintFromParent.getSecond() == ConstraintType.EQUALS) return constraintFromParent;
}
return typeParameterConstraint;
}
}
}
return null;
}
@Nullable
private Pair<PsiType, ConstraintType> inferConstraintFromFunctionalInterfaceMethod(PsiTypeParameter typeParam,
final PsiLambdaExpression lambdaExpression,
final PsiType functionalInterfaceType,
PsiType lowerBound) {
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType);
final PsiMethod method = LambdaUtil.getFunctionalInterfaceMethod(resolveResult);
if (method != null) {
final PsiSubstitutor subst = LambdaUtil.getSubstitutor(method, resolveResult);
final Pair<PsiType, ConstraintType> constraintFromFormalParams = inferConstraintFromLambdaFormalParams(typeParam, subst, method, lambdaExpression);
if (constraintFromFormalParams != null) return constraintFromFormalParams;
final PsiParameter[] methodParameters = method.getParameterList().getParameters();
if (methodParamsDependOn(typeParam, lambdaExpression, functionalInterfaceType, methodParameters, subst)) {
return null;
}
final PsiType returnType = subst.substitute(method.getReturnType());
if (returnType != null && returnType != PsiType.VOID) {
Pair<PsiType, ConstraintType> constraint = null;
final List<PsiExpression> expressions = LambdaUtil.getReturnExpressions(lambdaExpression);
for (final PsiExpression expression : expressions) {
final boolean independent = lambdaExpression.hasFormalParameterTypes() || LambdaUtil.isFreeFromTypeInferenceArgs(methodParameters, lambdaExpression, expression, subst, functionalInterfaceType, typeParam);
if (!independent) {
if (lowerBound != PsiType.NULL) {
return null;
}
continue;
}
if (expression instanceof PsiReferenceExpression && ((PsiReferenceExpression)expression).resolve() == null) continue;
PsiType exprType = PsiResolveHelper.ourGraphGuard.doPreventingRecursion(expression, true, new Computable<PsiType>() {
@Override
public PsiType compute() {
return expression.getType();
}
});
if (exprType instanceof PsiLambdaParameterType) {
final PsiParameter parameter = ((PsiLambdaParameterType)exprType).getParameter();
final int parameterIndex = lambdaExpression.getParameterList().getParameterIndex(parameter);
if (parameterIndex > -1) {
exprType = subst.substitute(methodParameters[parameterIndex].getType());
}
} else if (exprType instanceof PsiLambdaExpressionType) {
return inferConstraintFromFunctionalInterfaceMethod(typeParam, ((PsiLambdaExpressionType)exprType).getExpression(), returnType,
lowerBound);
} else if (exprType == null && independent) {
return null;
}
if (exprType == null){
return FAILED_INFERENCE;
}
final Pair<PsiType, ConstraintType> returnExprConstraint =
getSubstitutionForTypeParameterConstraint(typeParam, GenericsUtil.eliminateWildcards(returnType), exprType, true, PsiUtil.getLanguageLevel(method));
if (returnExprConstraint != null) {
if (returnExprConstraint == FAILED_INFERENCE) return returnExprConstraint;
if (constraint != null) {
final PsiType leastUpperBound = GenericsUtil.getLeastUpperBound(constraint.getFirst(), returnExprConstraint.getFirst(), myManager);
constraint = new Pair<PsiType, ConstraintType>(leastUpperBound, ConstraintType.SUPERTYPE);
} else {
constraint = returnExprConstraint;
}
}
}
if (constraint != null) return constraint;
}
}
return null;
}
private static boolean methodParamsDependOn(PsiTypeParameter typeParam, PsiElement psiElement,
PsiType functionalInterfaceType,
PsiParameter[] methodParameters,
PsiSubstitutor subst) {
for (PsiParameter parameter : methodParameters) {
if (LambdaUtil.dependsOnTypeParams(subst.substitute(parameter.getType()), functionalInterfaceType, psiElement, typeParam)) {
return true;
}
}
return false;
}
@Nullable
private Pair<PsiType, ConstraintType> inferConstraintFromLambdaFormalParams(PsiTypeParameter typeParam,
PsiSubstitutor subst,
PsiMethod method, PsiLambdaExpression lambdaExpression) {
final PsiParameter[] parameters = lambdaExpression.getParameterList().getParameters();
if (parameters.length == 0) return null;
final PsiType[] lambdaArgs = PsiType.createArray(parameters.length);
for (int i = 0; i < parameters.length; i++) {
PsiParameter parameter = parameters[i];
if (parameter.getTypeElement() == null) {
return null;
}
lambdaArgs[i] = parameter.getType();
}
final PsiParameter[] methodParameters = method.getParameterList().getParameters();
PsiType[] methodParamTypes = PsiType.createArray(methodParameters.length);
for (int i = 0; i < methodParameters.length; i++) {
methodParamTypes[i] = GenericsUtil.eliminateWildcards(subst.substitute(methodParameters[i].getType()));
}
return inferTypeForMethodTypeParameterInner(typeParam, methodParamTypes, lambdaArgs, subst, null, DefaultParameterTypeInferencePolicy.INSTANCE);
}
private static PsiType intersectAllExtends(PsiTypeParameter typeParam, PsiType arg) {
if (arg == null) return null;
PsiClassType[] superTypes = typeParam.getSuperTypes();
@@ -979,48 +710,10 @@ public class PsiOldInferenceHelper implements PsiInferenceHelper {
PsiType expectedType = PsiTypesUtil.getExpectedTypeByParent(methodCall);
if (expectedType == null) {
if (parent instanceof PsiReturnStatement) {
final PsiLambdaExpression lambdaExpression = PsiTreeUtil.getParentOfType(parent, PsiLambdaExpression.class);
if (lambdaExpression != null) {
return getFailedInferenceConstraint(typeParameter);
}
}
else if (parent instanceof PsiExpressionList) {
if (parent instanceof PsiExpressionList) {
final PsiElement pParent = parent.getParent();
if (pParent instanceof PsiCallExpression && parent.equals(((PsiCallExpression)pParent).getArgumentList())) {
constraint = policy.inferTypeConstraintFromCallContext(methodCall, (PsiExpressionList)parent, (PsiCallExpression)pParent, typeParameter);
if (constraint == null && PsiUtil.isLanguageLevel8OrHigher(methodCall)) {
constraint = graphInferenceFromCallContext(methodCall, typeParameter, (PsiCallExpression)pParent);
if (constraint != null) {
final PsiType constraintFirst = constraint.getFirst();
if (constraintFirst == null || constraintFirst.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) {
constraint = null;
}
}
}
}
} else if (parent instanceof PsiLambdaExpression) {
expectedType = PsiResolveHelper.ourGraphGuard.doPreventingRecursion(methodCall, true, new Computable<PsiType>() {
@Override
public PsiType compute() {
return LambdaUtil.getFunctionalInterfaceReturnType(((PsiLambdaExpression)parent).getFunctionalInterfaceType());
}
});
if (expectedType == null) {
return null;
}
expectedType = GenericsUtil.eliminateWildcards(expectedType);
} else if (parent instanceof PsiConditionalExpression) {
if (PsiUtil.isLanguageLevel8OrHigher(parent)) {
try {
final Pair<PsiType, ConstraintType> pair = inferFromConditionalExpression(parent, methodCall, typeParameter, substitutor, policy);
if (pair != null) {
return pair;
}
}
finally {
GraphInferencePolicy.forget(parent);
}
}
}
}
@@ -1054,33 +747,6 @@ public class PsiOldInferenceHelper implements PsiInferenceHelper {
if (constraint == null) {
if (methodCall instanceof PsiCallExpression) {
final PsiExpressionList argumentList = ((PsiCallExpression)methodCall).getArgumentList();
if (argumentList != null && PsiUtil.getLanguageLevel(argumentList).isAtLeast(LanguageLevel.JDK_1_8)) {
for (PsiExpression expression : argumentList.getExpressions()) {
if (expression instanceof PsiLambdaExpression || expression instanceof PsiMethodReferenceExpression) {
final PsiType functionalInterfaceType = LambdaUtil.getFunctionalInterfaceType(expression, false);
if (functionalInterfaceType == null || PsiUtil.resolveClassInType(functionalInterfaceType) == typeParameter){
return getFailedInferenceConstraint(typeParameter);
}
final PsiMethod method = LambdaUtil.getFunctionalInterfaceMethod(functionalInterfaceType);
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType);
if (method == null || methodParamsDependOn(typeParameter, expression,
functionalInterfaceType, method.getParameterList().getParameters(),
LambdaUtil.getSubstitutor(method, resolveResult))) {
if (expression instanceof PsiMethodReferenceExpression) {
return getFailedInferenceConstraint(typeParameter);
}
return null;
}
final Pair<PsiType, ConstraintType> inferredExceptionTypeConstraint = inferExceptionConstrains(typeParameter, expression, method, resolveResult.getSubstitutor());
if (inferredExceptionTypeConstraint != null) {
return inferredExceptionTypeConstraint;
}
}
}
}
PsiType[] superTypes = typeParameter.getSuperTypes();
if (superTypes.length == 0) return null;
final PsiType[] types = PsiType.createArray(superTypes.length);
@@ -1090,7 +756,6 @@ public class PsiOldInferenceHelper implements PsiInferenceHelper {
superType = TypeConversionUtil.erasure(superType);
}
if (superType == null) superType = PsiType.getJavaLangObject(myManager, scope);
if (superType == null) return null;
types[i] = superType;
}
return policy.getInferredTypeWithNoConstraint(myManager, PsiIntersectionType.createIntersection(types));
@@ -1120,113 +785,4 @@ public class PsiOldInferenceHelper implements PsiInferenceHelper {
return new Pair<PsiType, ConstraintType>(guess, constraint.getSecond());
}
private static boolean checkSameExpression(PsiExpression templateExpr, final PsiExpression expression) {
return templateExpr.equals(PsiUtil.skipParenthesizedExprDown(expression));
}
private static Pair<PsiType, ConstraintType> inferExceptionConstrains(PsiTypeParameter typeParameter,
PsiExpression expression,
PsiMethod method,
PsiSubstitutor substitutor) {
final PsiClassType[] declaredExceptions = method.getThrowsList().getReferencedTypes();
for (PsiClassType exception : declaredExceptions) {
final PsiType substitute = substitutor.substitute(exception);
if (PsiUtil.resolveClassInType(substitute) == typeParameter) {
if (expression instanceof PsiLambdaExpression) {
final PsiElement body = ((PsiLambdaExpression)expression).getBody();
if (body != null) {
final List<PsiClassType> unhandledExceptions = ExceptionUtil.getUnhandledExceptions(body);
if (unhandledExceptions.isEmpty()) {
return inferUncheckedException(typeParameter, exception, method);
}
}
}
else if (expression instanceof PsiMethodReferenceExpression) {
final PsiElement resolve = ((PsiMethodReferenceExpression)expression).resolve();
if (resolve instanceof PsiMethod) {
final PsiClassType[] declaredThrowsList = ((PsiMethod)resolve).getThrowsList().getReferencedTypes();
for (PsiClassType psiClassType : declaredThrowsList) {
if (!ExceptionUtil.isUncheckedException(psiClassType)) return null;
}
return inferUncheckedException(typeParameter, exception, method);
}
}
break;
}
}
return null;
}
private static Pair<PsiType, ConstraintType> inferUncheckedException(PsiTypeParameter typeParameter,
PsiClassType exception,
PsiMethod method) {
final Project project = typeParameter.getProject();
final PsiClass runtimeException = JavaPsiFacade.getInstance(project).findClass(CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION, method.getResolveScope());
if (runtimeException != null) {
for (PsiType superType : exception.getSuperTypes()) {
if (!InheritanceUtil.isInheritorOrSelf(runtimeException, PsiUtil.resolveClassInType(superType), true)) {
return getFailedInferenceConstraint(typeParameter);
}
}
return Pair.<PsiType, ConstraintType>create(JavaPsiFacade.getElementFactory(project).createType(runtimeException, PsiSubstitutor.EMPTY), ConstraintType.EQUALS);
}
return null;
}
private Pair<PsiType, ConstraintType> inferFromConditionalExpression(@NotNull PsiElement parent,
@NotNull PsiExpression methodCall,
@NotNull PsiTypeParameter typeParameter,
@NotNull PsiSubstitutor substitutor,
@NotNull ParameterTypeInferencePolicy policy) {
Pair<PsiType, ConstraintType> pair =
inferMethodTypeParameterFromParent(PsiUtil.skipParenthesizedExprUp(parent.getParent()), (PsiExpression)parent, typeParameter, substitutor, policy);
if (pair == null) {
final PsiExpression thenExpression = ((PsiConditionalExpression)parent).getThenExpression();
final PsiExpression elseExpression = ((PsiConditionalExpression)parent).getElseExpression();
final PsiType[] paramTypes = {((PsiMethod)typeParameter.getOwner()).getReturnType()};
if (methodCall.equals(PsiUtil.skipParenthesizedExprDown(elseExpression)) && thenExpression != null) {
final PsiType thenType = PsiResolveHelper.ourGraphGuard.doPreventingRecursion(parent, true, new Computable<PsiType>() {
@Override
public PsiType compute() {
return thenExpression.getType();
}
});
if (thenType != null) {
pair = inferTypeForMethodTypeParameterInner(typeParameter, paramTypes, new PsiType[] {thenType}, substitutor, null, policy);
}
} else if (methodCall.equals(PsiUtil.skipParenthesizedExprDown(thenExpression)) && elseExpression != null) {
final PsiType elseType = PsiResolveHelper.ourGraphGuard.doPreventingRecursion(parent, true, new Computable<PsiType>() {
@Override
public PsiType compute() {
return elseExpression.getType();
}
});
if (elseType != null) {
pair = inferTypeForMethodTypeParameterInner(typeParameter, paramTypes, new PsiType[] {elseType}, substitutor, null, policy);
}
}
}
return pair;
}
private static final ProcessCandidateParameterTypeInferencePolicy GRAPH_INFERENCE_POLICY = new GraphInferencePolicy();
private static Pair<PsiType, ConstraintType> graphInferenceFromCallContext(@NotNull final PsiExpression methodCall,
@NotNull final PsiTypeParameter typeParameter,
@NotNull final PsiCallExpression parentCall) {
if (Registry.is("disable.graph.inference", false)) return null;
final PsiExpressionList argumentList = parentCall.getArgumentList();
if (PsiDiamondType.ourDiamondGuard.currentStack().contains(parentCall)) {
PsiDiamondType.ourDiamondGuard.prohibitResultCaching(parentCall);
return FAILED_INFERENCE;
}
return PsiResolveHelper.ourGraphGuard.doPreventingRecursion(methodCall, true, new Computable<Pair<PsiType, ConstraintType>>() {
@Override
public Pair<PsiType, ConstraintType> compute() {
return GRAPH_INFERENCE_POLICY.inferTypeConstraintFromCallContext(methodCall, argumentList, parentCall, typeParameter);
}
});
}
}
@@ -17,7 +17,6 @@ package com.intellij.psi.impl.source.resolve;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.graphInference.PsiGraphInferenceHelper;
@@ -26,7 +25,8 @@ import com.intellij.psi.scope.MethodProcessorSetupFailedException;
import com.intellij.psi.scope.processor.MethodCandidatesProcessor;
import com.intellij.psi.scope.processor.MethodResolverProcessor;
import com.intellij.psi.scope.util.PsiScopesUtil;
import com.intellij.psi.util.*;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -204,10 +204,10 @@ public class PsiResolveHelperImpl implements PsiResolveHelper {
}
public PsiInferenceHelper getInferenceHelper(LanguageLevel languageLevel) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
return myTestHelper != null ? myTestHelper : new PsiOldInferenceHelper(myManager);
if (ApplicationManager.getApplication().isUnitTestMode() && myTestHelper != null) {
return myTestHelper;
}
if (languageLevel.isAtLeast(LanguageLevel.JDK_1_8) && Registry.is("enable.graph.inference", true)) {
if (languageLevel.isAtLeast(LanguageLevel.JDK_1_8)) {
return new PsiGraphInferenceHelper(myManager);
}
return new PsiOldInferenceHelper(myManager);
@@ -259,7 +259,9 @@ public class InferenceSession {
LOG.assertTrue(method != null);
final PsiExpression[] newArgs = argumentList.getExpressions();
final PsiParameter[] newParams = method.getParameterList().getParameters();
collectAdditionalConstraints(newParams, newArgs, method, ((MethodCandidateInfo)result).getSiteSubstitutor(), additionalConstraints);
if (newParams.length > 0) {
collectAdditionalConstraints(newParams, newArgs, method, ((MethodCandidateInfo)result).getSiteSubstitutor(), additionalConstraints);
}
}
}
}
@@ -1087,8 +1089,8 @@ public class InferenceSession {
if (arg instanceof PsiMethodReferenceExpression && ((PsiMethodReferenceExpression)arg).isExact()) {
final PsiParameter[] sParameters = sInterfaceMethod.getParameterList().getParameters();
final PsiParameter[] tParameters = tInterfaceMethod.getParameterList().getParameters();
LOG.assertTrue(sParameters.length == tParameters.length);
if (session != null) {
LOG.assertTrue(sParameters.length == tParameters.length);
for (int i = 0; i < tParameters.length; i++) {
session.addConstraint(new TypeEqualityConstraint(tSubstitutor.substitute(tParameters[i].getType()),
sSubstitutor.substitute(sParameters[i].getType())));
@@ -1104,15 +1106,15 @@ public class InferenceSession {
return false;
}
final boolean sPrimitive = sReturnType instanceof PsiPrimitiveType;
final boolean tPrimitive = tReturnType instanceof PsiPrimitiveType;
final boolean sPrimitive = sReturnType instanceof PsiPrimitiveType && sReturnType != PsiType.VOID;
final boolean tPrimitive = tReturnType instanceof PsiPrimitiveType && tReturnType != PsiType.VOID;
if (sPrimitive ^ tPrimitive) {
final PsiMember member = ((PsiMethodReferenceExpression)arg).getPotentiallyApplicableMember();
LOG.assertTrue(member != null);
if (member instanceof PsiMethod) {
final PsiType methodReturnType = ((PsiMethod)member).getReturnType();
if (sPrimitive && methodReturnType instanceof PsiPrimitiveType ||
if (sPrimitive && methodReturnType instanceof PsiPrimitiveType && methodReturnType != PsiType.VOID ||
tPrimitive && methodReturnType instanceof PsiClassType) {
return true;
}
@@ -15,7 +15,6 @@
*/
package com.intellij.psi.impl.source.resolve.graphInference.constraints;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession;
import com.intellij.psi.impl.source.resolve.graphInference.InferenceVariable;
@@ -78,9 +77,8 @@ public class ExpressionCompatibilityConstraint extends InputOutputConstraintForm
if (myExpression instanceof PsiCallExpression) {
final PsiExpressionList argumentList = ((PsiCallExpression)myExpression).getArgumentList();
if (argumentList != null) {
final Pair<PsiMethod,PsiSubstitutor> pair = MethodCandidateInfo.getCurrentMethod(argumentList);
final JavaResolveResult resolveResult = pair == null ? ((PsiCallExpression)myExpression).resolveMethodGenerics() : null;
final PsiMethod method = pair != null ? pair.first : (PsiMethod)resolveResult.getElement();
final JavaResolveResult resolveResult = ((PsiCallExpression)myExpression).resolveMethodGenerics();
final PsiMethod method = (PsiMethod)resolveResult.getElement();
PsiType returnType = null;
PsiTypeParameter[] typeParams = null;
if (method != null && !method.isConstructor()) {
@@ -105,21 +103,18 @@ public class ExpressionCompatibilityConstraint extends InputOutputConstraintForm
session.addCapturedVariable(typeParam);
}
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
if (pair == null) {
if (method != null) {
//typeParams are already included
final Collection<PsiTypeParameter> params = session.getTypeParams();
InferenceSession callSession = new InferenceSession(params.toArray(new PsiTypeParameter[params.size()]), ((MethodCandidateInfo)resolveResult).getSiteSubstitutor(), myExpression.getManager(), myExpression);
final PsiExpression[] args = argumentList.getExpressions();
final PsiParameter[] parameters = method.getParameterList().getParameters();
callSession.initExpressionConstraints(parameters, args, myExpression, method);
callSession.registerConstraints(returnType, myT);
if (callSession.repeatInferencePhases(true)) {
session.liftBounds(callSession.getInferenceVariables());
}
if (method != null) {
//typeParams are already included
final Collection<PsiTypeParameter> params = session.getTypeParams();
InferenceSession callSession = new InferenceSession(params.toArray(new PsiTypeParameter[params.size()]), resolveResult instanceof MethodCandidateInfo ? ((MethodCandidateInfo)resolveResult).getSiteSubstitutor()
: PsiSubstitutor.EMPTY, myExpression.getManager(), myExpression);
final PsiExpression[] args = argumentList.getExpressions();
final PsiParameter[] parameters = method.getParameterList().getParameters();
callSession.initExpressionConstraints(parameters, args, myExpression, method);
callSession.registerConstraints(returnType, myT);
if (callSession.repeatInferencePhases(true)) {
session.liftBounds(callSession.getInferenceVariables());
}
} else {
substitutor = pair.second;
}
final PsiType capturedReturnType = myExpression instanceof PsiMethodCallExpression
? PsiMethodCallExpressionImpl.captureReturnType((PsiMethodCallExpression)myExpression, method, returnType, substitutor)
@@ -17,11 +17,9 @@ package com.intellij.psi.impl.source.tree.java;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.impl.source.resolve.ParameterTypeInferencePolicy;
@@ -62,18 +60,14 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase
super(JavaElementType.METHOD_REF_EXPRESSION);
}
public static boolean onArrayType(PsiClass containingClass, MethodSignature signature) {
private static boolean arrayCreationSignature(MethodSignature signature) {
if (arrayCompatibleSignature(signature.getParameterTypes(), new Function<PsiType[], PsiType>() {
@Override
public PsiType fun(PsiType[] types) {
return types[0];
}
})) {
if (containingClass != null) {
final Project project = containingClass.getProject();
final LanguageLevel level = PsiUtil.getLanguageLevel(containingClass);
return containingClass == JavaPsiFacade.getElementFactory(project).getArrayClass(level);
}
return true;
}
return false;
}
@@ -438,9 +432,9 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase
substitutor = session.infer();
}
ClassCandidateInfo candidateInfo = null;
if ((containingClass.getContainingClass() == null || !isLocatedInStaticContext(containingClass)) &&
signature.getParameterTypes().length == 0 ||
onArrayType(containingClass, signature)) {
final boolean isArray = containingClass == JavaPsiFacade.getElementFactory(getProject()).getArrayClass(PsiUtil.getLanguageLevel(containingClass));
if (!isArray && (containingClass.getContainingClass() == null || !isLocatedInStaticContext(containingClass)) && signature.getParameterTypes().length == 0 ||
isArray && arrayCreationSignature(signature)) {
candidateInfo = new ClassCandidateInfo(containingClass, substitutor);
}
return candidateInfo == null ? JavaResolveResult.EMPTY_ARRAY : new JavaResolveResult[]{candidateInfo};
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="structure-view-impl" />
<orderEntry type="module" module-name="java-psi-impl" />
</component>
</module>
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -34,7 +34,7 @@ public class AddAllMembersProcessor extends BaseScopeProcessor {
private final PsiClass myPsiClass;
private final Map<MethodSignature,PsiMethod> myMethodsBySignature = new HashMap<MethodSignature, PsiMethod>();
public AddAllMembersProcessor(Collection<PsiElement> allMembers, PsiClass psiClass) {
public AddAllMembersProcessor(@NotNull Collection<PsiElement> allMembers, @NotNull PsiClass psiClass) {
for (PsiElement psiElement : allMembers) {
if (psiElement instanceof PsiMethod) mapMethodBySignature((PsiMethod)psiElement);
}
@@ -42,6 +42,7 @@ public class AddAllMembersProcessor extends BaseScopeProcessor {
myPsiClass = psiClass;
}
@Override
public boolean execute(@NotNull PsiElement element, ResolveState state) {
PsiMember member = (PsiMember)element;
if (!isInteresting(element)) return true;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -28,7 +28,7 @@ import java.util.Comparator;
public class AnonymousClassesSorter implements Sorter {
public static Sorter INSTANCE = new AnonymousClassesSorter();
private Comparator myComparator = new Comparator() {
private final Comparator myComparator = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
String s1 = SorterUtil.getStringPresentation(o1);
@@ -43,6 +43,7 @@ public class AnonymousClassesSorter implements Sorter {
}
};
@NotNull
@Override
public Comparator getComparator() {
return myComparator;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -31,6 +31,7 @@ public class ClassInitializerTreeElement extends PsiTreeElementBase<PsiClassInit
super(initializer);
}
@Override
public String getPresentableText() {
PsiClassInitializer initializer = getElement();
assert initializer != null;
@@ -38,6 +39,7 @@ public class ClassInitializerTreeElement extends PsiTreeElementBase<PsiClassInit
return CodeInsightBundle.message("static.class.initializer", isStatic);
}
@Override
public String getLocationString() {
PsiClassInitializer initializer = getElement();
assert initializer != null;
@@ -51,16 +53,19 @@ public class ClassInitializerTreeElement extends PsiTreeElementBase<PsiClassInit
return null;
}
@Override
@NotNull
public Collection<StructureViewTreeElement> getChildrenBase() {
return Collections.emptyList();
}
@Override
public int getAccessLevel() {
return PsiUtil.ACCESS_LEVEL_PRIVATE;
}
@Override
public int getSubLevel() {
return 0;
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -27,20 +27,24 @@ import org.jetbrains.annotations.NotNull;
public class FieldsFilter implements Filter{
@NonNls public static final String ID = "SHOW_FIELDS";
@Override
public boolean isVisible(TreeElement treeNode) {
return !(treeNode instanceof PsiFieldTreeElement);
}
@Override
@NotNull
public ActionPresentation getPresentation() {
return new ActionPresentationData(IdeBundle.message("action.structureview.show.fields"), null, PlatformIcons.FIELD_ICON);
}
@Override
@NotNull
public String getName() {
return ID;
}
@Override
public boolean isReverted() {
return true;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -27,7 +27,7 @@ import java.util.Set;
* @author Konstantin Bulenkov
*/
public class JavaAnonymousClassTreeElement extends JavaClassTreeElement {
public final static JavaAnonymousClassTreeElement[] EMPTY_ARRAY = {};
public static final JavaAnonymousClassTreeElement[] EMPTY_ARRAY = {};
private String myName;
private String myBaseName;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -45,29 +45,34 @@ public class JavaAnonymousClassesNodeProvider implements FileStructureNodeProvid
public static final String ID = "SHOW_ANONYMOUS";
public static final String JAVA_ANONYMOUS_PROPERTY_NAME = "java.anonymous.provider";
@NotNull
@Override
public Collection<JavaAnonymousClassTreeElement> provideNodes(TreeElement node) {
public Collection<JavaAnonymousClassTreeElement> provideNodes(@NotNull TreeElement node) {
if (node instanceof PsiMethodTreeElement || node instanceof PsiFieldTreeElement || node instanceof ClassInitializerTreeElement) {
final PsiElement el = ((PsiTreeElementBase)node).getElement();
for (AnonymousElementProvider provider : Extensions.getExtensions(AnonymousElementProvider.EP_NAME)) {
final PsiElement[] elements = provider.getAnonymousElements(el);
if (elements != null && elements.length > 0) {
List<JavaAnonymousClassTreeElement> result = new ArrayList<JavaAnonymousClassTreeElement>(elements.length);
for (PsiElement element : elements) {
result.add(new JavaAnonymousClassTreeElement((PsiAnonymousClass)element, new HashSet<PsiClass>()));
if (el != null) {
for (AnonymousElementProvider provider : Extensions.getExtensions(AnonymousElementProvider.EP_NAME)) {
final PsiElement[] elements = provider.getAnonymousElements(el);
if (elements.length > 0) {
List<JavaAnonymousClassTreeElement> result = new ArrayList<JavaAnonymousClassTreeElement>(elements.length);
for (PsiElement element : elements) {
result.add(new JavaAnonymousClassTreeElement((PsiAnonymousClass)element, new HashSet<PsiClass>()));
}
return result;
}
return result;
}
}
}
return Collections.emptyList();
}
@NotNull
@Override
public String getCheckBoxText() {
return "Show Anonymous Classes";
}
@NotNull
@Override
public Shortcut[] getShortcut() {
return new Shortcut[]{KeyboardShortcut.fromString(SystemInfo.isMac ? "meta I" : "control I")};
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -35,6 +35,7 @@ public class JavaClassTreeElement extends JavaClassTreeElementBase<PsiClass> {
myParents.add(cls);
}
@Override
@NotNull
public Collection<StructureViewTreeElement> getChildrenBase() {
return getClassChildren();
@@ -89,10 +90,12 @@ public class JavaClassTreeElement extends JavaClassTreeElementBase<PsiClass> {
return myParents;
}
@Override
public String getPresentableText() {
return getElement().getName();
}
@Override
public boolean isPublic() {
return getElement().getParent() instanceof PsiFile || super.isPublic();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -46,6 +46,7 @@ public abstract class JavaClassTreeElementBase<Value extends PsiElement> extends
return !(element instanceof PsiModifierListOwner) || ((PsiModifierListOwner)element).hasModifierProperty(PsiModifier.PUBLIC);
}
@Override
public int getAccessLevel() {
final PsiModifierList modifierList = ((PsiModifierListOwner)getElement()).getModifierList();
if (modifierList == null) {
@@ -54,6 +55,7 @@ public abstract class JavaClassTreeElementBase<Value extends PsiElement> extends
return PsiUtil.getAccessLevel(modifierList);
}
@Override
public int getSubLevel() {
return 0;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -31,10 +31,12 @@ public class JavaFileTreeElement extends PsiTreeElementBase<PsiClassOwner> imple
super(file);
}
@Override
public String getPresentableText() {
return getElement().getName();
}
@Override
@NotNull
public Collection<StructureViewTreeElement> getChildrenBase() {
PsiClass[] classes = getElement().getClasses();
@@ -45,4 +47,4 @@ public class JavaFileTreeElement extends PsiTreeElementBase<PsiClassOwner> imple
return result;
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -15,14 +15,10 @@
*/
package com.intellij.ide.structureView.impl.java;
import com.intellij.ide.actions.ViewStructureAction;
import com.intellij.ide.structureView.StructureViewModel;
import com.intellij.ide.structureView.StructureViewTreeElement;
import com.intellij.ide.structureView.TextEditorBasedStructureViewModel;
import com.intellij.ide.util.treeView.smartTree.Filter;
import com.intellij.ide.util.treeView.smartTree.Grouper;
import com.intellij.ide.util.treeView.smartTree.NodeProvider;
import com.intellij.ide.util.treeView.smartTree.Sorter;
import com.intellij.ide.util.treeView.smartTree.*;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.*;
import com.intellij.ui.PlaceHolder;
@@ -35,19 +31,16 @@ import java.util.Collection;
public class JavaFileTreeModel extends TextEditorBasedStructureViewModel implements StructureViewModel.ElementInfoProvider, PlaceHolder<String> {
private static final Collection<NodeProvider> NODE_PROVIDERS = Arrays.<NodeProvider>asList(new JavaInheritedMembersNodeProvider(),
new JavaAnonymousClassesNodeProvider());
private final PsiClassOwner myFile;
private String myPlace;
public JavaFileTreeModel(@NotNull PsiClassOwner file, @Nullable Editor editor) {
super(editor, file);
myFile = file;
}
@Override
@NotNull
public Filter[] getFilters() {
return new Filter[]{new FieldsFilter(),
new PublicElementsFilter()};
return new Filter[]{new FieldsFilter(), new PublicElementsFilter()};
}
@NotNull
@@ -65,7 +58,7 @@ public class JavaFileTreeModel extends TextEditorBasedStructureViewModel impleme
@Override
@NotNull
public StructureViewTreeElement getRoot() {
return new JavaFileTreeElement(myFile);
return new JavaFileTreeElement(getPsiFile());
}
@Override
@@ -77,15 +70,15 @@ public class JavaFileTreeModel extends TextEditorBasedStructureViewModel impleme
@NotNull
public Sorter[] getSorters() {
return new Sorter[] {
ViewStructureAction.isInStructureViewPopup(this) ? KindSorter.POPUP_INSTANCE : KindSorter.INSTANCE,
TreeStructureUtil.isInStructureViewPopup(this) ? KindSorter.POPUP_INSTANCE : KindSorter.INSTANCE,
VisibilitySorter.INSTANCE,
AnonymousClassesSorter.INSTANCE,
Sorter.ALPHA_SORTER};
}
@Override
protected PsiFile getPsiFile() {
return myFile;
protected PsiClassOwner getPsiFile() {
return (PsiClassOwner)super.getPsiFile();
}
@Override
@@ -130,7 +123,7 @@ public class JavaFileTreeModel extends TextEditorBasedStructureViewModel impleme
}
@Override
public void setPlace(String place) {
public void setPlace(@NotNull String place) {
myPlace = place;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -20,6 +20,7 @@ import com.intellij.ide.util.InheritedMembersNodeProvider;
import com.intellij.ide.util.treeView.smartTree.TreeElement;
import com.intellij.psi.*;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import java.util.*;
@@ -27,8 +28,9 @@ import java.util.*;
* @author Konstantin Bulenkov
*/
public class JavaInheritedMembersNodeProvider extends InheritedMembersNodeProvider {
@NotNull
@Override
public Collection<TreeElement> provideNodes(TreeElement node) {
public Collection<TreeElement> provideNodes(@NotNull TreeElement node) {
if (node instanceof JavaClassTreeElement) {
final PsiClass aClass = ((JavaClassTreeElement)node).getValue();
Collection<PsiElement> inherited = new LinkedHashSet<PsiElement>();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -24,14 +24,18 @@ import org.jetbrains.annotations.NotNull;
import java.util.Comparator;
public class KindSorter implements Sorter {
public static final Sorter INSTANCE = new KindSorter();
public static final Sorter POPUP_INSTANCE = new KindSorter(){{isPopup = true;}};
public static final Sorter INSTANCE = new KindSorter(false);
public static final Sorter POPUP_INSTANCE = new KindSorter(true);
public KindSorter(boolean isPopup) {
this.isPopup = isPopup;
}
@NonNls public static final String ID = "KIND";
boolean isPopup = false;
private final boolean isPopup;
private final Comparator COMPARATOR = new Comparator() {
@Override
public int compare(final Object o1, final Object o2) {
return getWeight(o1) - getWeight(o2);
}
@@ -65,19 +69,24 @@ public class KindSorter implements Sorter {
}
};
@Override
@NotNull
public Comparator getComparator() {
return COMPARATOR;
}
@Override
public boolean isVisible() {
return false;
}
@Override
@NotNull
public ActionPresentation getPresentation() {
throw new IllegalStateException();
}
@Override
@NotNull
public String getName() {
return ID;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -32,8 +32,9 @@ import java.util.Map;
public class PropertiesGrouper implements Grouper{
@NonNls public static final String ID = "SHOW_PROPERTIES";
@Override
@NotNull
public Collection<Group> group(final AbstractTreeNode parent, Collection<TreeElement> children) {
public Collection<Group> group(@NotNull final AbstractTreeNode parent, @NotNull Collection<TreeElement> children) {
if (parent.getValue() instanceof PropertyGroup) return Collections.emptyList();
Map<Group,Group> result = new THashMap<Group, Group>();
for (TreeElement o : children) {
@@ -60,11 +61,13 @@ public class PropertiesGrouper implements Grouper{
return result.values();
}
@Override
@NotNull
public ActionPresentation getPresentation() {
return new ActionPresentationData(IdeBundle.message("action.structureview.show.properties"), null, PlatformIcons.PROPERTY_ICON);
}
@Override
@NotNull
public String getName() {
return ID;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -90,14 +90,19 @@ public class PropertyGroup implements Group, ColoredItemPresentation, AccessLeve
return null;
}
@Override
@NotNull
public Collection<TreeElement> getChildren() {
return myChildren;
}
@Override
@NotNull
public ItemPresentation getPresentation() {
return this;
}
@Override
public Icon getIcon(boolean open) {
if (isStatic()) {
if (getGetter() != null && getSetter() != null) {
@@ -128,10 +133,12 @@ public class PropertyGroup implements Group, ColoredItemPresentation, AccessLeve
return myIsStatic;
}
@Override
public String getLocationString() {
return null;
}
@Override
public String getPresentableText() {
return myPropertyName + ": " + myPropertyType.getPresentableText();
}
@@ -174,6 +181,7 @@ public class PropertyGroup implements Group, ColoredItemPresentation, AccessLeve
return PropertyUtil.suggestGetterName(myPropertyName, myPropertyType);
}
@Override
public int getAccessLevel() {
int result = PsiUtil.ACCESS_LEVEL_PRIVATE;
if (getGetter() != null) {
@@ -188,6 +196,7 @@ public class PropertyGroup implements Group, ColoredItemPresentation, AccessLeve
return result;
}
@Override
public int getSubLevel() {
return 0;
}
@@ -235,6 +244,7 @@ public class PropertyGroup implements Group, ColoredItemPresentation, AccessLeve
return icon;
}
@Override
public TextAttributesKey getTextAttributesKey() {
return isDeprecated() ? CodeInsightColors.DEPRECATED_ATTRIBUTES : null;
}
@@ -258,6 +268,7 @@ public class PropertyGroup implements Group, ColoredItemPresentation, AccessLeve
return this;
}
@Override
public int getWeight() {
return 60;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -31,11 +31,13 @@ public class PsiFieldTreeElement extends JavaClassTreeElementBase<PsiField> impl
super(isInherited,field);
}
@Override
@NotNull
public Collection<StructureViewTreeElement> getChildrenBase() {
return Collections.emptyList();
}
@Override
public String getPresentableText() {
return StringUtil.replace(PsiFormatUtil.formatVariable(
getElement(),
@@ -48,6 +50,8 @@ public class PsiFieldTreeElement extends JavaClassTreeElementBase<PsiField> impl
return getElement();
}
@Override
@NotNull
public String getAlphaSortKey() {
final PsiField field = getElement();
if (field != null) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -127,6 +127,7 @@ public class PsiMethodTreeElement extends JavaClassTreeElementBase<PsiMethod> im
return getElement();
}
@NotNull
@Override
public String getAlphaSortKey() {
final PsiMethod method = getElement();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -27,6 +27,7 @@ import org.jetbrains.annotations.NotNull;
public class PublicElementsFilter implements Filter{
@NonNls public static final String ID = "SHOW_NON_PUBLIC";
@Override
public boolean isVisible(TreeElement treeNode) {
if (treeNode instanceof JavaClassTreeElementBase) {
return ((JavaClassTreeElementBase)treeNode).isPublic();
@@ -36,16 +37,19 @@ public class PublicElementsFilter implements Filter{
}
}
@Override
@NotNull
public ActionPresentation getPresentation() {
return new ActionPresentationData(IdeBundle.message("action.structureview.show.non.public"), null, PlatformIcons.PRIVATE_ICON);
}
@Override
@NotNull
public String getName() {
return ID;
}
@Override
public boolean isReverted() {
return true;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -25,6 +25,7 @@ import com.intellij.psi.PsiModifierList;
import com.intellij.psi.SmartPointerManager;
import com.intellij.psi.SmartPsiElementPointer;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
@@ -47,6 +48,8 @@ public class SuperTypeGroup implements Group, ItemPresentation, AccessLevelProvi
mySuperClassPointer = SmartPointerManager.getInstance(superClass.getProject()).createSmartPsiElementPointer(superClass);
}
@Override
@NotNull
public Collection<TreeElement> getChildren() {
return myChildren;
}
@@ -56,10 +59,13 @@ public class SuperTypeGroup implements Group, ItemPresentation, AccessLevelProvi
return (PsiClass)mySuperClassPointer.getElement();
}
@Override
@NotNull
public ItemPresentation getPresentation() {
return this;
}
@Override
public Icon getIcon(boolean open) {
switch (myOverrides) {
case IMPLEMENTS:
@@ -73,10 +79,12 @@ public class SuperTypeGroup implements Group, ItemPresentation, AccessLevelProvi
return null; // Can't be
}
@Override
public String getLocationString() {
return null;
}
@Override
public String getPresentableText() {
return toString();
}
@@ -108,12 +116,14 @@ public class SuperTypeGroup implements Group, ItemPresentation, AccessLevelProvi
return this;
}
@Override
public int getAccessLevel() {
final PsiClass superClass = getSuperClass();
PsiModifierList modifierList = superClass == null ? null : superClass.getModifierList();
return modifierList == null ? PsiUtil.ACCESS_LEVEL_PUBLIC : PsiUtil.getAccessLevel(modifierList);
}
@Override
public int getSubLevel() {
return 1;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -37,8 +37,9 @@ public class SuperTypesGrouper implements Grouper{
public static final Key<WeakReference<PsiMethod>> SUPER_METHOD_KEY = Key.create("StructureTreeBuilder.SUPER_METHOD_KEY");
@NonNls public static final String ID = "SHOW_INTERFACES";
@Override
@NotNull
public Collection<Group> group(final AbstractTreeNode parent, Collection<TreeElement> children) {
public Collection<Group> group(@NotNull final AbstractTreeNode parent, @NotNull Collection<TreeElement> children) {
if (isParentGrouped(parent)) return Collections.emptyList();
Map<Group, SuperTypeGroup> groups = new THashMap<Group, SuperTypeGroup>();
@@ -112,12 +113,14 @@ public class SuperTypesGrouper implements Grouper{
}
@Override
@NotNull
public ActionPresentation getPresentation() {
return new ActionPresentationData(IdeBundle.message("action.structureview.group.methods.by.defining.type"), null,
AllIcons.General.ImplementingMethod);
}
@Override
@NotNull
public String getName() {
return ID;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -15,8 +15,6 @@
*/
package com.intellij.ide.structureView.impl.java;
import com.intellij.ide.util.treeView.AlphaComparator;
import com.intellij.ide.util.treeView.SourceComparator;
import com.intellij.openapi.diagnostic.Logger;
import org.jetbrains.annotations.NotNull;
@@ -25,8 +23,6 @@ import java.util.Comparator;
public class VisibilityComparator implements Comparator {
private static final Logger LOG = Logger.getInstance("#com.intellij.ide.structureView.impl.java.VisibilityComparator");
private static final int GROUP_ACCESS_SUBLEVEL = 1;
public static Comparator THEN_SOURCE = new VisibilityComparator(SourceComparator.INSTANCE);
public static Comparator THEN_ALPHA = new VisibilityComparator(AlphaComparator.INSTANCE);
public static Comparator IMSTANCE = new VisibilityComparator(null);
private final Comparator myNextComparator;
@@ -36,6 +32,7 @@ public class VisibilityComparator implements Comparator {
myNextComparator = comparator;
}
@Override
public int compare(@NotNull Object descriptor1, @NotNull Object descriptor2) {
int accessLevel1 = getAccessLevel(descriptor1);
int accessLevel2 = getAccessLevel(descriptor2);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -30,33 +30,42 @@ public class VisibilitySorter implements Sorter{
public static final Sorter INSTANCE = new VisibilitySorter();
private static final ActionPresentation PRESENTATION = new ActionPresentation() {
@Override
@NotNull
public String getText() {
return IdeBundle.message("action.structureview.sort.by.visibility");
}
@Override
public String getDescription() {
return null;
}
@Override
public Icon getIcon() {
return AllIcons.ObjectBrowser.VisibilitySort;
}
};
@NonNls public static final String ID = "VISIBILITY_SORTER";
@Override
@NotNull
public Comparator getComparator() {
return VisibilityComparator.IMSTANCE;
}
@Override
public boolean isVisible() {
return true;
}
@Override
@NotNull
public ActionPresentation getPresentation() {
return PRESENTATION;
}
@Override
@NotNull
public String getName() {
return ID;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -0,0 +1,4 @@
class Foo {{
ret<caret>;
ret<caret>;
}}
@@ -0,0 +1,4 @@
class Foo {{
return<caret>;
return<caret>;
}}
@@ -0,0 +1,4 @@
class Foo {{
System.out.ap<caret>
System.out.ap<caret>
}}
@@ -0,0 +1,4 @@
class Foo {{
System.out.append(<caret>)
System.out.append(<caret>)
}}
@@ -1,8 +1,8 @@
class IntStream {
private void foo(IntStream s) {
s.map<error descr="Ambiguous method call: both 'IntStream.map(IntUnaryOperator)' and 'IntStream.map(ObjIntFunction<Integer>)' match">(i -> 1 << i)</error>;
s.map(i -> <error descr="Operator '<<' cannot be applied to 'int', '<lambda parameter>'">1 << i</error>);
s.map<error descr="Ambiguous method call: both 'IntStream.map(IntUnaryOperator)' and 'IntStream.map(ObjIntFunction<Integer>)' match">(i -> 1)</error>;
s.map<error descr="Ambiguous method call: both 'IntStream.map(IntUnaryOperator)' and 'IntStream.map(ObjIntFunction<Integer>)' match">(i -> i)</error>;
s.map<error descr="Ambiguous method call: both 'IntStream.map(IntUnaryOperator)' and 'IntStream.map(ObjIntFunction<T>)' match">(i -> i)</error>;
}
public static void main(String[] args) {
@@ -25,7 +25,7 @@ class ReturnTypeIncompatibility {
}
public static void main(String[] args) {
call<error descr="Ambiguous method call: both 'ReturnTypeIncompatibility.call(I1<Integer>)' and 'ReturnTypeIncompatibility.call(I2<P>)' match">(i-> {return i;})</error>;
call<error descr="Ambiguous method call: both 'ReturnTypeIncompatibility.call(I1<P>)' and 'ReturnTypeIncompatibility.call(I2<P>)' match">(i-> {return i;})</error>;
}
}
@@ -0,0 +1,46 @@
class Test {
interface I { void i_bar(); }
interface I1<T> { T i1_bar(); }
private void m(I i) {System.out.println(i);}
private void <warning descr="Private method 'm(Test.I1<java.lang.String>)' is never used">m</warning>(I1<String> i1) {System.out.println(i1);}
void test() {
m(Test::foo);
}
public static int foo() {
return 0;
}
}
class Test1 {
interface I { void i_bar(); }
interface I1<T> { T i1_bar(); }
void m(I i) { System.out.println(i);}
void m(I1<String> i1) { System.out.println(i1);}
void test() {
m(Test1::foo);
}
public static String foo() {return "";}
}
class Test2 {
interface I { void i_bar(); }
interface I1<T> { T i1_bar(); }
void m(I i) { System.out.println(i);}
void m(I1<String> i1) { System.out.println(i1);}
void test() {
m(Test2::foo);
}
public static void foo() {}
}
@@ -0,0 +1,44 @@
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collector;
class Stuff {
public enum Type { A }
private final int value;
private final Type type;
public Stuff(int value, Type type) {
this.value = value;
this.type = type;
}
public int getValue() {
return value;
}
public Type getType() {
return type;
}
}
class FakeErrors {
{
Collector<Stuff, ?, Map<Stuff.Type, Optional<Stuff>>> collector =
groupingBy(Stuff::getType,
reducing((d1, d2) -> {
boolean b = d1.getValue() > d2.getValue();
return d1;
}));
}
public static <T> Collector<T, ?, Optional<Stuff>> reducing(BinaryOperator<T> op) {
return null;
}
public static <T, K, A, D>
Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,
Collector<? super T, A, D> downstream) {
return null;
}
}
@@ -0,0 +1,11 @@
class Test {
interface I {
Object m();
}
void m(I i) {}
{
m<error descr="'m(Test.I)' in 'Test' cannot be applied to '(<method reference>)'">(String[]::new)</error>;
}
}
@@ -0,0 +1,6 @@
class A {
@org.jetbrains.annotations.Contract("null,_->fail")
public int method<caret>(Object i, Object j) {
return 0;
}
}
@@ -1,6 +1,6 @@
class Test {
void foo() {
final Foo<Number> a = new Foo<Number>(1);
final Foo<Number> a = new Foo<>(1);
}
}
@@ -4,7 +4,7 @@ interface SAM<X> {
class Foo {
void test() {
SAM<String> c = (i, j) -> "" + i + j;
SAM<X> c = (i, j) -> "" + i + j;
SAM<Integer> s3 = m(c);
}
<X> SAM<X> m(SAM<X> s) { return null; }
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -28,6 +28,7 @@ import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiMethod
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.psi.codeStyle.CommonCodeStyleSettings
import com.intellij.testFramework.EditorTestUtil
public class NormalCompletionTest extends LightFixtureCompletionTestCase {
@Override
@@ -874,6 +875,16 @@ public class ListUtils {
doAntiTest()
}
private void doMultiCaretTest() throws Exception {
EditorTestUtil.enableMultipleCarets()
try {
doTest()
}
finally {
EditorTestUtil.disableMultipleCarets()
}
}
private void doTest() throws Exception {
configure()
checkResult();
@@ -1365,6 +1376,14 @@ class Foo {{
}}'''
}
public void testMulticaretSingleItemInsertion() {
doMultiCaretTest()
}
public void testMulticaretMethodWithParen() {
doMultiCaretTest()
}
public void "test complete lowercase class name"() {
myFixture.addClass("package foo; public class myClass {}")
myFixture.configureByText "a.java", """
@@ -20,6 +20,7 @@ import com.intellij.codeInspection.compiler.JavacQuirksInspection;
import com.intellij.codeInspection.redundantCast.RedundantCastInspection;
import com.intellij.codeInspection.uncheckedWarnings.UncheckedWarningLocalInspection;
import com.intellij.codeInspection.unusedSymbol.UnusedSymbolLocalInspection;
import com.intellij.pom.java.LanguageLevel;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
@@ -52,4 +53,9 @@ public class AmbiguousMethodCallTest extends LightDaemonAnalyzerTestCase {
public void testMultipleInheritance() throws Exception {
doTest(false, false);
}
@Override
protected LanguageLevel getLanguageLevel() {
return LanguageLevel.JDK_1_7;
}
}
@@ -0,0 +1,55 @@
/*
* Copyright 2000-2014 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.daemon.lambda;
import com.intellij.codeInsight.daemon.LightDaemonAnalyzerTestCase;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.unusedSymbol.UnusedSymbolLocalInspection;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.testFramework.IdeaTestUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
public class MostSpecificResolutionTest extends LightDaemonAnalyzerTestCase {
@NonNls static final String BASE_PATH = "/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific";
@NotNull
@Override
protected LocalInspectionTool[] configureLocalInspectionTools() {
return new LocalInspectionTool[]{
new UnusedSymbolLocalInspection(),
};
}
public void testVoidConflict() throws Exception {
doTest();
}
private void doTest() {
doTest(true);
}
private void doTest(boolean warnings) {
IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_8, getModule(), getTestRootDisposable());
doTestNewInference(BASE_PATH + "/" + getTestName(false) + ".java", warnings, false);
}
@Override
protected Sdk getProjectJDK() {
return IdeaTestUtil.getMockJdk18();
}
}
@@ -126,6 +126,10 @@ public class NewLambdaHighlightingTest extends LightDaemonAnalyzerTestCase {
doTest();
}
public void testIDEA119535() throws Exception {
doTest();
}
private void doTest() {
doTest(false);
}
@@ -165,6 +165,10 @@ public class NewMethodRefHighlightingTest extends LightDaemonAnalyzerTestCase {
doTest();
}
public void testIncorrectArrayCreationSignature() throws Exception {
doTest();
}
private void doTest() {
doTest(false);
}
@@ -1,5 +1,7 @@
package com.intellij.codeInsight.daemon.quickFix;
import com.intellij.pom.java.LanguageLevel;
public class RemoveRedundantArgumentTest extends LightQuickFixParameterizedTestCase {
public void test() throws Exception { doAllTests(); }
@@ -9,4 +11,8 @@ public class RemoveRedundantArgumentTest extends LightQuickFixParameterizedTestC
return "/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantArgument";
}
@Override
protected LanguageLevel getLanguageLevel() {
return LanguageLevel.JDK_1_7;
}
}
@@ -17,6 +17,7 @@ package com.intellij.codeInsight.daemon.quickFix;
import com.intellij.codeInspection.ExplicitTypeCanBeDiamondInspection;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.pom.java.LanguageLevel;
import org.jetbrains.annotations.NotNull;
@@ -37,4 +38,8 @@ public class Simplify2DiamondInspectionsTest extends LightQuickFixParameterizedT
return "/codeInsight/daemonCodeAnalyzer/quickFix/explicit2diamond";
}
@Override
protected LanguageLevel getLanguageLevel() {
return LanguageLevel.JDK_1_7;
}
}
@@ -16,6 +16,8 @@
package com.intellij.codeInsight.daemon.quickFix;
import com.intellij.pom.java.LanguageLevel;
public class VariableTypeFromCallTest extends LightQuickFixParameterizedTestCase {
public void test() throws Exception { doAllTests(); }
@@ -25,5 +27,9 @@ public class VariableTypeFromCallTest extends LightQuickFixParameterizedTestCase
return "/codeInsight/daemonCodeAnalyzer/quickFix/varTypeFromCall";
}
@Override
protected LanguageLevel getLanguageLevel() {
return LanguageLevel.JDK_1_7;
}
}
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2014 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.execution;
import com.intellij.execution.actions.ConfigurationContext;
@@ -5,7 +20,9 @@ import com.intellij.execution.actions.ConfigurationFromContext;
import com.intellij.execution.actions.RunConfigurationProducer;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.junit.JUnitConfiguration;
import com.intellij.openapi.actionSystem.DataConstants;
import com.intellij.execution.junit.JUnitConfigurationProducer;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ex.PathManagerEx;
import com.intellij.openapi.module.Module;
@@ -25,6 +42,7 @@ import com.intellij.testFramework.IdeaTestCase;
import com.intellij.testFramework.MapDataContext;
import com.intellij.testFramework.PsiTestUtil;
import com.intellij.testFramework.TempFiles;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
@@ -64,7 +82,7 @@ public abstract class BaseConfigurationTestCase extends IdeaTestCase {
ModuleRootModificationUtil.addModuleLibrary(module, mockJUnit.getUrl());
ModuleRootModificationUtil.setModuleSdk(module, ModuleRootManager.getInstance(myModule).getSdk());
GlobalSearchScope scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module);
VirtualFile testCase = mockJUnit.findChild("junit").findChild("framework").findChild("TestCase.java");
VirtualFile testCase = mockJUnit.findFileByRelativePath("junit/framework/TestCase.java");
assertNotNull(testCase);
assertTrue(scope.contains(testCase));
Module missingModule = createTempModule();
@@ -139,37 +157,39 @@ public abstract class BaseConfigurationTestCase extends IdeaTestCase {
return JavaPsiFacade.getInstance(myProject).findClass(qualifiedName, scope);
}
protected JUnitConfiguration createJUnitConfiguration(final PsiElement psiElement,
final Class producerClass,
final MapDataContext dataContext) {
protected JUnitConfiguration createJUnitConfiguration(@NotNull PsiElement psiElement,
@NotNull Class<? extends JUnitConfigurationProducer> producerClass,
@NotNull MapDataContext dataContext) {
ConfigurationContext context = createContext(psiElement, dataContext);
RunConfigurationProducer producer = RunConfigurationProducer.getInstance(producerClass);
assert producer != null;
ConfigurationFromContext fromContext = producer.createConfigurationFromContext(context);
assertNotNull(fromContext);
return (JUnitConfiguration)fromContext.getConfiguration();
}
protected final <T extends RunConfiguration> T createConfiguration(PsiElement psiElement) {
return (T)createConfiguration(psiElement, new MapDataContext());
protected final <T extends RunConfiguration> T createConfiguration(@NotNull PsiElement psiElement) {
return createConfiguration(psiElement, new MapDataContext());
}
protected <T extends RunConfiguration> T createConfiguration(PsiElement psiElement, MapDataContext dataContext) {
protected <T extends RunConfiguration> T createConfiguration(@NotNull PsiElement psiElement, @NotNull MapDataContext dataContext) {
ConfigurationContext context = createContext(psiElement, dataContext);
RunnerAndConfigurationSettings settings = context.getConfiguration();
return settings == null ? null : (T)settings.getConfiguration();
@SuppressWarnings("unchecked") T configuration = settings == null ? null : (T)settings.getConfiguration();
return configuration;
}
public ConfigurationContext createContext(PsiElement psiClass) {
public ConfigurationContext createContext(@NotNull PsiElement psiClass) {
MapDataContext dataContext = new MapDataContext();
return createContext(psiClass, dataContext);
}
public ConfigurationContext createContext(PsiElement psiClass, MapDataContext dataContext) {
dataContext.put(DataConstants.PROJECT, myProject);
if (dataContext.getData(DataConstants.MODULE) == null) {
dataContext.put(DataConstants.MODULE, ModuleUtilCore.findModuleForPsiElement(psiClass));
public ConfigurationContext createContext(@NotNull PsiElement psiClass, @NotNull MapDataContext dataContext) {
dataContext.put(CommonDataKeys.PROJECT, myProject);
if (LangDataKeys.MODULE.getData(dataContext) == null) {
dataContext.put(LangDataKeys.MODULE, ModuleUtilCore.findModuleForPsiElement(psiClass));
}
dataContext.put(Location.LOCATION, PsiLocation.fromPsiElement(psiClass));
dataContext.put(Location.DATA_KEY, PsiLocation.fromPsiElement(psiClass));
return ConfigurationContext.getFromContext(dataContext);
}
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2014 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.execution;
import com.intellij.execution.application.ApplicationConfiguration;
@@ -6,6 +21,7 @@ import com.intellij.execution.configurations.RuntimeConfigurationException;
import com.intellij.execution.impl.RunnerAndConfigurationSettingsImpl;
import com.intellij.execution.junit.AllInPackageConfigurationProducer;
import com.intellij.execution.junit.JUnitConfiguration;
import com.intellij.execution.junit.JUnitConfigurationProducer;
import com.intellij.execution.junit.JUnitConfigurationType;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
@@ -19,6 +35,7 @@ import com.intellij.refactoring.move.moveMembers.MoveMembersProcessor;
import com.intellij.refactoring.rename.RenameProcessor;
import com.intellij.testFramework.MapDataContext;
import com.intellij.util.containers.HashSet;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
@@ -38,6 +55,7 @@ public class ConfigurationRefactoringsTest extends BaseConfigurationTestCase {
"}";
public void testRenameApplication() throws IOException {
PsiClass psiClass = mySource.createClass("Application", APPLICATION_CODE);
assertNotNull(psiClass);
ApplicationConfiguration configuration = createConfiguration(psiClass);
assertNotNull(configuration);
rename(psiClass, "NewName");
@@ -52,6 +70,7 @@ public class ConfigurationRefactoringsTest extends BaseConfigurationTestCase {
public void testMoveApplication() throws IOException {
PsiClass psiClass = mySource.createClass("Application", APPLICATION_CODE);
assertNotNull(psiClass);
ApplicationConfiguration configuration = createConfiguration(psiClass);
move(psiClass, "pkg");
try {
@@ -71,15 +90,16 @@ public class ConfigurationRefactoringsTest extends BaseConfigurationTestCase {
JUnitConfiguration configuration = createJUnitConfiguration(psiPackage, AllInPackageConfigurationProducer.class, new MapDataContext());
rename(psiPackage, "pkg2");
checkPackage("pkg2", configuration);
PsiPackage outter = mySource.createPackage("outterPkg");
move(JavaPsiFacade.getInstance(myProject).findPackage("pkg2"), outter.getQualifiedName());
checkPackage("outterPkg.pkg2", configuration);
rename(outter, "outter2");
checkPackage("outter2.pkg2", configuration);
PsiPackage outer = mySource.createPackage("outerPkg");
move(JavaPsiFacade.getInstance(myProject).findPackage("pkg2"), outer.getQualifiedName());
checkPackage("outerPkg.pkg2", configuration);
rename(outer, "outer2");
checkPackage("outer2.pkg2", configuration);
}
public void testRenameJUnitContainingPackage() throws IOException {
PsiClass psiClass = mySource.createClass("ATest", TEST_CODE);
assertNotNull(psiClass);
JUnitConfiguration configuration = createConfiguration(psiClass);
PsiPackage psiPackage = mySource.createPackage("pkg");
move(psiClass, "pkg");
@@ -95,6 +115,7 @@ public class ConfigurationRefactoringsTest extends BaseConfigurationTestCase {
public void testRefactorTestMethod() throws IOException {
PsiClass psiClass = mySource.createClass("ATest", TEST_CODE);
assertNotNull(psiClass);
PsiMethod testMethod = psiClass.findMethodsByName("test", false)[0];
JUnitConfiguration configuration = createConfiguration(testMethod);
rename(testMethod, "test1");
@@ -110,6 +131,7 @@ public class ConfigurationRefactoringsTest extends BaseConfigurationTestCase {
PsiClass otherTest = mySource.createClass("ATest", TEST_CODE);
HashSet<PsiMember> members = new HashSet<PsiMember>();
assertNotNull(psiClass);
members.add(psiClass.findMethodsByName("test1", false)[0]);
moveMembers(otherTest, members);
psiClass = configuration.getConfigurationModule().findClass(configuration.getPersistentData().getMainClassName());
@@ -117,6 +139,7 @@ public class ConfigurationRefactoringsTest extends BaseConfigurationTestCase {
checkClassName("ATest", configuration);
assertEquals("ATest.test1", configuration.getName());
assertNotNull(psiClass);
PsiMethod otherMethod = psiClass.findMethodsByName("otherMethod", false)[0];
rename(otherMethod, "newName");
checkMethodName("test1", configuration);
@@ -124,11 +147,13 @@ public class ConfigurationRefactoringsTest extends BaseConfigurationTestCase {
public void testRenameBadTestClass() throws IOException {
PsiClass psiClass = mySource.createClass("NotATest", NOT_A_TEST);
JUnitConfiguration configuration = new JUnitConfiguration("notATest", myProject, JUnitConfigurationType.getInstance().getConfigurationFactories()[0]);
assertNotNull(psiClass);
JUnitConfigurationType instance = JUnitConfigurationType.getInstance();
assertNotNull(instance);
JUnitConfiguration configuration = new JUnitConfiguration("notATest", myProject, instance.getConfigurationFactories()[0]);
configuration.setMainClass(psiClass);
configuration.setModule(configuration.getValidModules().iterator().next());
checkConfigurationException("NotATest isn't test class", configuration);
RunManagerEx.getInstanceEx(myProject).setTemporaryConfiguration(new RunnerAndConfigurationSettingsImpl(null, configuration, false));
@@ -144,7 +169,7 @@ public class ConfigurationRefactoringsTest extends BaseConfigurationTestCase {
assertEquals("test2", data.getMethodName());
}
private void checkConfigurationException(String expectedExceptionMessage, JUnitConfiguration configuration) {
private static void checkConfigurationException(String expectedExceptionMessage, JUnitConfiguration configuration) {
try {
configuration.checkConfiguration();
}
@@ -156,13 +181,18 @@ public class ConfigurationRefactoringsTest extends BaseConfigurationTestCase {
}
public void testRefactorOtherClass() throws IOException {
JUnitConfiguration configuration = createConfiguration(mySource.createClass("ATest", TEST_CODE));
PsiClass psiClass = mySource.createClass("Application", APPLICATION_CODE);
PsiClass psiClass = mySource.createClass("ATest", TEST_CODE);
assertNotNull(psiClass);
JUnitConfiguration configuration = createConfiguration(psiClass);
psiClass = mySource.createClass("Application", APPLICATION_CODE);
assertNotNull(psiClass);
rename(psiClass, "NewName");
checkClassName("ATest", configuration);
mySource.createPackage("pkg");
psiClass = mySource.findClass("NewName");
assertNotNull(psiClass);
move(psiClass, "pkg");
checkClassName("ATest", configuration);
}
@@ -170,7 +200,7 @@ public class ConfigurationRefactoringsTest extends BaseConfigurationTestCase {
private void moveMembers(final PsiClass otherTest, final HashSet<PsiMember> members) {
new WriteCommandAction(myProject) {
@Override
protected void run(final Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
MockMoveMembersOptions options = new MockMoveMembersOptions(otherTest.getQualifiedName(), members);
new MoveMembersProcessor(myProject, null, options).run();
}
@@ -186,12 +216,13 @@ public class ConfigurationRefactoringsTest extends BaseConfigurationTestCase {
private void move(final PsiElement psiElement, String packageName) {
VirtualFile pkgFile = mySource.createPackageDir(packageName);
final PsiDirectory toDir = PsiManager.getInstance(myProject).findDirectory(pkgFile);
assertNotNull(toDir);
new WriteCommandAction(myProject, psiElement.getContainingFile()) {
@Override
protected void run(final Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
PackageWrapper wrapper = PackageWrapper.create(JavaDirectoryService.getInstance().getPackage(toDir));
new MoveClassesOrPackagesProcessor(myProject, new PsiElement[]{psiElement},
new SingleSourceRootMoveDestination(
PackageWrapper.create(JavaDirectoryService.getInstance().getPackage(toDir)), toDir),
new SingleSourceRootMoveDestination(wrapper, toDir),
false, false, null).run();
}
}.executeSilently();
@@ -200,11 +231,11 @@ public class ConfigurationRefactoringsTest extends BaseConfigurationTestCase {
private void rename(final PsiElement psiElement, final String newName) {
new WriteCommandAction(myProject, psiElement.getContainingFile()) {
@Override
protected void run(final Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
new RenameProcessor(myProject, psiElement, newName, false, false).run();
}
}.executeSilently();
}
}
@Override
protected void setUp() throws Exception {
@@ -218,18 +249,20 @@ public class ConfigurationRefactoringsTest extends BaseConfigurationTestCase {
protected void tearDown() throws Exception {
mySource.tearDown();
mySource = null;
super.tearDown(); //To change body of overriden methods use Options | File Templates.
super.tearDown();
}
@Override
protected <T extends RunConfiguration> T createConfiguration(PsiElement psiClass, MapDataContext dataContext) {
T configuration = (T)super.createConfiguration(psiClass, dataContext);
protected <T extends RunConfiguration> T createConfiguration(@NotNull PsiElement psiClass, @NotNull MapDataContext dataContext) {
T configuration = super.createConfiguration(psiClass, dataContext);
RunManagerEx.getInstanceEx(myProject).setTemporaryConfiguration(new RunnerAndConfigurationSettingsImpl(null, configuration, false));
return configuration;
}
@Override
protected JUnitConfiguration createJUnitConfiguration(final PsiElement psiElement, final Class producerClass, final MapDataContext dataContext) {
protected JUnitConfiguration createJUnitConfiguration(@NotNull PsiElement psiElement,
@NotNull Class<? extends JUnitConfigurationProducer> producerClass,
@NotNull MapDataContext dataContext) {
final JUnitConfiguration configuration = super.createJUnitConfiguration(psiElement, producerClass, dataContext);
RunManagerEx.getInstanceEx(myProject).setTemporaryConfiguration(new RunnerAndConfigurationSettingsImpl(null, configuration, false));
return configuration;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -18,8 +18,8 @@ package com.intellij.ide.fileStructure;
import com.intellij.JavaTestUtil;
import com.intellij.ide.structureView.impl.java.JavaAnonymousClassesNodeProvider;
import com.intellij.ide.structureView.impl.java.JavaInheritedMembersNodeProvider;
import com.intellij.ide.util.FileStructurePopup;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.ide.util.treeView.smartTree.TreeStructureUtil;
import com.intellij.testFramework.FileStructureTestBase;
import com.intellij.testFramework.IdeaTestCase;
@@ -66,7 +66,7 @@ public abstract class JavaFileStructureTestCase extends FileStructureTestBase {
}
private static String getAnonymousPropertyName() {
return FileStructurePopup.getPropertyName(JavaAnonymousClassesNodeProvider.JAVA_ANONYMOUS_PROPERTY_NAME);
return TreeStructureUtil.getPropertyName(JavaAnonymousClassesNodeProvider.JAVA_ANONYMOUS_PROPERTY_NAME);
}
@Override
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2014 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.projectView;
import com.intellij.ide.projectView.PresentationData;
@@ -23,8 +38,9 @@ class ClassNameConvertor implements TreeStructureProvider {
myProject = project;
}
@NotNull
@Override
public Collection<AbstractTreeNode> modify(AbstractTreeNode parent, Collection<AbstractTreeNode> children, ViewSettings settings) {
public Collection<AbstractTreeNode> modify(@NotNull AbstractTreeNode parent, @NotNull Collection<AbstractTreeNode> children, ViewSettings settings) {
ArrayList<AbstractTreeNode> result = new ArrayList<AbstractTreeNode>();
for (final AbstractTreeNode aChildren : children) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -427,8 +427,9 @@ public class ProjectViewUpdatingTest extends BaseProjectViewTestCase {
private TreeStructureProvider createWrapProvider(final NodeWrapper rootWrapper) {
return new TreeStructureProvider() {
@NotNull
@Override
public Collection<AbstractTreeNode> modify(AbstractTreeNode parent, Collection<AbstractTreeNode> children, ViewSettings settings) {
public Collection<AbstractTreeNode> modify(@NotNull AbstractTreeNode parent, @NotNull Collection<AbstractTreeNode> children, ViewSettings settings) {
if (parent instanceof NodeWrapper) {
return children;
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2014 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.projectView;
import com.intellij.ide.projectView.PresentationData;
@@ -17,8 +32,9 @@ import java.util.Collection;
import java.util.Iterator;
class SameNamesJoiner implements TreeStructureProvider {
@NotNull
@Override
public Collection<AbstractTreeNode> modify(AbstractTreeNode parent, Collection<AbstractTreeNode> children, ViewSettings settings) {
public Collection<AbstractTreeNode> modify(@NotNull AbstractTreeNode parent, @NotNull Collection<AbstractTreeNode> children, ViewSettings settings) {
if (parent instanceof JoinedNode) return children;
ArrayList<AbstractTreeNode> result = new ArrayList<AbstractTreeNode>();
@@ -236,4 +236,137 @@ class Test {
}
void "test dependent methods DFS"() {
doTest(
initial: '''
public class Q {
void E() {
ER();
}
void B() {
E();
F();
}
void A() {
B();
C();
}
void F() {
}
void C() {
G();
}
void ER() {
}
void G() {
}
}
''',
expected: '''
public class Q {
void A() {
B();
C();
}
void B() {
E();
F();
}
void E() {
ER();
}
void ER() {
}
void F() {
}
void C() {
G();
}
void G() {
}
}
''',
groups: [group(DEPENDENT_METHODS, DEPTH_FIRST)]
)
}
void "test dependent methods BFS"() {
doTest(
initial: '''
public class Q {
void E() {
ER();
}
void B() {
E();
F();
}
void A() {
B();
C();
}
void F() {
}
void C() {
G();
}
void ER() {
}
void G() {
}
}
''',
expected: '''
public class Q {
void A() {
B();
C();
}
void B() {
E();
F();
}
void C() {
G();
}
void E() {
ER();
}
void F() {
}
void G() {
}
void ER() {
}
}
''',
groups: [group(DEPENDENT_METHODS, BREADTH_FIRST)]
)
}
}
@@ -42,6 +42,15 @@ public class ChangeSignatureTest extends LightRefactoringTestCase {
doTest(null, new ParameterInfoImpl[]{new ParameterInfoImpl(1), new ParameterInfoImpl(0)}, false);
}
public void testWarnAboutContract() throws Exception {
try {
doTest(null, new ParameterInfoImpl[]{new ParameterInfoImpl(1), new ParameterInfoImpl(0)}, false);
fail("Conflict expected");
}
catch (BaseRefactoringProcessor.ConflictsInTestsException ignored) {
}
}
public void testGenericTypes() throws Exception {
doTest(null, null, "T", new GenParams() {
@Override
@@ -13,11 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* User: anna
* Date: 20-Aug-2008
*/
package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
@@ -28,6 +23,10 @@ import com.intellij.refactoring.inlineSuperClass.InlineSuperClassRefactoringProc
import com.intellij.refactoring.util.DocCommentPolicy;
import org.jetbrains.annotations.NotNull;
/**
* @author anna
* @since 20-Aug-2008
*/
public class InlineSuperClassTest extends MultiFileTestCase {
@NotNull
@Override
@@ -40,33 +39,55 @@ public class InlineSuperClassTest extends MultiFileTestCase {
return JavaTestUtil.getJavaTestDataPath();
}
private void doTest() throws Exception {
doTest(false);
public void testInlineOneClass() { doTest(false, true); }
public void testInlineOneClassWithConflicts() { doTest(true, true); }
public void testAbstractOverrides() { doTest(); }
public void testSimple() { doTest(); }
public void testSimpleGenerics() { doTest(); }
public void testConflictGenerics() { doTest(true, false); }
public void testImports() { doTest(); }
public void testGenerics() { doTest(); }
public void testNewExpr() { doTest(); }
public void testConflictConstructors() { doTest(true, false); }
public void testConflictMultipleConstructors() { doTest(true, false); }
public void testMultipleConstructors() { doTest(); }
public void testImplicitChildConstructor() { doTest(); }
public void testStaticMembers() { doTest(); }
public void testSuperReference() { doTest(); }
public void testInnerClassReference() { doTest(); }
public void testStaticImport() { doTest(); }
public void testNewArrayInitializerExpr() { doTest(); }
public void testNewArrayDimensionsExpr() { doTest(); }
public void testNewArrayComplexDimensionsExpr() { doTest(); }
public void testSuperConstructorWithReturnInside() { doTest(true, false); }
public void testSuperConstructorWithFieldInitialization() { doTest(); }
public void testSuperConstructorWithParam() { doTest(); }
public void testChildConstructorImplicitlyCallsSuper() { doTest(); }
public void testNoChildConstructorCallsSuperDefault() { doTest(); }
public void testReplaceGenericsInside() { doTest(); }
public void testMultipleSubclasses() { doTestMultipleSubclasses(); }
public void testMultipleSubstitutions() { doTestMultipleSubclasses(); }
public void testMultipleSubclassesInheritsOneBaseBase() { doTestMultipleSubclasses(); }
public void testInlineSuperclassExtendsList() { doTest(); }
public void testInterfaceHierarchyWithSubstitution() { doTest(); }
private void doTest() {
doTest(false, false);
}
private void doTest(final boolean fail) throws Exception {
doTest(fail, false);
}
private void doTest(final boolean fail, final boolean inlineOne) throws Exception {
private void doTest(boolean fail, final boolean inlineOne) {
try {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.allScope(myProject));
if (aClass == null) aClass = myJavaFacade.findClass("p.Test", GlobalSearchScope.allScope(myProject));
GlobalSearchScope scope = GlobalSearchScope.allScope(myProject);
PsiClass aClass = myJavaFacade.findClass("Test", scope);
if (aClass == null) aClass = myJavaFacade.findClass("p.Test", scope);
assertNotNull("Class Test not found", aClass);
PsiClass superClass = myJavaFacade.findClass("Super", GlobalSearchScope.allScope(myProject));
if (superClass == null) superClass = myJavaFacade.findClass("p1.Super", GlobalSearchScope.allScope(myProject));
PsiClass superClass = myJavaFacade.findClass("Super", scope);
if (superClass == null) superClass = myJavaFacade.findClass("p1.Super", scope);
assertNotNull("Class Super not found", superClass);
new InlineSuperClassRefactoringProcessor(getProject(), inlineOne ? aClass : null, superClass, DocCommentPolicy.ASIS, aClass).run();
//LocalFileSystem.getInstance().refresh(false);
//FileDocumentManager.getInstance().saveAllDocuments();
new InlineSuperClassRefactoringProcessor(myProject, inlineOne ? aClass : null, superClass, DocCommentPolicy.ASIS, aClass).run();
}
});
}
@@ -83,140 +104,17 @@ public class InlineSuperClassTest extends MultiFileTestCase {
}
}
public void testInlineOneClass() throws Exception {
doTest(false, true);
}
public void testInlineOneClassWithConflicts() throws Exception {
doTest(true, true);
}
public void testAbstractOverrides() throws Exception {
doTest();
}
public void testSimple() throws Exception {
doTest();
}
public void testSimpleGenerics() throws Exception {
doTest();
}
public void testConflictGenerics() throws Exception {
doTest(true);
}
public void testImports() throws Exception {
doTest();
}
public void testGenerics() throws Exception {
doTest();
}
public void testNewexpr() throws Exception {
doTest();
}
public void testConflictConstructors() throws Exception {
doTest(true);
}
public void testConflictMultipleConstructors() throws Exception {
doTest(true);
}
public void testMultipleConstructors() throws Exception {
doTest();
}
public void testImplicitChildConstructor() throws Exception {
doTest();
}
public void testStaticMembers() throws Exception {
doTest();
}
public void testSuperReference() throws Exception {
doTest();
}
public void testInnerclassReference() throws Exception {
doTest();
}
public void testStaticImport() throws Exception {
doTest();
}
public void testNewArrayInitializerExpr() throws Exception {
doTest();
}
public void testNewArrayDimensionsExpr() throws Exception {
doTest();
}
public void testNewArrayComplexDimensionsExpr() throws Exception {
doTest();
}
public void testSuperConstructorWithReturnInside() throws Exception {
doTest(true);
}
public void testSuperConstructorWithFieldInitialization() throws Exception {
doTest();
}
public void testSuperConstructorWithParam() throws Exception {
doTest();
}
public void testChildConstructorImplicitlyCallsSuper() throws Exception {
doTest();
}
public void testNoChildConstructorCallsSuperDefault() throws Exception {
doTest();
}
public void testReplaceGenericsInside() throws Exception {
doTest();
}
public void testMultipleSubclasses() throws Exception {
doTestMultipleSubclasses();
}
public void testMultipleSubstitutions() throws Exception {
doTestMultipleSubclasses();
}
public void testMultipleSubclassesInheritsOneBaseBase() throws Exception {
doTestMultipleSubclasses();
}
public void testInlineSuperclassExtendsList() throws Exception {
doTest();
}
public void testInterfaceHierarchyWithSubstitution() throws Exception {
doTest();
}
private void doTestMultipleSubclasses() throws Exception {
private void doTestMultipleSubclasses() {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
PsiClass superClass = myJavaFacade.findClass("Super", GlobalSearchScope.allScope(myProject));
if (superClass == null) superClass = myJavaFacade.findClass("p1.Super", GlobalSearchScope.allScope(myProject));
GlobalSearchScope scope = GlobalSearchScope.allScope(myProject);
PsiClass superClass = myJavaFacade.findClass("Super", scope);
if (superClass == null) superClass = myJavaFacade.findClass("p1.Super", scope);
assertNotNull("Class Super not found", superClass);
new InlineSuperClassRefactoringProcessor(getProject(), null, superClass, DocCommentPolicy.ASIS,
myJavaFacade.findClass("Test", GlobalSearchScope.allScope(myProject)),
myJavaFacade.findClass("Test1", GlobalSearchScope.allScope(myProject))).run();
PsiClass target1 = myJavaFacade.findClass("Test", scope);
PsiClass target2 = myJavaFacade.findClass("Test1", scope);
new InlineSuperClassRefactoringProcessor(myProject, null, superClass, DocCommentPolicy.ASIS, target1, target2).run();
}
});
}
@@ -463,4 +463,9 @@ public class IntroduceParameterTest extends LightRefactoringTestCase {
IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_INACCESSIBLE,
declareFinal, false, null, parametersToRemove).run();
}
@Override
protected LanguageLevel getLanguageLevel() {
return LanguageLevel.JDK_1_7;
}
}
@@ -1,13 +1,27 @@
/*
* Copyright 2000-2014 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.refactoring;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* @author dsl
*/
public class IntroduceVariableSuite extends TestCase {
public class IntroduceVariableSuite {
public static Test suite() {
final TestSuite suite = new TestSuite();
suite.addTestSuite(IntroduceVariableTest.class);
@@ -428,6 +428,7 @@ public class IntroduceVariableTest extends LightCodeInsightTestCase {
}
public void testLambdaExpr() throws Exception {
doTest(new MockIntroduceVariableHandler("c", false, false, false, "SAM<java.lang.Integer>"));
}
@@ -436,7 +437,7 @@ public class IntroduceVariableTest extends LightCodeInsightTestCase {
}
public void testLambdaExprNotAccepted() throws Exception {
doTest(new MockIntroduceVariableHandler("c", false, false, false, "SAM<java.lang.String>"));
doTest(new MockIntroduceVariableHandler("c", false, false, false, "SAM<X>"));
}
public void testOneLineLambdaVoidCompatible() throws Exception {
@@ -16,11 +16,12 @@
package com.intellij.codeInsight.daemon.quickFix;
import com.intellij.testFramework.FileBasedTestCaseHelperEx;
import com.intellij.testFramework.Parameterized;
import org.jetbrains.annotations.Nullable;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(com.intellij.testFramework.Parameterized.class)
@RunWith(Parameterized.class)
public abstract class LightQuickFixParameterizedTestCase extends LightQuickFixTestCase implements FileBasedTestCaseHelperEx {
@Override
public String getRelativeBasePath() {
@@ -34,32 +35,20 @@ public abstract class LightQuickFixParameterizedTestCase extends LightQuickFixTe
return fileName.substring(BEFORE_PREFIX.length());
}
@SuppressWarnings("deprecation")
@Override
protected void doAllTests() {
super.doAllTests();
}
@SuppressWarnings("JUnit4AnnotatedMethodInJUnit3TestCase")
@Test
public void runSingle() throws Throwable {
final Throwable[] throwables = new Throwable[1];
Runnable runnable = new Runnable() {
runSingleTest(new Runnable() {
@Override
public void run() {
try {
doSingleTest(myFileSuffix, myTestDataPath);
}
catch (Throwable e) {
throwables[0] = e;
}
doSingleTest(myFileSuffix, myTestDataPath);
}
};
invokeTestRunnable(runnable);
if (throwables[0] != null) {
throw throwables[0];
}
});
}
}
@@ -114,7 +114,9 @@ public abstract class LightQuickFixTestCase extends LightDaemonAnalyzerTestCase
}
@NotNull
public static Pair<String, Boolean> parseActionHint(@NotNull PsiFile file, @NotNull String contents, @NotNull @NonNls @RegExp String actionPattern) {
public static Pair<String, Boolean> parseActionHint(@NotNull PsiFile file,
@NotNull String contents,
@NotNull @NonNls @RegExp String actionPattern) {
PsiFile hostFile = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file);
final Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(hostFile.getLanguage());
@@ -198,6 +200,14 @@ public abstract class LightQuickFixTestCase extends LightDaemonAnalyzerTestCase
return null;
}
/**
* @deprecated use {@link com.intellij.codeInsight.daemon.quickFix.LightQuickFixParameterizedTestCase}
* to get separate tests for all data files in testData directory.
*/
protected void doAllTests() {
doAllTests(createWrapper());
}
public static void doAllTests(QuickFixTestCase testCase) {
assertNotNull("getBasePath() should not return null!", testCase.getBasePath());
@@ -210,7 +220,7 @@ public abstract class LightQuickFixTestCase extends LightDaemonAnalyzerTestCase
}
});
if (files == null) {
if (files == null || files.length == 0) {
fail("Test files not found in " + testDirPath);
}
@@ -218,20 +228,12 @@ public abstract class LightQuickFixTestCase extends LightDaemonAnalyzerTestCase
final String testName = file.getName().substring(BEFORE_PREFIX.length());
doTestFor(testName, testCase);
}
assertTrue("Test files not found in "+testDirPath,files.length != 0);
}
protected void doSingleTest(String fileSuffix) {
doTestFor(fileSuffix, createWrapper());
}
/**
* @deprecated use com.intellij.codeInsight.daemon.quickFix.LightQuickFixParameterizedTestCase to get separate tests for all data files in
* testData directory
*/
protected void doAllTests() {
doAllTests(createWrapper());
}
protected void doSingleTest(String fileSuffix, String testDataPath) {
doTestFor(fileSuffix, createWrapper(testDataPath));
}
@@ -35,36 +35,44 @@ import java.io.File;
public abstract class MultiFileTestCase extends CodeInsightTestCase {
protected boolean myDoCompare = true;
protected void doTest(final PerformAction performAction) throws Exception {
protected void doTest(final PerformAction performAction) {
doTest(performAction, getTestName(true));
}
protected void doTest(final PerformAction performAction, final boolean lowercaseFirstLetter) throws Exception {
protected void doTest(final PerformAction performAction, final boolean lowercaseFirstLetter) {
doTest(performAction, getTestName(lowercaseFirstLetter));
}
protected void doTest(final PerformAction performAction, final String testName) throws Exception {
String path = getTestDataPath() + getTestRoot() + testName;
protected void doTest(final PerformAction performAction, final String testName) {
try {
String path = getTestDataPath() + getTestRoot() + testName;
String pathBefore = path + "/before";
final VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, pathBefore, myFilesToDelete, false);
prepareProject(rootDir);
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
String pathBefore = path + "/before";
VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, pathBefore, myFilesToDelete, false);
prepareProject(rootDir);
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
String pathAfter = path + "/after";
final VirtualFile rootAfter = LocalFileSystem.getInstance().findFileByPath(pathAfter.replace(File.separatorChar, '/'));
String pathAfter = path + "/after";
final VirtualFile rootAfter = LocalFileSystem.getInstance().findFileByPath(pathAfter.replace(File.separatorChar, '/'));
performAction.performAction(rootDir, rootAfter);
WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() {
public void run() {
myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
performAction.performAction(rootDir, rootAfter);
WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() {
public void run() {
myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
}
});
FileDocumentManager.getInstance().saveAllDocuments();
if (myDoCompare) {
PlatformTestUtil.assertDirectoriesEqual(rootAfter, rootDir);
}
});
FileDocumentManager.getInstance().saveAllDocuments();
if (myDoCompare) {
PlatformTestUtil.assertDirectoriesEqual(rootAfter, rootDir);
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -25,6 +25,7 @@ package com.intellij.codeInspection;
* Instead, use the {@link ProblemDescriptor#getPsiElement()}
* in {@link QuickFix#applyFix(com.intellij.openapi.project.Project, CommonProblemDescriptor)}
* to retrieve the PSI context the fix will work on.
* See also {@link LocalQuickFixOnPsiElement} which uses {@link com.intellij.psi.SmartPsiElementPointer} instead of storing PSI elements.
*
* @author max
* @see LocalQuickFixBase
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -18,6 +18,7 @@ package com.intellij.openapi.editor.colors;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.ui.Gray;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.util.HashMap;
@@ -31,7 +32,7 @@ public final class ColorKey implements Comparable<ColorKey> {
private Color myDefaultColor = NULL_COLOR;
private static final Map<String, ColorKey> ourRegistry = new HashMap<String, ColorKey>();
private ColorKey(String externalName) {
private ColorKey(@NotNull String externalName) {
myExternalName = externalName;
if (ourRegistry.containsKey(myExternalName)) {
LOG.error("Key " + myExternalName + " already registered.");
@@ -41,20 +42,23 @@ public final class ColorKey implements Comparable<ColorKey> {
}
}
public static ColorKey find(String externalName) {
@NotNull
public static ColorKey find(@NotNull String externalName) {
ColorKey key = ourRegistry.get(externalName);
return key != null ? key : new ColorKey(externalName);
return key == null ? new ColorKey(externalName) : key;
}
public String toString() {
return myExternalName;
}
@NotNull
public String getExternalName() {
return myExternalName;
}
public int compareTo(ColorKey key) {
@Override
public int compareTo(@NotNull ColorKey key) {
return myExternalName.compareTo(key.myExternalName);
}
@@ -72,15 +76,14 @@ public final class ColorKey implements Comparable<ColorKey> {
return myDefaultColor;
}
public static ColorKey createColorKey(@NonNls String externalName) {
@NotNull
public static ColorKey createColorKey(@NonNls @NotNull String externalName) {
return find(externalName);
}
public static ColorKey createColorKey(@NonNls String externalName, Color defaultColor) {
ColorKey key = ourRegistry.get(externalName);
if (key == null) {
key = find(externalName);
}
@NotNull
public static ColorKey createColorKey(@NonNls @NotNull String externalName, Color defaultColor) {
ColorKey key = createColorKey(externalName);
if (key.getDefaultColor() == null) {
key.myDefaultColor = defaultColor;
@@ -33,11 +33,11 @@ public abstract class CopyPasteManager {
return ServiceManager.getService(CopyPasteManager.class);
}
public abstract void addContentChangedListener(ContentChangedListener listener);
public abstract void addContentChangedListener(@NotNull ContentChangedListener listener);
public abstract void addContentChangedListener(ContentChangedListener listener, Disposable parentDisposable);
public abstract void addContentChangedListener(@NotNull ContentChangedListener listener, @NotNull Disposable parentDisposable);
public abstract void removeContentChangedListener(ContentChangedListener listener);
public abstract void removeContentChangedListener(@NotNull ContentChangedListener listener);
/** @deprecated use {@link #getContents(DataFlavor)} or {@link #areDataFlavorsAvailable(DataFlavor...)} (to remove in IDEA 14) */
@SuppressWarnings("unused")
@@ -53,6 +53,7 @@ public abstract class CopyPasteManager {
@Nullable
public abstract <T> T getContents(@NotNull DataFlavor flavor);
@NotNull
public abstract Transferable[] getAllContents();
public abstract void setContents(@NotNull Transferable content);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -26,6 +26,7 @@ import java.util.concurrent.atomic.AtomicInteger;
public interface BusyObject {
@NotNull
ActionCallback getReady(@NotNull Object requestor);
abstract class Impl implements BusyObject {
@@ -66,9 +67,7 @@ public interface BusyObject {
if (isReady()) {
return new ActionCallback.Done();
}
else {
return addReadyCallback(requestor);
}
return addReadyCallback(requestor);
}
@NotNull
@@ -84,6 +83,7 @@ public interface BusyObject {
}
}
@NotNull
private ActionCallback[] getReadyCallbacks() {
synchronized (myReadyCallbacks) {
ActionCallback[] result = myReadyCallbacks.values().toArray(new ActionCallback[myReadyCallbacks.size()]);
@@ -92,6 +92,7 @@ public interface BusyObject {
}
}
@NotNull
private Pair<ActionCallback, List<ActionCallback>> getReadyCallbacks(Object readyRequestor) {
synchronized (myReadyCallbacks) {
ActionCallback done = myReadyCallbacks.get(readyRequestor);

Some files were not shown because too many files have changed in this diff Show More