Merge remote-tracking branch 'origin/master'

This commit is contained in:
Vladimir.Orlov
2015-11-09 16:58:57 +03:00
318 changed files with 3721 additions and 2338 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
# IntelliJ IDEA Community Edition
### Building and Running from the IDE
To develop IntelliJ IDEA, you can use either IntelliJ IDEA Community Edition or IntelliJ IDEA Ultimate not older than 14.1.5. To build and run the code:
To develop IntelliJ IDEA, you can use either IntelliJ IDEA Community Edition or IntelliJ IDEA Ultimate not older than 15.0. To build and run the code:
* Run **getPlugins.sh** / **getPlugins.bat** from the project root directory to check out additional modules.
* If this git repository is not on 'master' branch you need to checkout the same branches/tags in android and android/tools-base git repositories.
* Open the project.
-1
View File
@@ -796,7 +796,6 @@ private Map readIdeaProperties(Map args) {
ideaPropertiesFile.close();
def defaultProperties = ["CVS_PASSFILE": "~/.cvspass",
"JVMVersion": "1.6+",
"com.apple.mrj.application.live-resize": "false",
"idea.paths.selector": args.system_selector,
"idea.executable": args.executable,
@@ -16,6 +16,7 @@
package com.intellij.debugger.engine.evaluation;
import com.intellij.debugger.ui.DebuggerEditorImpl;
import com.intellij.lang.LanguageUtil;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.StdFileTypes;
@@ -26,7 +27,6 @@ import com.intellij.psi.*;
import com.intellij.xdebugger.XExpression;
import com.intellij.xdebugger.evaluation.EvaluationMode;
import com.intellij.xdebugger.impl.breakpoints.XExpressionImpl;
import com.intellij.xdebugger.impl.ui.XDebuggerEditorBase;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -136,7 +136,7 @@ public final class TextWithImportsImpl implements TextWithImports{
public static XExpression toXExpression(@Nullable TextWithImports text) {
if (text != null && !text.getText().isEmpty()) {
return new XExpressionImpl(text.getText(),
XDebuggerEditorBase.getFileTypeLanguage(text.getFileType()),
LanguageUtil.getFileTypeLanguage(text.getFileType()),
StringUtil.nullize(text.getImports()),
getMode(text.getKind()));
}
@@ -169,7 +169,7 @@ public final class TextWithImportsImpl implements TextWithImports{
return new TextWithImportsImpl(getKind(expression.getMode()),
expression.getExpression(),
StringUtil.notNullize(expression.getCustomInfo()),
expression.getLanguage() != null ? expression.getLanguage().getAssociatedFileType() : null);
LanguageUtil.getLanguageFileType(expression.getLanguage()));
}
}
}
@@ -494,7 +494,7 @@ public class LocalVariablesUtil {
}
private static int getTypeSlotSize(PsiType varType) {
if (varType == PsiType.DOUBLE || varType == PsiType.LONG) {
if (PsiType.DOUBLE.equals(varType) || PsiType.LONG.equals(varType)) {
return 2;
}
return 1;
@@ -18,14 +18,11 @@ package com.intellij.debugger.ui;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.ide.highlighter.JavaClassFileType;
import com.intellij.ide.util.ModuleRendererFactory;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
@@ -33,6 +30,7 @@ import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.ui.EditorNotificationPanel;
import com.intellij.ui.EditorNotifications;
import com.intellij.ui.components.JBList;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.xdebugger.XDebugSession;
@@ -41,6 +39,7 @@ import com.intellij.xdebugger.XSourcePosition;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
@@ -115,7 +114,7 @@ public class AlternativeSourceNotificationProvider extends EditorNotifications.P
new Function<PsiClass, ComboBoxClassElement>() {
@Override
public ComboBoxClassElement fun(PsiClass psiClass) {
return new ComboBoxClassElement(psiClass);
return new ComboBoxClassElement((PsiClass)psiClass.getNavigationElement());
}
});
@@ -132,27 +131,15 @@ public class AlternativeSourceNotificationProvider extends EditorNotifications.P
myClass = aClass;
}
private static JList ourDummyList = new JBList(); // to use ModuleRendererFactory
@Override
public String toString() {
if (myText == null) {
Module module = ModuleUtilCore.findModuleForPsiElement(myClass);
if (module != null) {
myText = module.getName();
}
else {
VirtualFile virtualFile = myClass.getContainingFile().getVirtualFile();
final ProjectFileIndex index = ProjectRootManager.getInstance(myClass.getProject()).getFileIndex();
VirtualFile root = index.getSourceRootForFile(virtualFile);
if (root == null) {
root = index.getClassRootForFile(virtualFile);
}
if (root != null) {
myText = root.getName();
}
else {
myText = virtualFile.getPath();
}
}
ModuleRendererFactory factory = ModuleRendererFactory.findInstance(myClass);
DefaultListCellRenderer moduleRenderer = factory.getModuleRenderer();
moduleRenderer.getListCellRendererComponent(ourDummyList, myClass, 1, false, false);
myText = moduleRenderer.getText();
}
return myText;
}
@@ -174,7 +161,6 @@ public class AlternativeSourceNotificationProvider extends EditorNotifications.P
public void actionPerformed(ActionEvent e) {
FileEditorManager.getInstance(project).closeFile(file);
PsiClass item = ((ComboBoxClassElement)switcher.getSelectedItem()).myClass;
item = (PsiClass)item.getNavigationElement(); // go through compiled
DebuggerUtilsEx.setAlternativeSource(file, item.getContainingFile().getVirtualFile());
item.navigate(true);
XDebugSession session = XDebuggerManager.getInstance(project).getCurrentSession();
@@ -24,6 +24,7 @@ import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.ListPopupStep;
import com.intellij.ui.popup.list.ListPopupImpl;
import com.intellij.util.PsiNavigateUtil;
import com.intellij.util.Time;
import javax.swing.*;
import java.awt.event.ActionEvent;
@@ -35,7 +36,7 @@ public class ShowRecentTests extends AnAction {
private static final int TEST_LIMIT = Integer.MAX_VALUE;
private static Date getSinceDate() {
return new Date(0);
return new Date(System.currentTimeMillis() - Time.DAY);
}
@Override
@@ -109,7 +109,7 @@ public class SimplifyBooleanExpressionFix extends LocalQuickFixOnPsiElement {
public static void simplifyIfStatement(final PsiExpression expression) throws IncorrectOperationException {
PsiElement parent = expression.getParent();
if (!(parent instanceof PsiIfStatement) || ((PsiIfStatement)parent).getCondition() != expression) return;
if (!(expression instanceof PsiLiteralExpression) || expression.getType() != PsiType.BOOLEAN) return;
if (!(expression instanceof PsiLiteralExpression) || !PsiType.BOOLEAN.equals(expression.getType())) return;
boolean condition = Boolean.parseBoolean(expression.getText());
PsiIfStatement ifStatement = (PsiIfStatement)parent;
if (condition) {
@@ -210,7 +210,7 @@ public class SimplifyBooleanExpressionFix extends LocalQuickFixOnPsiElement {
}
public static boolean canBeSimplified(@NotNull PsiExpression expression) {
if (!(expression instanceof PsiConditionalExpression) && expression.getType() != PsiType.BOOLEAN) return false;
if (!(expression instanceof PsiConditionalExpression) && !PsiType.BOOLEAN.equals(expression.getType())) return false;
final ExpressionVisitor expressionVisitor = new ExpressionVisitor(expression.getManager(), false);
final Ref<Boolean> canBeSimplified = new Ref<Boolean>(Boolean.FALSE);
@@ -1218,7 +1218,7 @@ public class ControlFlowAnalyzer extends JavaElementVisitor {
}
private void generateBoxingUnboxingInstructionFor(@NotNull PsiExpression expression, PsiType expectedType) {
if (expectedType == PsiType.VOID) return;
if (PsiType.VOID.equals(expectedType)) return;
PsiType exprType = expression.getType();
@@ -572,7 +572,7 @@ public class DataFlowInspectionBase extends BaseJavaBatchLocalInspectionTool {
PsiType returnType = method.getReturnType();
// no warnings in void lambdas, where the expression is not returned anyway
if (block instanceof PsiExpression && block.getParent() instanceof PsiLambdaExpression && returnType == PsiType.VOID) return;
if (block instanceof PsiExpression && block.getParent() instanceof PsiLambdaExpression && PsiType.VOID.equals(returnType)) return;
// no warnings for Void methods, where only null can be possibly returned
if (returnType == null || returnType.equalsToText(CommonClassNames.JAVA_LANG_VOID)) return;
@@ -36,7 +36,7 @@ public class PurityInference {
public static boolean inferPurity(@NotNull final PsiMethod method) {
if (!InferenceFromSourceUtil.shouldInferFromSource(method) ||
method.getReturnType() == PsiType.VOID ||
PsiType.VOID.equals(method.getReturnType()) ||
method.getBody() == null ||
method.isConstructor() ||
PropertyUtil.isSimpleGetter(method)) {
@@ -517,18 +517,16 @@ public class StandardInstructionVisitor extends InstructionVisitor {
PsiType varType = var.getVariableType();
if (!(varType instanceof PsiPrimitiveType)) return null;
if (varType == PsiType.FLOAT || varType == PsiType.DOUBLE) return null;
if (PsiType.FLOAT.equals(varType) || PsiType.DOUBLE.equals(varType)) return null;
double minValue = varType == PsiType.BYTE ? Byte.MIN_VALUE :
varType == PsiType.SHORT ? Short.MIN_VALUE :
varType == PsiType.INT ? Integer.MIN_VALUE :
varType == PsiType.CHAR ? Character.MIN_VALUE :
Long.MIN_VALUE;
double maxValue = varType == PsiType.BYTE ? Byte.MAX_VALUE :
varType == PsiType.SHORT ? Short.MAX_VALUE :
varType == PsiType.INT ? Integer.MAX_VALUE :
varType == PsiType.CHAR ? Character.MAX_VALUE :
Long.MAX_VALUE;
double minValue = PsiType.BYTE.equals(varType) ? Byte.MIN_VALUE : PsiType.SHORT.equals(varType)
? Short.MIN_VALUE : PsiType.INT.equals(varType)
? Integer.MIN_VALUE : PsiType.CHAR.equals(varType) ? Character.MIN_VALUE :
Long.MIN_VALUE;
double maxValue = PsiType.BYTE.equals(varType) ? Byte.MAX_VALUE : PsiType.SHORT.equals(varType)
? Short.MAX_VALUE : PsiType.INT.equals(varType)
? Integer.MAX_VALUE : PsiType.CHAR.equals(varType) ? Character.MAX_VALUE :
Long.MAX_VALUE;
return checkComparisonWithKnownRange(instruction, runner, memState, opSign, comparedWith, minValue, maxValue);
}
@@ -105,12 +105,12 @@ public class NullableStuffInspectionBase extends BaseJavaBatchLocalInspectionToo
checkAccessors(field, annotated, project, manager, anno, annoToRemove, holder);
if (REQUIRE_NOTNULL_FIELDS_INITIALIZED) {
checkNotNullFieldsInitialized(field, annotated, manager, holder);
}
checkConstructorParameters(field, annotated, manager, anno, annoToRemove, holder);
}
if (REQUIRE_NOTNULL_FIELDS_INITIALIZED && !annotated.isDeclaredNullable) {
checkNotNullFieldsInitialized(field, manager, holder);
}
}
@Override
@@ -259,17 +259,14 @@ public class NullableStuffInspectionBase extends BaseJavaBatchLocalInspectionToo
LOG.assertTrue(parameter.isPhysical(), setter.getText());
}
private static void checkNotNullFieldsInitialized(PsiField field,
Annotated annotated,
NullableNotNullManager manager, @NotNull ProblemsHolder holder) {
if (annotated.isDeclaredNotNull && !HighlightControlFlowUtil.isFieldInitializedAfterObjectConstruction(field)) {
final PsiAnnotation annotation = AnnotationUtil.findAnnotation(field, manager.getNotNulls());
if (annotation != null) {
holder.registerProblem(annotation.isPhysical() ? annotation : field.getNameIdentifier(),
"Not-null fields must be initialized",
ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
}
}
private static void checkNotNullFieldsInitialized(PsiField field, NullableNotNullManager manager, @NotNull ProblemsHolder holder) {
PsiAnnotation annotation = manager.getNotNullAnnotation(field, false);
if (annotation == null || HighlightControlFlowUtil.isFieldInitializedAfterObjectConstruction(field)) return;
boolean byDefault = manager.isContainerAnnotation(annotation);
PsiJavaCodeReferenceElement name = annotation.getNameReferenceElement();
holder.registerProblem(annotation.isPhysical() && !byDefault ? annotation : field.getNameIdentifier(),
(byDefault && name != null ? "@" + name.getReferenceName() : "Not-null") + " fields must be initialized");
}
private void checkConstructorParameters(PsiField field,
@@ -251,7 +251,7 @@ public class RefJavaUtilImpl extends RefJavaUtil{
if (refExpression instanceof PsiMethodReferenceExpression) {
PsiType returnType = psiMethod.getReturnType();
if (!psiMethod.isConstructor() && returnType != PsiType.VOID) {
if (!psiMethod.isConstructor() && !PsiType.VOID.equals(returnType)) {
refMethod.setReturnValueUsed(true);
addTypeReference(psiFrom, returnType, refFrom.getRefManager());
}
@@ -263,7 +263,7 @@ public class RefJavaUtilImpl extends RefJavaUtil{
);
if (call != null) {
PsiType returnType = psiMethod.getReturnType();
if (!psiMethod.isConstructor() && returnType != PsiType.VOID) {
if (!psiMethod.isConstructor() && !PsiType.VOID.equals(returnType)) {
if (!(call.getParent() instanceof PsiExpressionStatement)) {
refMethod.setReturnValueUsed(true);
}
@@ -27,11 +27,9 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.util.Pass;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.util.*;
import com.intellij.xml.util.XmlUtil;
import org.intellij.lang.annotations.Pattern;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
@@ -407,7 +405,7 @@ public class UncheckedWarningLocalInspectionBase extends BaseJavaBatchLocalInspe
if (psiElement instanceof PsiMethod) {
final PsiMethod method = (PsiMethod)psiElement;
final PsiType returnType = method.getReturnType();
if (returnType != null && returnType != PsiType.VOID) {
if (returnType != null && !PsiType.VOID.equals(returnType)) {
final PsiExpression returnValue = statement.getReturnValue();
if (returnValue != null) {
final PsiType valueType = returnValue.getType();
@@ -221,7 +221,7 @@ public class ParametersFolder {
if (expression == null) break;
final PsiType expressionType = ((PsiExpression)expression).getType();
if (expressionType != null && expressionType != PsiType.VOID && !(expression.getParent() instanceof PsiExpressionStatement)) {
if (expressionType != null && !PsiType.VOID.equals(expressionType) && !(expression.getParent() instanceof PsiExpressionStatement)) {
if (dependsOnLocals(expression, inputVariables)) {
break;
}
@@ -123,7 +123,7 @@ public class FunctionalInterfaceSuggester {
return null;
}
if (returnType == PsiType.VOID && interfaceMethodReturnType != PsiType.VOID) {
if (PsiType.VOID.equals(returnType) && !PsiType.VOID.equals(interfaceMethodReturnType)) {
return null;
}
@@ -30,7 +30,7 @@ public class JavaRegExpModifierProvider implements RegExpModifierProvider {
@Override
public int getFlags(PsiElement elementInHost, PsiFile regexp) {
final PsiExpressionList list = PsiTreeUtil.getParentOfType(elementInHost, PsiExpressionList.class);
if (list != null && list.getExpressions().length == 2 && list.getExpressionTypes()[1] == PsiType.INT) {
if (list != null && list.getExpressions().length == 2 && PsiType.INT.equals(list.getExpressionTypes()[1])) {
final Object result = JavaConstantExpressionEvaluator.computeConstantExpression(list.getExpressions()[1], false);
if (result instanceof Integer) {
//noinspection MagicConstant
@@ -757,7 +757,7 @@ public class JavaCompletionUtil {
TailType toInsert = tailType;
LookupItem<?> lookupItem = item.as(LookupItem.CLASS_CONDITION_KEY);
if (lookupItem == null || lookupItem.getAttribute(LookupItem.TAIL_TYPE_ATTR) != TailType.UNKNOWN) {
if (!hasTail && item.getObject() instanceof PsiMethod && ((PsiMethod)item.getObject()).getReturnType() == PsiType.VOID) {
if (!hasTail && item.getObject() instanceof PsiMethod && PsiType.VOID.equals(((PsiMethod)item.getObject()).getReturnType())) {
PsiDocumentManager.getInstance(context.getProject()).commitAllDocuments();
if (psiElement().beforeLeaf(psiElement().withText(".")).accepts(context.getFile().findElementAt(context.getTailOffset() - 1))) {
return false;
@@ -221,19 +221,26 @@ public class JavaInheritorsGetter extends CompletionProvider<CompletionParameter
public static void processInheritors(final CompletionParameters parameters,
final Collection<PsiClassType> expectedClassTypes,
final PrefixMatcher matcher, final Consumer<PsiType> consumer) {
processInheritors(parameters.getOriginalFile(), parameters.getPosition(), expectedClassTypes, matcher, consumer);
}
public static void processInheritors(final PsiFile file,
final PsiElement context,
final Collection<PsiClassType> expectedClassTypes,
final PrefixMatcher matcher, final Consumer<PsiType> consumer) {
//quick
if (!processMostProbableInheritors(parameters, expectedClassTypes, consumer)) return;
if (!processMostProbableInheritors(file, context, expectedClassTypes, consumer)) return;
//long
for (final PsiClassType type : expectedClassTypes) {
CodeInsightUtil.processSubTypes(type, parameters.getPosition(), false, matcher, consumer);
CodeInsightUtil.processSubTypes(type, context, false, matcher, consumer);
}
}
private static boolean processMostProbableInheritors(CompletionParameters parameters,
private static boolean processMostProbableInheritors(PsiFile contextFile,
PsiElement context,
Collection<PsiClassType> expectedClassTypes,
Consumer<PsiType> consumer) {
PsiFile file = parameters.getOriginalFile();
for (final PsiClassType type : expectedClassTypes) {
consumer.consume(type);
@@ -243,15 +250,15 @@ public class JavaInheritorsGetter extends CompletionProvider<CompletionParameter
final PsiSubstitutor baseSubstitutor = baseResult.getSubstitutor();
final Processor<PsiClass> processor = CodeInsightUtil.createInheritorsProcessor(parameters.getPosition(), type, 0, false,
final Processor<PsiClass> processor = CodeInsightUtil.createInheritorsProcessor(context, type, 0, false,
consumer, baseClass, baseSubstitutor);
final StatisticsInfo[] stats = StatisticsManager.getInstance().getAllValues(JavaStatisticsManager.getAfterNewKey(type));
for (final StatisticsInfo statisticsInfo : stats) {
final String value = statisticsInfo.getValue();
if (value.startsWith(JavaStatisticsManager.CLASS_PREFIX)) {
final String qname = value.substring(JavaStatisticsManager.CLASS_PREFIX.length());
final PsiClass psiClass = JavaPsiFacade.getInstance(file.getProject()).findClass(qname, file.getResolveScope());
if (psiClass != null && !PsiTreeUtil.isAncestor(file, psiClass, true) && !processor.process(psiClass)) break;
final PsiClass psiClass = JavaPsiFacade.getInstance(contextFile.getProject()).findClass(qname, contextFile.getResolveScope());
if (psiClass != null && !PsiTreeUtil.isAncestor(contextFile, psiClass, true) && !processor.process(psiClass)) break;
}
}
}
@@ -491,7 +491,7 @@ public class JavaKeywordCompletion {
private static boolean mayExpectBoolean(CompletionParameters parameters) {
for (ExpectedTypeInfo info : JavaSmartCompletionContributor.getExpectedTypes(parameters)) {
PsiType type = info.getType();
if (type instanceof PsiClassType || type == PsiType.BOOLEAN) return true;
if (type instanceof PsiClassType || PsiType.BOOLEAN.equals(type)) return true;
}
return false;
}
@@ -325,7 +325,7 @@ public class JavaMemberNameCompletionContributor extends CompletionContributor {
}
}
if (!hasStartMatches(matcher, result) && PsiType.VOID != varType && includeOverlapped) {
if (!hasStartMatches(matcher, result) && !PsiType.VOID.equals(varType) && includeOverlapped) {
// use suggested names as suffixes
final String requiredSuffix = codeStyleManager.getSuffixByVariableKind(varKind);
final String prefix = matcher.getPrefix();
@@ -81,7 +81,7 @@ public class JavaMethodMergingContributor extends CompletionContributor {
private static int getPriority(LookupElement element) {
PsiMethod method = assertNotNull(getItemMethod(element));
return (method.getReturnType() == PsiType.VOID ? 0 : 1) +
return (PsiType.VOID.equals(method.getReturnType()) ? 0 : 1) +
(method.getParameterList().getParametersCount() > 0 ? 2 : 0);
}
@@ -85,12 +85,6 @@ public class JavaSmartCompletionContributor extends CompletionContributor {
return THROWABLES_FILTER;
}
//throws list
PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
if (method != null && PsiTreeUtil.isAncestor(method.getThrowsList(), element, true)) {
return THROWABLES_FILTER;
}
//new xxx.yyy
if (psiElement().afterLeaf(psiElement().withText(".")).withSuperParent(2, psiElement(PsiNewExpression.class)).accepts(element)) {
if (((PsiNewExpression)element.getParent().getParent()).getClassReference() == element.getParent()) {
@@ -107,6 +101,10 @@ public class JavaSmartCompletionContributor extends CompletionContributor {
return null;
}
private static boolean isInsideThrowsList(PsiElement element) {
PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
return method != null && PsiTreeUtil.isAncestor(method.getThrowsList(), element, true);
}
public JavaSmartCompletionContributor() {
@@ -128,11 +126,18 @@ public class JavaSmartCompletionContributor extends CompletionContributor {
PsiTreeUtil.findElementOfClassAtOffset(element.getContainingFile(), parameters.getOffset(), PsiJavaCodeReferenceElement.class, false);
if (reference != null) {
ElementFilter filter = getClassReferenceFilter(element);
boolean completeConstructor = filter != null;
if (filter == null && isInsideThrowsList(element)) {
filter = THROWABLES_FILTER;
}
if (filter != null) {
final List<ExpectedTypeInfo> infos = Arrays.asList(getExpectedTypes(parameters));
for (final LookupElement item : completeReference(element, reference, filter, true, false, parameters, result.getPrefixMatcher())) {
for (LookupElement item : completeReference(element, reference, filter, true, false, parameters, result.getPrefixMatcher())) {
if (item.getObject() instanceof PsiClass) {
result.addElement(decorate(LookupElementDecorator.withInsertHandler(item, ConstructorInsertHandler.SMART_INSTANCE), infos));
if (completeConstructor) {
item = LookupElementDecorator.withInsertHandler(item, ConstructorInsertHandler.SMART_INSTANCE);
}
result.addElement(decorate(item, infos));
}
}
}
@@ -74,7 +74,7 @@ class SmartCastProvider extends CompletionProvider<CompletionParameters> {
type = ((PsiWildcardType)type).getBound();
}
if (type == null || type == PsiType.VOID) {
if (type == null || PsiType.VOID.equals(type)) {
continue;
}
@@ -16,18 +16,33 @@
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.CodeInsightUtilCore;
import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.lookup.*;
import com.intellij.codeInsight.template.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.util.Consumer;
import com.intellij.util.Function;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import static com.intellij.util.containers.ContainerUtil.*;
public class AddVariableInitializerFix implements IntentionAction {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.AddReturnFix");
@@ -62,9 +77,10 @@ public class AddVariableInitializerFix implements IntentionAction {
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
if (!FileModificationService.getInstance().prepareFileForWrite(myVariable.getContainingFile())) return;
String initializerText = suggestInitializer();
PsiElementFactory factory = JavaPsiFacade.getInstance(myVariable.getProject()).getElementFactory();
PsiExpression initializer = factory.createExpressionFromText(initializerText, myVariable);
final LookupElement[] suggestedInitializers = suggestInitializer(myVariable);
LOG.assertTrue(suggestedInitializers.length > 0);
LOG.assertTrue(suggestedInitializers[0] instanceof ExpressionLookupItem);
final PsiExpression initializer = (PsiExpression) suggestedInitializers[0].getObject();
if (myVariable instanceof PsiLocalVariable) {
((PsiLocalVariable)myVariable).setInitializer(initializer);
}
@@ -74,17 +90,120 @@ public class AddVariableInitializerFix implements IntentionAction {
else {
LOG.error("Unknown variable type: "+myVariable);
}
PsiVariable var = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(myVariable);
TextRange range = var.getInitializer().getTextRange();
int offset = range.getStartOffset();
editor.getCaretModel().moveToOffset(offset);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset());
runAssignmentTemplate(Collections.singletonList(myVariable.getInitializer()), suggestedInitializers, editor);
}
private String suggestInitializer() {
PsiType type = myVariable.getType();
return PsiTypesUtil.getDefaultValueOfType(type);
public static void runAssignmentTemplate(@NotNull final List<PsiExpression> initializers,
@NotNull final LookupElement[] suggestedInitializers,
@Nullable Editor editor) {
if (editor == null) return;
LOG.assertTrue(!initializers.isEmpty());
final PsiExpression initializer = ContainerUtil.getFirstItem(initializers);
PsiElement context = initializers.size() == 1 ? initializer : PsiTreeUtil.findCommonParent(initializers);
PsiDocumentManager.getInstance(initializer.getProject()).doPostponedOperationsAndUnblockDocument(editor.getDocument());
final TemplateBuilderImpl builder = (TemplateBuilderImpl)TemplateBuilderFactory.getInstance().createTemplateBuilder(context);
for (PsiExpression e : initializers) {
builder.replaceElement(e, new Expression() {
@Nullable
@Override
public Result calculateResult(ExpressionContext context1) {
return calculateQuickResult(context1);
}
@Nullable
@Override
public Result calculateQuickResult(ExpressionContext context1) {
return new PsiElementResult(suggestedInitializers[0].getPsiElement());
}
@Nullable
@Override
public LookupElement[] calculateLookupItems(ExpressionContext context1) {
return suggestedInitializers;
}
});
}
builder.run(editor, false);
}
@NotNull
public static LookupElement[] suggestInitializer(final PsiVariable variable) {
PsiType type = variable.getType();
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(variable.getProject());
if (type instanceof PsiClassType) {
final PsiClass aClass = PsiTypesUtil.getPsiClass(type);
if (aClass != null) {
final LookupElement nullLookupItem = new ExpressionLookupItem(elementFactory.createExpressionFromText(PsiKeyword.NULL, variable));
if (InheritanceUtil.isInheritor(aClass, CommonClassNames.JAVA_LANG_ITERABLE) ||
InheritanceUtil.isInheritor(aClass, CommonClassNames.JAVA_UTIL_MAP)) {
final List<PsiType> suggestedTypes = new SmartList<PsiType>();
JavaInheritorsGetter.processInheritors(variable.getContainingFile(), variable, Collections.singleton((PsiClassType) type), PrefixMatcher.ALWAYS_TRUE, new Consumer<PsiType>() {
@Override
public void consume(PsiType type) {
LOG.assertTrue(type instanceof PsiClassType);
final PsiClass psiClass = PsiTypesUtil.getPsiClass(type);
if (psiClass != null &&
!psiClass.isInterface() &&
!psiClass.hasModifierProperty(PsiModifier.ABSTRACT) &&
psiClass.hasModifierProperty(PsiModifier.PUBLIC) &&
PsiUtil.hasDefaultConstructor(psiClass)) {
suggestedTypes.add(type);
}
}
});
List<LookupElement> sortedLookups = map(sorted(map(suggestedTypes, new Function<PsiType, LookupElement>() {
@Override
public LookupElement fun(PsiType type) {
return PsiTypeLookupItem.createLookupItem(type, variable);
}
}), new Comparator<LookupElement>() {
@Override
public int compare(LookupElement o1, LookupElement o2) {
final int count1 = StatisticsWeigher.getBaseStatisticsInfo(o1, null).getUseCount();
final int count2 = StatisticsWeigher.getBaseStatisticsInfo(o2, null).getUseCount();
return count2 - count1;
}
}), new Function<LookupElement, LookupElement>() {
@Override
public LookupElement fun(LookupElement element) {
final LookupElementDecorator<LookupElement> constructorLookupElement =
LookupElementDecorator.withInsertHandler(element, ConstructorInsertHandler.BASIC_INSTANCE);
return new LookupElementDecorator<LookupElement>(constructorLookupElement) {
@Override
public void renderElement(LookupElementPresentation presentation) {
super.renderElement(presentation);
presentation.setTailText("");
presentation.setItemText(PsiKeyword.NEW + " " + presentation.getItemText() + "()");
}
@Override
public void handleInsert(InsertionContext context) {
super.handleInsert(context);
context.getDocument().insertString(context.getStartOffset(), PsiKeyword.NEW + " ");
}
};
}
});
LookupElement[] result = new LookupElement[sortedLookups.size() + 1];
result[0] = nullLookupItem;
for (int i = 0; i < sortedLookups.size(); i++) {
LookupElement lookup = sortedLookups.get(i);
result[i + 1] = lookup;
}
return result;
} else {
if (PsiUtil.hasDefaultConstructor(aClass)) {
final PsiExpression newExpression = elementFactory
.createExpressionFromText(PsiKeyword.NEW + " " + type.getCanonicalText(false) + "()", variable);
return new LookupElement[]{nullLookupItem, new ExpressionLookupItem(newExpression)};
}
}
}
}
final String defaultValue = PsiTypesUtil.getDefaultValueOfType(type);
final PsiExpression expression = elementFactory.createExpressionFromText(defaultValue, variable);
return new LookupElement[] {new ExpressionLookupItem(expression)};
}
@Override
@@ -145,7 +145,7 @@ public class DelegateWithDefaultParamValueIntentionAction extends PsiElementBase
final String methodCall;
if (method.getReturnType() == null) {
methodCall = "this";
} else if (method.getReturnType() != PsiType.VOID) {
} else if (!PsiType.VOID.equals(method.getReturnType())) {
methodCall = "return " + method.getName();
} else {
methodCall = method.getName();
@@ -15,23 +15,20 @@
*/
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.CodeInsightUtilCore;
import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.generation.PsiMethodMember;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.ide.util.MemberChooser;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
@@ -93,59 +90,34 @@ public class InitializeFinalFieldInConstructorFix implements IntentionAction {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
final List<PsiExpressionStatement> statements = addFieldInitialization(constructors, myField, project);
final PsiExpressionStatement highestStatement = getHighestElement(statements);
if (highestStatement == null) return;
final PsiAssignmentExpression expression = (PsiAssignmentExpression)highestStatement.getExpression();
final PsiElement rightExpression = expression.getRExpression();
final TextRange expressionRange = rightExpression.getTextRange();
editor.getCaretModel().moveToOffset(expressionRange.getStartOffset());
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
editor.getSelectionModel().setSelection(expressionRange.getStartOffset(), expressionRange.getEndOffset());
addFieldInitialization(constructors, myField, project, editor);
}
});
}
@Nullable
private static <T extends PsiElement> T getHighestElement(@NotNull List<T> elements) {
T highest = null;
int highestTextOffset = Integer.MAX_VALUE;
for (T element : elements) {
final T forcedElem = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(element);
final int startOffset = forcedElem.getTextOffset();
if (startOffset < highestTextOffset) {
highest = forcedElem;
highestTextOffset = startOffset;
}
}
return highest;
}
private static void addFieldInitialization(@NotNull List<PsiMethod> constructors,
@NotNull PsiField field,
@NotNull Project project,
@Nullable Editor editor) {
final List<PsiExpression> rExpressions = new ArrayList<PsiExpression>(constructors.size());
final LookupElement[] suggestedInitializers = AddVariableInitializerFix.suggestInitializer(field);
@NotNull
private static List<PsiExpressionStatement> addFieldInitialization(@NotNull List<PsiMethod> constructors,
@NotNull PsiField field,
@NotNull Project project) {
final List<PsiExpressionStatement> statements = new ArrayList<PsiExpressionStatement>();
for (PsiMethod constructor : constructors) {
final PsiExpressionStatement statement = addFieldInitialization(constructor, field, project);
if (statement != null) {
statements.add(statement);
}
rExpressions.add(addFieldInitialization(constructor, suggestedInitializers, field, project));
}
return statements;
AddVariableInitializerFix.runAssignmentTemplate(rExpressions, suggestedInitializers, editor);
}
@Nullable
private static PsiExpressionStatement addFieldInitialization(@NotNull PsiMethod constructor,
@NotNull PsiField field,
@NotNull Project project) {
private static PsiExpression addFieldInitialization(@NotNull PsiMethod constructor,
@NotNull LookupElement[] suggestedInitializers,
@NotNull PsiField field,
@NotNull Project project) {
PsiCodeBlock methodBody = constructor.getBody();
if (methodBody == null) return null;
final String fieldName = field.getName();
String stmtText = fieldName + " = " + suggestInitValue(field) + ";";
String stmtText = fieldName + " = " + suggestedInitializers[0].getPsiElement().getText() + ";";
if (methodContainsParameterWithName(constructor, fieldName)) {
stmtText = "this." + stmtText;
}
@@ -154,7 +126,9 @@ public class InitializeFinalFieldInConstructorFix implements IntentionAction {
final PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();
final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
return (PsiExpressionStatement)methodBody.add(codeStyleManager.reformat(factory.createStatementFromText(stmtText, methodBody)));
final PsiExpressionStatement addedStatement = (PsiExpressionStatement)methodBody.add(codeStyleManager
.reformat(factory.createStatementFromText(stmtText, methodBody)));
return ((PsiAssignmentExpression)addedStatement.getExpression()).getRExpression();
}
private static boolean methodContainsParameterWithName(@NotNull PsiMethod constructor, @NotNull String name) {
@@ -228,11 +202,6 @@ public class InitializeFinalFieldInConstructorFix implements IntentionAction {
return result.toArray(new PsiMethod[result.size()]);
}
private static String suggestInitValue(@NotNull PsiField field) {
PsiType type = field.getType();
return PsiTypesUtil.getDefaultValueOfType(type);
}
@Override
public boolean startInWriteAction() {
return false;
@@ -55,7 +55,7 @@ public class MissingReturnExpressionFixer implements Fixer {
PsiElement parent = PsiTreeUtil.getParentOfType(psiElement, PsiClassInitializer.class, PsiMethod.class);
if (parent instanceof PsiMethod) {
final PsiType returnType = ((PsiMethod)parent).getReturnType();
if (returnType != null && returnType != PsiType.VOID) {
if (returnType != null && !PsiType.VOID.equals(returnType)) {
final int startOffset = retStatement.getTextRange().getStartOffset();
if (returnValue != null) {
editor.getDocument().insertString(startOffset + "return".length(), ";");
@@ -84,7 +84,7 @@ public class MissingReturnExpressionFixer implements Fixer {
if (!(prev instanceof PsiJavaToken)) {
int offset = returnStatement.getTextRange().getEndOffset();
final PsiMethod method = PsiTreeUtil.getParentOfType(returnStatement, PsiMethod.class, true, PsiLambdaExpression.class);
if (method != null && method.getReturnType() == PsiType.VOID) {
if (method != null && PsiType.VOID.equals(method.getReturnType())) {
offset = returnStatement.getTextRange().getStartOffset() + "return".length();
}
editor.getDocument().insertString(offset, ";");
@@ -101,7 +101,7 @@ public class MissingReturnExpressionFixer implements Fixer {
editor.getDocument().insertString(offset, ";");
if (prevToken.getTokenType() == JavaTokenType.RETURN_KEYWORD) {
final PsiMethod method = PsiTreeUtil.getParentOfType(returnStatement, PsiMethod.class);
if (method != null && method.getReturnType() != PsiType.VOID) {
if (method != null && !PsiType.VOID.equals(method.getReturnType())) {
editor.getCaretModel().moveToOffset(offset);
processor.setSkipEnter(true);
}
@@ -115,7 +115,7 @@ public class GenerateDelegateHandler implements LanguageCodeInsightActionHandler
PsiModifierList modifierList = null;
if (method.getReturnType() != PsiType.VOID) {
if (!PsiType.VOID.equals(method.getReturnType())) {
call.append("return ");
}
@@ -337,7 +337,7 @@ public class OverrideImplementUtil extends OverrideImplementExploreUtil {
@NotNull
public static String callSuper(PsiMethod superMethod, PsiMethod overriding) {
@NonNls StringBuilder buffer = new StringBuilder();
if (!superMethod.isConstructor() && superMethod.getReturnType() != PsiType.VOID) {
if (!superMethod.isConstructor() && !PsiType.VOID.equals(superMethod.getReturnType())) {
buffer.append("return ");
}
buffer.append("super");
@@ -54,7 +54,7 @@ public class IntroduceVariableIntentionAction extends BaseRefactoringIntentionAc
final PsiExpression expression = statement.getExpression();
return expression.getType() != PsiType.VOID && !(expression instanceof PsiAssignmentExpression);
return !PsiType.VOID.equals(expression.getType()) && !(expression instanceof PsiAssignmentExpression);
}
@Override
@@ -406,7 +406,7 @@ public class JavaDocumentationProvider extends DocumentationProviderEx implement
if (typeParameterList != null) {
createTypeParamsListComment(builder, project, commenter, typeParameterList);
}
if (psiMethod.getReturnType() != null && psiMethod.getReturnType() != PsiType.VOID) {
if (psiMethod.getReturnType() != null && !PsiType.VOID.equals(psiMethod.getReturnType())) {
builder.append(CodeDocumentationUtil.createDocCommentLine(RETURN_TAG, project, commenter));
builder.append(LINE_SEPARATOR);
}
@@ -41,6 +41,7 @@ import com.intellij.refactoring.util.*;
import com.intellij.refactoring.util.usageInfo.DefaultConstructorImplicitUsageInfo;
import com.intellij.refactoring.util.usageInfo.NoConstructorClassUsageInfo;
import com.intellij.usageView.UsageInfo;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.VisibilityUtil;
import com.intellij.util.containers.ContainerUtil;
@@ -857,13 +858,13 @@ public class JavaChangeSignatureUsageProcessor implements ChangeSignatureUsagePr
public boolean value(Pair<PsiParameter, String> pair) {
final PsiParameter parameter = pair.first;
final String oldParamName = pair.second;
final int idx = Arrays.binarySearch(oldParameterNames, oldParamName);
final int idx = ArrayUtil.find(oldParameterNames, oldParamName);
return idx >= 0 && idx == method.getParameterList().getParameterIndex(parameter) && changeInfo.getNewParameters()[idx].getOldIndex() == idx;
}
}, new Condition<String>() {
@Override
public boolean value(String paramName) {
return Arrays.binarySearch(oldParameterNames, paramName) >= 0;
return ArrayUtil.find(oldParameterNames, paramName) >= 0;
}
});
}
@@ -267,10 +267,10 @@ public class ExtractMethodProcessor implements MatchProvider {
if (expressionType == null) {
expressionType = PsiType.VOID;
}
myHasExpressionOutput = expressionType != PsiType.VOID;
myHasExpressionOutput = !PsiType.VOID.equals(expressionType);
final PsiType returnStatementType = getExpectedReturnType();
myHasReturnStatementOutput = myHasReturnStatement && returnStatementType != null && returnStatementType != PsiType.VOID;
myHasReturnStatementOutput = myHasReturnStatement && returnStatementType != null && !PsiType.VOID.equals(returnStatementType);
if (myGenerateConditionalExit && myOutputVariables.length == 1) {
if (!(myOutputVariables[0].getType() instanceof PsiPrimitiveType)) {
@@ -381,7 +381,7 @@ public class ExtractMethodProcessor implements MatchProvider {
private boolean areAllExitPointsAreNotNull(PsiType returnStatementType) {
if (insertNotNullCheckIfPossible() && myControlFlowWrapper.getOutputVariables(false).length == 0) {
boolean isNotNull = returnStatementType != null && returnStatementType != PsiType.VOID;
boolean isNotNull = returnStatementType != null && !PsiType.VOID.equals(returnStatementType);
for (PsiStatement statement : myExitStatements) {
if (statement instanceof PsiReturnStatement) {
final PsiExpression returnValue = ((PsiReturnStatement)statement).getReturnValue();
@@ -432,7 +432,7 @@ public class ExtractMethodProcessor implements MatchProvider {
return;
}
final PsiMethod method = (PsiMethod)myCodeFragmentMember;
if (!method.isConstructor() || myReturnType != PsiType.VOID) {
if (!method.isConstructor() || !PsiType.VOID.equals(myReturnType)) {
return;
}
final PsiCodeBlock body = method.getBody();
@@ -277,7 +277,7 @@ public class ExtractLightMethodObjectHandler {
private static boolean isValidVariableType(PsiType type) {
if (type instanceof PsiClassType ||
type instanceof PsiArrayType ||
type instanceof PsiPrimitiveType && type != PsiType.VOID) {
type instanceof PsiPrimitiveType && !PsiType.VOID.equals(type)) {
return true;
}
return false;
@@ -549,7 +549,7 @@ public class InheritanceToDelegationProcessor extends BaseRefactoringProcessor {
@NonNls final StringBuffer buffer = new StringBuffer();
buffer.append("{\n");
if (methodToAdd.getReturnType() != PsiType.VOID) {
if (!PsiType.VOID.equals(methodToAdd.getReturnType())) {
buffer.append("return ");
}
@@ -747,7 +747,7 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
PsiType returnType = callSubstitutor.substitute(myMethod.getReturnType());
String resultName = null;
final int applicabilityLevel = PsiUtil.getApplicabilityLevel(myMethod, callSubstitutor, argumentList);
if (returnType != null && returnType != PsiType.VOID && tailCallType == InlineUtil.TailCallType.None) {
if (returnType != null && !PsiType.VOID.equals(returnType) && tailCallType == InlineUtil.TailCallType.None) {
resultName = myJavaCodeStyle.propertyNameToVariableName("result", VariableKind.LOCAL_VARIABLE);
resultName = myJavaCodeStyle.suggestUniqueVariableName(resultName, block.getFirstChild(), true);
PsiDeclarationStatement declaration = myFactory.createVariableDeclarationStatement(resultName, returnType, null);
@@ -236,7 +236,7 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase {
PsiExpression expression = PsiTreeUtil.getParentOfType(elementAtCaret, PsiExpression.class);
while (expression != null) {
if (!expressions.contains(expression) && !(expression instanceof PsiParenthesizedExpression) && !(expression instanceof PsiSuperExpression) &&
(acceptVoid || expression.getType() != PsiType.VOID)) {
(acceptVoid || !PsiType.VOID.equals(expression.getType()))) {
if (expression instanceof PsiMethodReferenceExpression) {
expressions.add(expression);
}
@@ -179,14 +179,15 @@ public class MoveJavaMemberHandler implements MoveMemberHandler {
changeQualifier(refExpr, usage.qualifierClass, usage.member);
}
else {
final PsiReferenceParameterList parameterList = refExpr.getParameterList();
if (parameterList != null && parameterList.getTypeArguments().length == 0 && !(refExpr instanceof PsiMethodReferenceExpression)){
refExpr.setQualifierExpression(null);
} else {
final Project project = element.getProject();
final PsiClass targetClass =
JavaPsiFacade.getInstance(project).findClass(options.getTargetClassName(), GlobalSearchScope.projectScope(project));
if (targetClass != null) {
final Project project = element.getProject();
final PsiClass targetClass =
JavaPsiFacade.getInstance(project).findClass(options.getTargetClassName(), GlobalSearchScope.projectScope(project));
if (targetClass != null) {
final PsiReferenceParameterList parameterList = refExpr.getParameterList();
if ((targetClass.isEnum() || PsiTreeUtil.isAncestor(targetClass, element, true)) && parameterList != null && parameterList.getTypeArguments().length == 0 && !(refExpr instanceof PsiMethodReferenceExpression)) {
refExpr.setQualifierExpression(null);
}
else {
changeQualifier(refExpr, targetClass, usage.member);
}
}
@@ -38,7 +38,7 @@ public class WrapReturnValueAction extends BaseRefactoringAction{
final PsiMethod psiMethod = PsiTreeUtil.getParentOfType(element, PsiMethod.class, false);
if (psiMethod != null && !(psiMethod instanceof PsiCompiledElement)) {
final PsiType returnType = psiMethod.getReturnType();
return returnType != null && returnType != PsiType.VOID;
return returnType != null && !PsiType.VOID.equals(returnType);
}
return false;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@ import com.intellij.psi.*;
import com.intellij.psi.util.PsiFormatUtil;
import com.intellij.psi.util.PsiFormatUtilBase;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.ui.JBColor;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.usages.TextChunk;
import com.intellij.util.FontUtil;
@@ -56,7 +57,7 @@ public class SliceUsageCellRenderer extends SliceUsageCellRendererBase {
TextChunk textChunk = text[i];
SimpleTextAttributes attributes = textChunk.getSimpleAttributesIgnoreBackground();
if (isForcedLeaf) {
attributes = attributes.derive(attributes.getStyle(), Color.LIGHT_GRAY, attributes.getBgColor(), attributes.getWaveColor());
attributes = attributes.derive(attributes.getStyle(), JBColor.LIGHT_GRAY, attributes.getBgColor(), attributes.getWaveColor());
}
boolean inUsage = (attributes.getFontStyle() & Font.BOLD) != 0;
if (isInsideContainer && inUsage) {
@@ -66,7 +67,7 @@ public class SliceUsageCellRenderer extends SliceUsageCellRendererBase {
//setPaintFocusBorder(true);
}
append(textChunk.getText(), attributes);
if(i == 0){
if (i == 0) {
append(FontUtil.spaceAndThinSpace());
}
}
@@ -132,7 +132,7 @@ public class LambdaUtil {
public static boolean isLambdaFullyInferred(PsiLambdaExpression expression, PsiType functionalInterfaceType) {
final boolean hasParams = expression.getParameterList().getParametersCount() > 0;
if (hasParams || getFunctionalInterfaceReturnType(functionalInterfaceType) != PsiType.VOID) { //todo check that void lambdas without params check
if (hasParams || !PsiType.VOID.equals(getFunctionalInterfaceReturnType(functionalInterfaceType))) { //todo check that void lambdas without params check
return !dependsOnTypeParams(functionalInterfaceType, functionalInterfaceType, expression);
}
@@ -570,7 +570,7 @@ public class LambdaUtil {
}
public static String checkReturnTypeCompatible(PsiLambdaExpression lambdaExpression, PsiType functionalInterfaceReturnType) {
if (functionalInterfaceReturnType == PsiType.VOID) {
if (PsiType.VOID.equals(functionalInterfaceReturnType)) {
final PsiElement body = lambdaExpression.getBody();
if (body instanceof PsiCodeBlock) {
if (!getReturnExpressions(lambdaExpression).isEmpty()) return "Unexpected return value";
@@ -32,7 +32,7 @@ import java.util.*;
public class PsiIntersectionType extends PsiType.Stub {
private final PsiType[] myConjuncts;
private PsiIntersectionType(@NotNull PsiType[] conjuncts) {
protected PsiIntersectionType(@NotNull PsiType[] conjuncts) {
super(PsiAnnotation.EMPTY_ARRAY);
myConjuncts = conjuncts;
}
@@ -67,7 +67,7 @@ public class PsiIntersectionType extends PsiType.Stub {
}
}
private static Set<PsiType> flatten(PsiType[] conjuncts, Set<PsiType> types) {
protected static Set<PsiType> flatten(PsiType[] conjuncts, Set<PsiType> types) {
for (PsiType conjunct : conjuncts) {
if (conjunct instanceof PsiIntersectionType) {
PsiIntersectionType type = (PsiIntersectionType)conjunct;
@@ -321,7 +321,7 @@ public class PsiMethodReferenceUtil {
returnType = ((PsiMethod)resolve).getReturnType();
}
PsiType methodReturnType = subst.substitute(returnType);
if (interfaceReturnType != null && interfaceReturnType != PsiType.VOID) {
if (interfaceReturnType != null && !PsiType.VOID.equals(interfaceReturnType)) {
if (methodReturnType == null) {
methodReturnType = JavaPsiFacade.getElementFactory(expression.getProject()).createType(containingClass, subst);
}
@@ -33,7 +33,11 @@ public class PsiClassUtil {
public static boolean isRunnableClass(final PsiClass aClass, final boolean mustBePublic, boolean mustNotBeAbstract) {
if (aClass instanceof PsiAnonymousClass) return false;
if (aClass.isInterface()) return false;
if (mustBePublic && !aClass.hasModifierProperty(PsiModifier.PUBLIC)) return false;
if (mustBePublic && !aClass.hasModifierProperty(PsiModifier.PUBLIC)) {
if (mustNotBeAbstract || !aClass.hasModifierProperty(PsiModifier.ABSTRACT)) {
return false;
}
}
if (aClass.hasModifierProperty(PsiModifier.PRIVATE)) return false;
if (mustNotBeAbstract && aClass.hasModifierProperty(PsiModifier.ABSTRACT)) return false;
return aClass.getContainingClass() == null || aClass.hasModifierProperty(PsiModifier.STATIC);
@@ -66,7 +66,7 @@ public class PsiConcatenationUtil {
addFormatParameter(subExpression, formatString, formatParameters, printfFormat);
}
if (stringStarted) {
if (optype != null && (optype.equalsToText(JAVA_LANG_STRING) || optype == PsiType.CHAR)) {
if (optype != null && (optype.equalsToText(JAVA_LANG_STRING) || PsiType.CHAR.equals(optype))) {
buildFormatString(op, formatString, formatParameters, printfFormat);
}
else {
@@ -15,10 +15,10 @@
*/
package com.intellij.psi.util;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.psi.*;
import com.intellij.codeInsight.runner.JavaMainMethodProvider;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.*;
import org.jetbrains.annotations.Nullable;
/**
@@ -59,7 +59,7 @@ public class PsiMethodUtil {
public static boolean isMainMethod(final PsiMethod method) {
if (method == null || method.getContainingClass() == null) return false;
if (PsiType.VOID != method.getReturnType()) return false;
if (!PsiType.VOID.equals(method.getReturnType())) return false;
if (!method.hasModifierProperty(PsiModifier.STATIC)) return false;
if (!method.hasModifierProperty(PsiModifier.PUBLIC)) return false;
final PsiParameter[] parameters = method.getParameterList().getParameters();
@@ -658,7 +658,16 @@ public class PsiImplUtil {
findApplicableTarget((PsiAnnotation)element, TargetType.TYPE_USE) == TargetType.TYPE_USE;
}
@Nullable
public static void collectTypeUseAnnotations(@NotNull PsiModifierList modifierList, @NotNull List<PsiAnnotation> annotations) {
for (PsiAnnotation annotation : modifierList.getAnnotations()) {
if (isTypeAnnotation(annotation)) {
annotations.add(annotation);
}
}
}
/** @deprecated use {@link #collectTypeUseAnnotations(PsiModifierList, List)} (to be removed in IDEA 16) */
@SuppressWarnings("unused")
public static List<PsiAnnotation> getTypeUseAnnotations(@NotNull PsiModifierList modifierList) {
SmartList<PsiAnnotation> result = null;
@@ -592,10 +592,7 @@ public class PsiJavaCodeReferenceElementImpl extends CompositePsiElement impleme
if (!isQualified()) {
PsiModifierList modifierList = PsiImplUtil.findNeighbourModifierList(this);
if (modifierList != null) {
List<PsiAnnotation> typeAnnotations = PsiImplUtil.getTypeUseAnnotations(modifierList);
if (typeAnnotations != null && !typeAnnotations.isEmpty()) {
annotations.addAll(typeAnnotations);
}
PsiImplUtil.collectTypeUseAnnotations(modifierList, annotations);
}
}
@@ -37,6 +37,8 @@ import org.jetbrains.annotations.Nullable;
import java.util.List;
public class PsiTypeElementImpl extends CompositePsiElement implements PsiTypeElement {
private static final Class[] INTERMEDIATES = {PsiComment.class, PsiWhiteSpace.class, PsiAnnotation.class, PsiTypeParameterList.class};
@SuppressWarnings({"UnusedDeclaration"})
public PsiTypeElementImpl() {
this(JavaElementType.TYPE);
@@ -69,7 +71,7 @@ public class PsiTypeElementImpl extends CompositePsiElement implements PsiTypeEl
}
private PsiType calculateType() {
final PsiType inferredType = PsiAugmentProvider.getInferredType(this);
PsiType inferredType = PsiAugmentProvider.getInferredType(this);
if (inferredType != null) {
return inferredType;
}
@@ -153,16 +155,13 @@ public class PsiTypeElementImpl extends CompositePsiElement implements PsiTypeEl
return type == null ? PsiType.NULL : type;
}
private void addTypeUseAnnotations(List<PsiAnnotation> list) {
private void addTypeUseAnnotations(List<PsiAnnotation> annotations) {
PsiElement parent = this;
while (parent instanceof PsiTypeElement) {
PsiElement left = PsiTreeUtil.skipSiblingsBackward(parent, PsiComment.class, PsiWhiteSpace.class, PsiAnnotation.class);
PsiElement left = PsiTreeUtil.skipSiblingsBackward(parent, INTERMEDIATES);
if (left instanceof PsiModifierList) {
List<PsiAnnotation> annotations = PsiImplUtil.getTypeUseAnnotations((PsiModifierList)left);
if (annotations != null && !annotations.isEmpty()) {
list.addAll(annotations);
}
PsiImplUtil.collectTypeUseAnnotations((PsiModifierList)left, annotations);
break;
}
@@ -75,7 +75,7 @@ public class ReplaceExpressionUtil {
}
else if (i == JavaElementType.ARRAY_ACCESS_EXPRESSION) {
int role = ((CompositeElement)oldParent).getChildRole(oldExpr);
return role != ChildRole.ARRAY_DIMENSION && priority < parentPriority;
return role != ChildRole.ARRAY_DIMENSION && role != ChildRole.INDEX && priority < parentPriority;
}
else if (i == JavaElementType.ARRAY_INITIALIZER_EXPRESSION) {
return false;
@@ -0,0 +1,10 @@
class FirstException extends Exception {}
class SecondException extends Exception {}
interface I {
void method() throws FirstException, SecondException;
}
class C implements I {
void method() throws FirstException, SecondException<caret>;
}
@@ -0,0 +1,10 @@
class FirstException extends Exception {}
class SecondException extends Exception {}
interface I {
void method() throws FirstException, SecondException;
}
class C implements I {
void method() throws FirstException, Sec<caret>;
}
@@ -0,0 +1,47 @@
import java.util.Comparator;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.stream.Stream;
class Bug {
public static void main(String[] args) {
Stream<String> tokenStream = Stream.of("hello", "world");
Comparator<String> order = Comparator.naturalOrder();
Min<String> min = tokenStream.collect(
() -> new Min<>(order),
Min::accept,
Min::combine);
System.out.printf("Min = %s%n",
min.asOptional().orElse(null));
}
static class Min<T> implements Consumer<T> {
private final BinaryOperator<T> minOf;
private T min;
public Min(Comparator<? super T> order) {
this.minOf = BinaryOperator.minBy(order);
}
@Override
public void accept(T t) {
this.min = min != null ? minOf.apply(min, t) : t;
}
public void combine(Min<T> other) {
if (other.min != null) {
accept(other.min);
}
}
public Optional<T> asOptional() {
return Optional.ofNullable(min);
}
}
}
@@ -3,7 +3,7 @@
class AClass
{
int f() {
int i = <caret><selection>0</selection>;
int i = 0<caret>;
return i;
}
}
@@ -2,6 +2,6 @@
class AClass
{
final AClass f = <caret><selection>null</selection>;
final AClass f = null<caret>;
}
@@ -3,10 +3,10 @@ class A {
private final int var;
private Main() {
var = <caret><selection>0</selection>;
var = 0;
}
private Main(int var) {
this.var = 0;
}
}
}<caret>
@@ -3,6 +3,6 @@ class A {
private final int var;
private Main(int var) {
this.var = <caret><selection>0</selection>;
this.var = 0<caret>;
}
}
@@ -3,6 +3,6 @@ class A {
private final int var;
private Main() {
var = <caret><selection>0</selection>;
var = 0<caret>;
}
}
@@ -0,0 +1,15 @@
import javax.annotation.*;
@NonnullByDefault
class Test {
Object <warning descr="@NonnullByDefault fields must be initialized">member</warning>;
private void accessMember() {
member = new Object();
}
}
@Nonnull
@javax.annotation.meta.TypeQualifierDefault(java.lang.annotation.ElementType.FIELD)
@interface NonnullByDefault {}
@@ -0,0 +1,30 @@
/*
* 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.
*/
class C {
/**
* This is the role -
* @param role another desc
* @param labelExpression blah-blah
* @return return description
*/
public Integer ex<caret>ample(int role, String labelExpression) {
switch (role) {
case Constants.FOO:
break;
}
return 1;
}
}
@@ -0,0 +1,29 @@
/*
* 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.
*/
class C {
/**
* This is the role -
* @param role another desc
* @return return description
*/
public Integer example(int role) {
switch (role) {
case Constants.FOO:
break;
}
return 1;
}
}
@@ -0,0 +1,6 @@
class C {
void f(int[] a, int i) {
int i1 = i + 1;
int temp = a[i<caret>1];
}
}
@@ -0,0 +1,5 @@
class C {
void f(int[] a, int i) {
int temp = a[i + 1];
}
}
@@ -0,0 +1,13 @@
public class B {
public static final String FOO = "FOO";
}
class U {
public void example(String foo) {
switch (foo) {
case B.FOO:
break;
}
}
}
@@ -0,0 +1,3 @@
public interface A {
public static final String FOO = "FOO";
}
@@ -0,0 +1,12 @@
public class B {
}
class U {
public void example(String foo) {
switch (foo) {
case A.FOO:
break;
}
}
}
@@ -428,6 +428,8 @@ public class SmartTypeCompletionTest extends LightFixtureCompletionTestCase {
public void testJavadocThrows() throws Throwable { doTest(); }
public void testMethodThrows() throws Throwable { doTest(); }
public void testDoNotExcludeAssignedVariable() throws Throwable { doTest(); }
public void testArrayIndexTailType() throws Throwable { doTest(); }
@@ -80,6 +80,7 @@ public class InferredTypeTest extends LightCodeInsightFixtureTestCase {
final PsiJavaFile file = (PsiJavaFile)myFixture.addFileToProject("R.java", "public interface R {@D void run();}");
final PsiClass psiClass = file.getClasses()[0];
final PsiMethod method = psiClass.getMethods()[0];
//noinspection UsePrimitiveTypes
assertFalse(PsiType.VOID == method.getReturnType());
myFixture.configureByText("a.java", "class A {{R r = () -> {};}} ");
myFixture.checkHighlighting(false, false, false);
@@ -446,6 +446,10 @@ public class NewMethodRefHighlightingTest extends LightDaemonAnalyzerTestCase {
doTest();
}
public void testIDEA147511() throws Exception {
doTest();
}
private void doTest() {
doTest(false);
}
@@ -40,8 +40,8 @@ class AnnotatedTypeTest extends LightCodeInsightFixtureTestCase {
class I { }
}
class E1 extends Exception { }
class E2 extends Exception { }""".stripIndent())
@SuppressWarnings("ExceptionClassNameDoesntEndWithException") class E1 extends Exception { }
@SuppressWarnings("ExceptionClassNameDoesntEndWithException") class E2 extends Exception { }""".stripIndent())
}
public void testPrimitiveArrayType() {
@@ -78,20 +78,32 @@ class AnnotatedTypeTest extends LightCodeInsightFixtureTestCase {
public void testDisjunctionType() {
def psi = factory.createStatementFromText("try { } catch (@A @TA(1) E1 | @TA(2) E2 e) { }", context) as PsiTryStatement
assertTypeText(psi.catchBlockParameters[0].type, "pkg.@pkg.TA(1) E1 | pkg.@pkg.TA(2) E2", "pkg.E1 | pkg.E2")
assertTypeText psi.catchBlockParameters[0].type, "pkg.@pkg.TA(1) E1 | pkg.@pkg.TA(2) E2", "pkg.E1 | pkg.E2"
}
public void testDiamondType() {
def psi = factory.createStatementFromText("Class<@TA String> cs = new Class<>()", context) as PsiDeclarationStatement
def var = psi.declaredElements[0] as PsiVariable
assertTypeText(var.initializer.type, "java.lang.Class<java.lang.@pkg.TA String>", "java.lang.Class<java.lang.String>")
assertTypeText var.initializer.type, "java.lang.Class<java.lang.@pkg.TA String>", "java.lang.Class<java.lang.String>"
}
public void testImmediateClassType() {
def aClass = myFixture.javaFacade.findClass(CommonClassNames.JAVA_LANG_OBJECT)
def annotations = factory.createParameterFromText("@TA int x", context).modifierList.annotations
def type = new PsiImmediateClassType(aClass, PsiSubstitutor.EMPTY, LanguageLevel.JDK_1_8, annotations)
assertTypeText(type, "java.lang.@pkg.TA Object", CommonClassNames.JAVA_LANG_OBJECT)
assertTypeText type, "java.lang.@pkg.TA Object", CommonClassNames.JAVA_LANG_OBJECT
}
public void testFieldType() {
def psi = factory.createFieldFromText("@A @TA(1) String f;", context)
assertTypeText psi.type, "java.lang.@pkg.TA(1) String", "java.lang.String"
assertAnnotations psi.type, "@TA(1)"
}
public void testMethodReturnType() {
def psi = factory.createMethodFromText("@A @TA(1) String m() { return null; }", context)
assertTypeText psi.returnType, "java.lang.@pkg.TA(1) String", "java.lang.String"
assertAnnotations psi.returnType, "@TA(1)"
}
private void doTest(String text, String annotated, String canonical) {
@@ -102,4 +114,8 @@ class AnnotatedTypeTest extends LightCodeInsightFixtureTestCase {
assert type.getCanonicalText(true) == annotated
assert type.getCanonicalText(false) == canonical
}
private static void assertAnnotations(PsiType type, String... annotations) {
assert type.annotations.collect { it.text } == annotations.toList()
}
}
@@ -59,6 +59,11 @@ public class NullableStuffInspectionTest extends LightCodeInsightFixtureTestCase
doTest();
}
public void testNotNullByDefaultFieldNotInitialized() {
DataFlowInspectionTest.addJavaxNullabilityAnnotations(myFixture);
doTest();
}
public void testNotNullAnnotationChecksInChildClassMethods() { doTest(); }
public void testGetterSetterProblems() throws Exception{ doTest(); }
@@ -38,8 +38,11 @@ import com.intellij.testFramework.PsiTestUtil;
import com.intellij.testFramework.SkipSlowTestLocally;
import com.intellij.testFramework.Timings;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -75,7 +78,7 @@ public class PsiConcurrencyStressTest extends DaemonAnalyzerTestCase {
final CountDownLatch reads = new CountDownLatch(numOfThreads);
final Random random = new Random();
for (int i = 0; i < numOfThreads; i++) {
List<Thread> threads = ContainerUtil.map(Collections.nCopies(numOfThreads, ""), i ->
new Thread(() -> {
for (int i1 = 0; i1 < readIterations; i1++) {
if (myPsiManager == null) return;
@@ -86,8 +89,8 @@ public class PsiConcurrencyStressTest extends DaemonAnalyzerTestCase {
}
reads.countDown();
}, "stress thread" + i).start();
}
}, "stress thread" + i));
threads.forEach(Thread::start);
final Document document = documentManager.getDocument(myFile);
@@ -107,6 +110,15 @@ public class PsiConcurrencyStressTest extends DaemonAnalyzerTestCase {
}
assertTrue("Timed out", reads.await(5, TimeUnit.MINUTES));
ContainerUtil.process(threads, thread -> {
try {
thread.join();
return true;
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
private static void mark(final String s) {
@@ -0,0 +1,62 @@
/*
* Copyright 2000-2015 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.codeStyle.autodetect
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.extensions.ExtensionPoint
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.extensions.LoadingOrder
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.codeStyle.FileIndentOptionsProvider
import com.intellij.testFramework.LightPlatformTestCase
import org.junit.Test
import org.mockito.Matchers
import org.mockito.Mockito.*
class ViewerEditorTest: LightPlatformTestCase() {
lateinit var mockProvider: FileIndentOptionsProvider
lateinit var extensionPoint: ExtensionPoint<FileIndentOptionsProvider>
override fun setUp() {
super.setUp()
extensionPoint = Extensions.getRootArea().getExtensionPoint(FileIndentOptionsProvider.EP_NAME)
mockProvider = mock(FileIndentOptionsProvider::class.java)
extensionPoint.registerExtension(mockProvider, LoadingOrder.FIRST)
}
override fun tearDown() {
extensionPoint.unregisterExtension(mockProvider)
super.tearDown()
}
@Test
fun `test do not use file indent option providers for viewer editors`() {
val file = createFile("Test.java", "class Test {}")
val document = PsiDocumentManager.getInstance(getProject()).getDocument(file)
val editor = EditorFactory.getInstance().createEditor(document!!, getProject(), file.virtualFile, true);
try {
(editor as EditorImpl).reinitSettings()
editor.settings.isLineNumbersShown = true
editor.settings.getTabSize(getProject())
}
finally {
EditorFactory.getInstance().releaseEditor(editor)
}
verify(mockProvider, never()).getIndentOptions(Matchers.any(), Matchers.any())
}
}
@@ -62,7 +62,7 @@ public class JavaAutoDetectIndentPerformanceTest extends AbstractIndentAutoDetec
AbstractIndentAutoDetectionTest.detectIndentOptions();
PlatformTestUtil
.startPerformanceTest("Detecting indent on hot file", 30, AbstractIndentAutoDetectionTest::detectIndentOptions)
.startPerformanceTest("Detecting indent on hot file", 40, AbstractIndentAutoDetectionTest::detectIndentOptions)
.cpuBound()
.assertTiming();
}
@@ -247,6 +247,12 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest {
}, false);
}
public void testJavadocOfDeleted() {
doTest(null, new ParameterInfoImpl[]{
new ParameterInfoImpl(0, "role", PsiType.INT),
}, false);
}
public void testCovariantReturnType() {
doTest(CommonClassNames.JAVA_LANG_RUNNABLE, new ParameterInfoImpl[0], false);
}
@@ -18,7 +18,6 @@ package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
@@ -174,7 +173,11 @@ public class MoveMembersTest extends MultiFileTestCase {
public void testEscalateVisibility1() throws Exception {
doTest("A", "B", true, VisibilityUtil.ESCALATE_VISIBILITY, 0);
}
public void testStringConstantInSwitchLabelExpression() throws Exception {
doTest("A", "B", true, VisibilityUtil.ESCALATE_VISIBILITY, 0);
}
public void testMultipleWithDependencies() throws Exception {
doTest("A", "B", true, VisibilityUtil.ESCALATE_VISIBILITY, 0, 1);
}
@@ -244,6 +244,10 @@ public class InlineLocalTest extends LightCodeInsightTestCase {
doTest(true);
}
public void testArrayAccessPriority() throws Exception {
doTest(true);
}
public void testLocalVarInsideLambdaBodyWriteUsage() throws Exception {
doTest(true, "Cannot perform refactoring.\n" +
"Variable 'hello' is accessed for writing");
@@ -32,6 +32,7 @@ import com.intellij.structuralsearch.plugin.replace.impl.Replacer;
import com.intellij.structuralsearch.plugin.ui.Configuration;
import com.intellij.structuralsearch.plugin.ui.SearchContext;
import com.intellij.structuralsearch.plugin.ui.UIUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -382,7 +383,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile {
private void checkModifier(final String name) {
if (!MatchOptions.INSTANCE_MODIFIER_NAME.equals(name) &&
!PsiModifier.PACKAGE_LOCAL.equals(name) &&
Arrays.binarySearch(JavaMatchingVisitor.MODIFIERS, name) < 0
ArrayUtil.find(JavaMatchingVisitor.MODIFIERS, name) < 0
) {
throw new MalformedPatternException(SSRBundle.message("invalid.modifier.type",name));
}
@@ -530,7 +531,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile {
handleMethodParameter(buf, info, matchMap);
replacementString = buf.toString();
}
else if (match.getAllSons().size() > 0 && !match.isScopeMatch()) {
else if (match.hasSons() && !match.isScopeMatch()) {
// compound matches
StringBuilder buf = new StringBuilder();
MatchResult r = null;
@@ -550,7 +551,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile {
}
}
else if (info.isStatementContext()) {
final PsiElement previousElement = previous.getMatchRef().getElement();
final PsiElement previousElement = previous.getMatch();
if (!(previousElement instanceof PsiComment) &&
( buf.charAt(buf.length() - 1) != '}' ||
@@ -720,15 +721,15 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile {
}
}
private static void appendParameter(final StringBuilder buf, final MatchResult _matchResult) {
for(Iterator<MatchResult> j = _matchResult.getAllSons().iterator();j.hasNext();) {
buf.append(j.next().getMatchImage()).append(' ').append(j.next().getMatchImage());
}
private static void appendParameter(final StringBuilder buf, final MatchResult matchResult) {
final List<MatchResult> sons = matchResult.getAllSons();
assert sons.size() == 1;
buf.append(sons.get(0).getMatchImage()).append(' ').append(matchResult.getMatchImage());
}
private static void removeExtraSemicolonForSingleVarInstanceInMultipleMatch(final ParameterInfo info, MatchResult r, StringBuilder buf) {
if (info.isStatementContext()) {
final PsiElement element = r.getMatchRef().getElement();
final PsiElement element = r.getMatch();
// remove extra ;
if (buf.charAt(buf.length()-1)==';' &&
@@ -941,13 +941,12 @@ public class JavaMatchingVisitor extends JavaElementVisitor {
myMatchingVisitor.getMatchContext().pushResult();
final PsiIdentifier nameIdentifier = var.getNameIdentifier();
boolean isTypedVar = myMatchingVisitor.getMatchContext().getPattern().isTypedVar(nameIdentifier);
final boolean isTypedVar = myMatchingVisitor.getMatchContext().getPattern().isTypedVar(nameIdentifier);
final PsiVariable var2 = (PsiVariable)myMatchingVisitor.getElement();
try {
myMatchingVisitor.setResult((myMatchingVisitor.matchText(var.getNameIdentifier(), var2.getNameIdentifier()) || isTypedVar) &&
((var.getParent() instanceof PsiClass && ((PsiClass)var.getParent()).isInterface()) ||
myMatchingVisitor.match(var.getModifierList(), var2.getModifierList())));
myMatchingVisitor.match(var.getModifierList(), var2.getModifierList()));
if (myMatchingVisitor.getResult()) {
final PsiTypeElement typeElement1 = var.getTypeElement();
if (typeElement1 != null) {
@@ -972,10 +971,6 @@ public class JavaMatchingVisitor extends JavaElementVisitor {
((PsiCatchSection)var2.getParent()).getCatchBlock()
));
}
if (myMatchingVisitor.getResult() && isTypedVar) {
myMatchingVisitor.setResult(myMatchingVisitor.handleTypedElement(nameIdentifier, var2.getNameIdentifier()));
}
}
finally {
saveOrDropResult(nameIdentifier, isTypedVar, var2.getNameIdentifier());
@@ -1692,9 +1687,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor {
myMatchingVisitor.matchSonsOptionally(method.getBody(), method2.getBody()));
}
finally {
final PsiIdentifier methodNameNode2 = method2.getNameIdentifier();
saveOrDropResult(methodNameNode, isTypedVar, methodNameNode2);
saveOrDropResult(methodNameNode, isTypedVar, method2.getNameIdentifier());
}
}
}
@@ -16,7 +16,6 @@
package com.intellij.compiler;
import com.intellij.compiler.server.BuildManager;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.WriteAction;
@@ -34,6 +33,7 @@ import com.intellij.testFramework.EdtTestUtil;
import com.intellij.util.SmartList;
import com.intellij.util.ThrowableRunnable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;
import java.util.List;
@@ -44,6 +44,7 @@ public class CompilerTestUtil {
private CompilerTestUtil() {
}
@TestOnly
public static void setupJavacForTests(Project project) {
CompilerConfigurationImpl compilerConfiguration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(project);
compilerConfiguration.setDefaultCompiler(compilerConfiguration.getJavacCompiler());
@@ -55,6 +56,7 @@ public class CompilerTestUtil {
public static void scanSourceRootsToRecompile(Project project) {
}
@TestOnly
public static void saveApplicationSettings() {
EdtTestUtil.runInEdtAndWait(new Runnable() {
@Override
@@ -65,6 +67,7 @@ public class CompilerTestUtil {
});
}
@TestOnly
public static void saveApplicationComponent(final Object appComponent) {
EdtTestUtil.runInEdtAndWait(new Runnable() {
@Override
@@ -79,6 +82,7 @@ public class CompilerTestUtil {
ServiceKt.getStateStore(ApplicationManager.getApplication()).saveApplicationComponent(appComponent);
}
@TestOnly
public static void enableExternalCompiler() {
final JavaAwareProjectJdkTableImpl table = JavaAwareProjectJdkTableImpl.getInstanceEx();
new WriteAction() {
@@ -89,30 +93,30 @@ public class CompilerTestUtil {
}.execute();
}
@TestOnly
public static void disableExternalCompiler(@NotNull final Project project) {
EdtTestUtil.runInEdtAndWait(new ThrowableRunnable<Throwable>() {
@Override
public void run() throws Throwable {
JavaAwareProjectJdkTableImpl table = JavaAwareProjectJdkTableImpl.getInstanceEx();
AccessToken token = WriteAction.start();
try {
Sdk internalJdk = table.getInternalJdk();
List<Module> modulesToRestore = new SmartList<Module>();
for (Module module : ModuleManager.getInstance(project).getModules()) {
Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
if (sdk != null && sdk.equals(internalJdk)) {
modulesToRestore.add(module);
final JavaAwareProjectJdkTableImpl table = JavaAwareProjectJdkTableImpl.getInstanceEx();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
Sdk internalJdk = table.getInternalJdk();
List<Module> modulesToRestore = new SmartList<Module>();
for (Module module : ModuleManager.getInstance(project).getModules()) {
Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
if (sdk != null && sdk.equals(internalJdk)) {
modulesToRestore.add(module);
}
}
table.removeJdk(internalJdk);
for (Module module : modulesToRestore) {
ModuleRootModificationUtil.setModuleSdk(module, internalJdk);
}
BuildManager.getInstance().clearState(project);
}
table.removeJdk(internalJdk);
for (Module module : modulesToRestore) {
ModuleRootModificationUtil.setModuleSdk(module, internalJdk);
}
BuildManager.getInstance().clearState(project);
}
finally {
token.finish();
}
});
}
});
}
@@ -61,7 +61,7 @@ public class ConvertFieldToThreadLocalIntention extends PsiElementBaseIntentionA
if (psiField.getTypeElement() == null) return false;
final PsiType fieldType = psiField.getType();
final PsiClass fieldTypeClass = PsiUtil.resolveClassInType(fieldType);
if (fieldType instanceof PsiPrimitiveType && fieldType != PsiType.VOID || fieldType instanceof PsiArrayType) return true;
if (fieldType instanceof PsiPrimitiveType && !PsiType.VOID.equals(fieldType) || fieldType instanceof PsiArrayType) return true;
return fieldTypeClass != null && !Comparing.strEqual(fieldTypeClass.getQualifiedName(), ThreadLocal.class.getName())
&& AllowedApiFilterExtension.isClassAllowed(ThreadLocal.class.getName(), element);
}
@@ -121,7 +121,7 @@ public class ConvertFieldToThreadLocalIntention extends PsiElementBaseIntentionA
if (initializer == null) {
final PsiType type = psiField.getType();
String initializerText = null;
if (type == PsiType.BOOLEAN) {
if (PsiType.BOOLEAN.equals(type)) {
initializerText = "false";
}
else if (type instanceof PsiPrimitiveType) {
@@ -39,19 +39,19 @@ public class AtomicConversionRule extends TypeConversionRule {
}
private static boolean isAtomicTypeMigration(PsiType from, PsiClassType to, PsiExpression context) {
if (from == PsiType.INT && to.getCanonicalText().equals(AtomicInteger.class.getName())) {
if (PsiType.INT.equals(from) && to.getCanonicalText().equals(AtomicInteger.class.getName())) {
return true;
}
if (from.equals(PsiType.INT.createArrayType()) && to.getCanonicalText().equals(AtomicIntegerArray.class.getName())) {
return true;
}
if (from == PsiType.LONG && to.getCanonicalText().equals(AtomicLong.class.getName())) {
if (PsiType.LONG.equals(from) && to.getCanonicalText().equals(AtomicLong.class.getName())) {
return true;
}
if (from.equals(PsiType.LONG.createArrayType()) && to.getCanonicalText().equals(AtomicLongArray.class.getName())) {
return true;
}
if (from == PsiType.BOOLEAN && to.getCanonicalText().equals(AtomicBoolean.class.getName())) {
if (PsiType.BOOLEAN.equals(from) && to.getCanonicalText().equals(AtomicBoolean.class.getName())) {
return true;
}
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(to);
@@ -39,7 +39,7 @@ public interface CodeDocumentationAwareCommenter extends Commenter {
* Returns the type of the block comment in the language,
* or null if the language does not support block comments.
* It is assumed that block comment prefix is not null when block comment type is not null.
* @return the line block comment type.
* @return the block comment type.
*/
@Nullable
IElementType getBlockCommentTokenType();
@@ -48,7 +48,7 @@ public interface CodeDocumentationAwareCommenter extends Commenter {
* Returns the type of the documentation comment token in the language,
* or null if the language does not support documentation comments.
* It is assumed that documentation comment prefix is not null when documentation comment type is not null.
* @return the line block comment type.
* @return the documentation comment type.
*/
@Nullable
IElementType getDocumentationCommentTokenType();
@@ -36,6 +36,7 @@ public abstract class ApplicationInfo {
public abstract String getThirdPartySoftwareURL();
public abstract String getJetbrainsTvUrl();
public abstract String getEvalLicenseUrl();
public abstract String getKeyConversionUrl();
public abstract Rectangle getAboutLogoRect();
public abstract boolean hasHelp();
@@ -64,7 +64,9 @@ public abstract class DumbService {
}
/**
* Executes the runnable immediately if not in dumb mode, or on AWT Event Dispatch thread when the dumb mode ends.
* Executes the runnable immediately if not in dumb mode, or on AWT Event Dispatch thread after the dumb mode ends.
* Note that it's not guaranteed that the dumb mode won't start again during this runnable execution, it should manage that situation explicitly
* (e.g. by starting a read action; it's still necessary to check isDumb inside the read action).
* @param runnable runnable to run
*/
public abstract void runWhenSmart(@NotNull Runnable runnable);
@@ -584,11 +584,18 @@ public class VfsUtilCore {
}
if (file == null) {
if (base == null) return StandardFileSystems.local().findFileByPath(uri);
if (!base.isDirectory()) base = base.getParent();
if (base == null) return StandardFileSystems.local().findFileByPath(uri);
file = VirtualFileManager.getInstance().findFileByUrl(base.getUrl() + "/" + uri);
if (file == null) return null;
if (base != null && !base.isDirectory()) {
base = base.getParent();
}
if (base == null) {
file = StandardFileSystems.local().findFileByPath(uri);
if (file == null) {
file = VirtualFileManager.getInstance().findFileByUrl(uri);
}
}
else {
file = VirtualFileManager.getInstance().findFileByUrl(base.getUrl() + "/" + uri);
}
}
return file;
@@ -96,7 +96,10 @@ public class CoreProjectScopeBuilder extends ProjectScopeBuilder {
@Override
public boolean contains(@NotNull VirtualFile file) {
return myFileIndexFacade.isInContent(file);
return myFileIndexFacade.isInContent(file) &&
// skip libraries that can be under our project content (IDEA-147584)
!myFileIndexFacade.isInLibraryClasses(file) &&
!myFileIndexFacade.isInLibrarySource(file);
}
@Override
@@ -110,6 +110,7 @@ public class ApplicationInfoImpl extends ApplicationInfoEx {
private String myThirdPartySoftwareUrl;
private String myJetbrainsTvUrl;
private String myEvalLicenseUrl = "https://www.jetbrains.com/company/useterms.html";
private String myKeyConversionUrl = "https://www.jetbrains.com/shop/eform/keys-exchange";
private Rectangle myAboutLogoRect;
@@ -187,6 +188,8 @@ public class ApplicationInfoImpl extends ApplicationInfoEx {
private static final String STEPS_PROVIDER = "provider";
private static final String ELEMENT_EVALUATION = "evaluation";
private static final String ATTRIBUTE_EVAL_LICENSE_URL = "license-url";
private static final String ELEMENT_LICENSING = "licensing";
private static final String ATTRIBUTE_KEY_CONVERSION_URL = "key-conversion-url";
private static final String ESSENTIAL_PLUGIN = "essential-plugin";
private static final String DEFAULT_PLUGINS_HOST = "http://plugins.jetbrains.com";
@@ -541,6 +544,11 @@ public class ApplicationInfoImpl extends ApplicationInfoEx {
return myEvalLicenseUrl;
}
@Override
public String getKeyConversionUrl() {
return myKeyConversionUrl;
}
@Override
public Rectangle getAboutLogoRect() {
return myAboutLogoRect;
@@ -836,7 +844,15 @@ public class ApplicationInfoImpl extends ApplicationInfoEx {
if (evaluationElement != null) {
final String url = evaluationElement.getAttributeValue(ATTRIBUTE_EVAL_LICENSE_URL);
if (url != null && !url.isEmpty()) {
myEvalLicenseUrl = url;
myEvalLicenseUrl = url.trim();
}
}
Element licensingElement = parentNode.getChild(ELEMENT_LICENSING);
if (licensingElement != null) {
final String url = licensingElement.getAttributeValue(ATTRIBUTE_KEY_CONVERSION_URL);
if (url != null && !url.isEmpty()) {
myKeyConversionUrl = url.trim();
}
}
@@ -35,9 +35,9 @@ public class EditorDocumentPriorities {
public static final int FOLD_MODEL = 60;
public static final int LOGICAL_POSITION_CACHE = 65;
public static final int EDITOR_TEXT_LAYOUT_CACHE = 70;
public static final int EDITOR_TEXT_WIDTH_CACHE = 75;
public static final int LEXER_EDITOR = 80;
public static final int SOFT_WRAP_MODEL = 100;
public static final int EDITOR_TEXT_WIDTH_CACHE = 110;
public static final int CARET_MODEL = 120;
public static final int SELECTION_MODEL = 140;
public static final int EDITOR_DOCUMENT_ADAPTER = 160;
@@ -22,10 +22,10 @@ import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.psi.PsiFile;
import com.intellij.psi.StubBuilder;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.IFileElementType;
import com.intellij.psi.tree.ILightStubFileElementType;
import com.intellij.psi.tree.IStubFileElementType;
import com.intellij.util.containers.Stack;
import gnu.trove.TIntStack;
import org.jetbrains.annotations.NotNull;
@@ -45,10 +45,10 @@ public class LightStubBuilder implements StubBuilder {
LOG.error("File is not of LanguageFileType: " + fileType + ", " + file);
return null;
}
Language language = ((LanguageFileType)fileType).getLanguage();
final IFileElementType contentType = LanguageParserDefinitions.INSTANCE.forLanguage(language).getFileNodeType();
if (!(contentType instanceof IStubFileElementType)) {
LOG.error("File is not of IStubFileElementType: " + contentType + ", " + file);
assert file instanceof PsiFileImpl;
final IFileElementType contentType = ((PsiFileImpl)file).getElementTypeForStubBuilder();
if (contentType == null) {
LOG.error("File is not of IStubFileElementType: " + file);
return null;
}
@@ -96,6 +96,14 @@ public final class DocumentUtil {
return document.getLineStartOffset(lineNumber);
}
public static int getLineEndOffset(int offset, @NotNull Document document) {
if (offset < 0 || offset > document.getTextLength()) {
return offset;
}
int lineNumber = document.getLineNumber(offset);
return document.getLineEndOffset(lineNumber);
}
@NotNull
public static TextRange getLineTextRange(@NotNull Document document, int line) {
return TextRange.create(document.getLineStartOffset(line), document.getLineEndOffset(line));
@@ -10,6 +10,7 @@ import com.intellij.openapi.externalSystem.model.project.LibraryPathType;
import com.intellij.openapi.externalSystem.model.project.ProjectData;
import com.intellij.openapi.externalSystem.service.project.ExternalLibraryPathTypeMapper;
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider;
import com.intellij.openapi.externalSystem.service.project.IdeUIModifiableModelsProvider;
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil;
@@ -22,7 +23,6 @@ import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.roots.RootPolicy;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
@@ -110,8 +110,7 @@ public class LibraryDataService extends AbstractProjectDataService<LibraryData,
@SuppressWarnings("MethodMayBeStatic")
public void registerPaths(@NotNull Map<OrderRootType, Collection<File>> libraryFiles,
@NotNull Library.ModifiableModel model,
@NotNull String libraryName)
{
@NotNull String libraryName) {
for (Map.Entry<OrderRootType, Collection<File>> entry : libraryFiles.entrySet()) {
for (File file : entry.getValue()) {
VirtualFile virtualFile = ExternalSystemUtil.refreshAndFindFileByIoFile(file);
@@ -167,6 +166,11 @@ public class LibraryDataService extends AbstractProjectDataService<LibraryData,
if (projectData == null) return;
// do not cleanup orphan project libraries if import runs from Project Structure Dialog
// since libraries order entries cannot be imported for modules in that case
// and hence #isOrphanProjectLibrary() method will work incorrectly
if (modelsProvider instanceof IdeUIModifiableModelsProvider) return;
final List<Library> orphanIdeLibraries = ContainerUtil.newSmartList();
final LibraryTable.ModifiableModel librariesModel = modelsProvider.getModifiableProjectLibrariesModel();
for (Library library : librariesModel.getLibraries()) {
@@ -33,6 +33,7 @@ import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.roots.ui.configuration.ModulesConfigurator;
import com.intellij.openapi.roots.ui.configuration.ModulesProvider;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
@@ -124,7 +125,7 @@ public abstract class AbstractExternalProjectImportBuilder<C extends AbstractImp
beforeCommit(externalProjectNode, project);
}
boolean isFromUI = model != null;
final boolean isFromUI = model != null;
final List<Module> modules = ContainerUtil.newSmartList();
final IdeModifiableModelsProvider modelsProvider = isFromUI ? new IdeUIModifiableModelsProvider(
@@ -163,46 +164,62 @@ public abstract class AbstractExternalProjectImportBuilder<C extends AbstractImp
}
}
myProjectDataManager.importData(externalProjectNode, project, modelsProvider, true);
myExternalProjectNode = null;
// resolve dependencies
final Runnable resolveDependenciesTask = new Runnable() {
@Override
public void run() {
ExternalSystemUtil.refreshProject(
project, myExternalSystemId, projectSettings.getExternalProjectPath(), false,
ProgressExecutionMode.IN_BACKGROUND_ASYNC);
}
};
if (!isFromUI) {
resolveDependenciesTask.run();
}
else {
// execute when current dialog is closed
ExternalSystemUtil.invokeLater(project, ModalityState.NON_MODAL, new Runnable() {
if (!project.isInitialized()) {
StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() {
@Override
public void run() {
final Module[] committedModules = ModuleManager.getInstance(project).getModules();
if (ContainerUtil.list(committedModules).containsAll(modules)) {
resolveDependenciesTask.run();
}
else {
ExternalSystemApiUtil.getLocalSettings(project, myExternalSystemId).forgetExternalProjects(
Collections.singleton(projectSettings.getExternalProjectPath()));
ExternalSystemApiUtil.getSettings(project, myExternalSystemId).unlinkExternalProject(
projectSettings.getExternalProjectPath());
ExternalProjectsManager.getInstance(project).forgetExternalProjectData(
myExternalSystemId, projectSettings.getExternalProjectPath());
}
finishImport(project, externalProjectNode, isFromUI, modules, modelsProvider, projectSettings);
}
});
}
else finishImport(project, externalProjectNode, isFromUI, modules, modelsProvider, projectSettings);
}
return modules;
}
protected void finishImport(final Project project,
DataNode<ProjectData> externalProjectNode,
boolean isFromUI,
final List<Module> modules,
IdeModifiableModelsProvider modelsProvider, final ExternalProjectSettings projectSettings) {
myProjectDataManager.importData(externalProjectNode, project, modelsProvider, true);
myExternalProjectNode = null;
// resolve dependencies
final Runnable resolveDependenciesTask = new Runnable() {
@Override
public void run() {
ExternalSystemUtil.refreshProject(
project, myExternalSystemId, projectSettings.getExternalProjectPath(), false,
ProgressExecutionMode.IN_BACKGROUND_ASYNC);
}
};
if (!isFromUI) {
resolveDependenciesTask.run();
}
else {
// execute when current dialog is closed
ExternalSystemUtil.invokeLater(project, ModalityState.NON_MODAL, new Runnable() {
@Override
public void run() {
final Module[] committedModules = ModuleManager.getInstance(project).getModules();
if (ContainerUtil.list(committedModules).containsAll(modules)) {
resolveDependenciesTask.run();
}
else {
ExternalSystemApiUtil.getLocalSettings(project, myExternalSystemId).forgetExternalProjects(
Collections.singleton(projectSettings.getExternalProjectPath()));
ExternalSystemApiUtil.getSettings(project, myExternalSystemId).unlinkExternalProject(
projectSettings.getExternalProjectPath());
ExternalProjectsManager.getInstance(project).forgetExternalProjectData(
myExternalSystemId, projectSettings.getExternalProjectPath());
}
}
});
}
}
@NotNull
private ExternalProjectSettings getCurrentExternalProjectSettings() {
ExternalProjectSettings result = myControl.getProjectSettings().clone();
@@ -32,10 +32,7 @@ import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.patterns.StandardPatterns;
@@ -93,7 +90,7 @@ public class CompletionLookupArranger extends LookupArranger {
myLocation = new CompletionLocation(parameters);
}
private MultiMap<CompletionSorterImpl, LookupElement> groupItemsBySorter(List<LookupElement> source) {
private MultiMap<CompletionSorterImpl, LookupElement> groupItemsBySorter(Iterable<LookupElement> source) {
MultiMap<CompletionSorterImpl, LookupElement> inputBySorter = MultiMap.createLinked();
for (LookupElement element : source) {
inputBySorter.putValue(obtainSorter(element), element);
@@ -106,28 +103,30 @@ public class CompletionLookupArranger extends LookupArranger {
return myProcess.getSorter(element);
}
@NotNull
@Override
public Map<LookupElement, StringBuilder> getRelevanceStrings() {
final LinkedHashMap<LookupElement,StringBuilder> map = new LinkedHashMap<LookupElement, StringBuilder>();
for (LookupElement item : myItems) {
map.put(item, new StringBuilder());
}
final MultiMap<CompletionSorterImpl, LookupElement> inputBySorter = groupItemsBySorter(new ArrayList<LookupElement>(map.keySet()));
if (inputBySorter.size() > 1) {
for (LookupElement element : map.keySet()) {
map.get(element).append(obtainSorter(element)).append(": ");
}
}
public Map<LookupElement, List<Pair<String, Object>>> getRelevanceObjects(@NotNull Iterable<LookupElement> items,
boolean hideSingleValued) {
final LinkedHashMap<LookupElement, List<Pair<String, Object>>> map = ContainerUtil.newLinkedHashMap();
final MultiMap<CompletionSorterImpl, LookupElement> inputBySorter = groupItemsBySorter(items);
int sorterNumber = 0;
for (CompletionSorterImpl sorter : inputBySorter.keySet()) {
final LinkedHashMap<LookupElement, StringBuilder> subMap = new LinkedHashMap<LookupElement, StringBuilder>();
for (LookupElement element : inputBySorter.get(sorter)) {
subMap.put(element, map.get(element));
sorterNumber++;
Collection<LookupElement> thisSorterItems = inputBySorter.get(sorter);
for (LookupElement element : thisSorterItems) {
map.put(element, ContainerUtil.newArrayList(new Pair<String, Object>("frozen", myFrozenItems.contains(element)),
new Pair<String, Object>("sorter", sorterNumber)));
}
ProcessingContext context = createContext(false);
Classifier<LookupElement> classifier = myClassifiers.get(sorter);
if (classifier != null) {
classifier.describeItems(subMap, createContext(false));
while (classifier != null) {
List<Pair<LookupElement, Object>> pairs = classifier.getSortingWeights(thisSorterItems, context);
if (!hideSingleValued || !haveSameWeights(pairs)) {
for (Pair<LookupElement, Object> pair : pairs) {
map.get(pair.first).add(Pair.create(classifier.getPresentableName(), pair.second));
}
}
classifier = classifier.getNext();
}
}
@@ -135,6 +134,18 @@ public class CompletionLookupArranger extends LookupArranger {
}
private static boolean haveSameWeights(List<Pair<LookupElement, Object>> pairs) {
if (pairs.isEmpty()) return true;
for (int i = 1; i < pairs.size(); i++) {
if (!Comparing.equal(pairs.get(i).second, pairs.get(0).second)) {
return false;
}
}
return true;
}
@Override
public void addElement(Lookup lookup, LookupElement element, LookupElementPresentation presentation) {
StatisticsWeigher.clearBaseStatisticsInfo(element);
@@ -570,12 +581,19 @@ public class CompletionLookupArranger extends LookupArranger {
private final LookupImpl myLookup;
private AlphaClassifier(LookupImpl lookup) {
super(null);
super(null, "alpha");
myLookup = lookup;
}
@NotNull
@Override
public Iterable<LookupElement> classify(Iterable<LookupElement> source, ProcessingContext context) {
public List<Pair<LookupElement, Object>> getSortingWeights(@NotNull Iterable<LookupElement> items, @NotNull ProcessingContext context) {
return Collections.emptyList();
}
@NotNull
@Override
public Iterable<LookupElement> classify(@NotNull Iterable<LookupElement> source, @NotNull ProcessingContext context) {
return sortByPresentation(source, myLookup);
}
@@ -0,0 +1,51 @@
/*
* Copyright 2000-2015 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.completion;
import com.intellij.psi.statistics.StatisticsInfo;
import org.jetbrains.annotations.NotNull;
/**
* @author peter
*/
public class StatisticsComparable implements Comparable<StatisticsComparable> {
private final int myScalar;
private final StatisticsInfo myStatisticsInfo;
public StatisticsComparable(int scalar, @NotNull StatisticsInfo statisticsInfo) {
myScalar = scalar;
myStatisticsInfo = statisticsInfo;
}
public int getScalar() {
return myScalar;
}
@NotNull
public StatisticsInfo getStatisticsInfo() {
return myStatisticsInfo;
}
@Override
public String toString() {
return String.valueOf(myScalar);
}
@Override
public int compareTo(StatisticsComparable o) {
return myScalar < o.myScalar ? -1 : myScalar == o.myScalar ? 0 : 1;
}
}
@@ -22,8 +22,10 @@ import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.statistics.StatisticsInfo;
import com.intellij.psi.statistics.StatisticsManager;
import com.intellij.util.Function;
import com.intellij.util.ProcessingContext;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
@@ -49,19 +51,19 @@ public class StatisticsWeigher extends CompletionWeigher {
public static class LookupStatisticsWeigher extends Classifier<LookupElement> {
private final CompletionLocation myLocation;
private final Map<LookupElement, Integer> myWeights = new IdentityHashMap<LookupElement, Integer>();
@SuppressWarnings("unchecked") private final Set<LookupElement> myNoStats = new THashSet<LookupElement>(TObjectHashingStrategy.IDENTITY);
private final Map<LookupElement, StatisticsComparable> myWeights = ContainerUtil.newIdentityHashMap();
private final Set<LookupElement> myNoStats = ContainerUtil.newIdentityTroveSet();
private int myPrefixChanges;
public LookupStatisticsWeigher(CompletionLocation location, Classifier<LookupElement> next) {
super(next);
super(next, "stats");
myLocation = location;
}
@Override
public void addElement(LookupElement element, ProcessingContext context) {
public void addElement(@NotNull LookupElement element, @NotNull ProcessingContext context) {
StatisticsInfo baseInfo = getBaseStatisticsInfo(element, myLocation);
myWeights.put(element, weigh(element, baseInfo, context.get(CompletionLookupArranger.WEIGHING_CONTEXT)));
myWeights.put(element, new StatisticsComparable(weigh(element, baseInfo, context.get(CompletionLookupArranger.WEIGHING_CONTEXT)), baseInfo));
if (baseInfo == StatisticsInfo.EMPTY) {
myNoStats.add(element);
}
@@ -76,8 +78,9 @@ public class StatisticsWeigher extends CompletionWeigher {
}
}
@NotNull
@Override
public Iterable<LookupElement> classify(Iterable<LookupElement> source, final ProcessingContext context) {
public Iterable<LookupElement> classify(@NotNull Iterable<LookupElement> source, @NotNull final ProcessingContext context) {
checkPrefixChanged(context);
final Collection<List<LookupElement>> byWeight = buildMapByWeight(source, context).descendingMap().values();
@@ -122,7 +125,7 @@ public class StatisticsWeigher extends CompletionWeigher {
private TreeMap<Integer, List<LookupElement>> buildMapByWeight(Iterable<LookupElement> source, ProcessingContext context) {
TreeMap<Integer, List<LookupElement>> map = new TreeMap<Integer, List<LookupElement>>();
for (LookupElement element : source) {
final int weight = getWeight(element, context.get(CompletionLookupArranger.WEIGHING_CONTEXT));
final int weight = getWeight(element, context.get(CompletionLookupArranger.WEIGHING_CONTEXT)).getScalar();
List<LookupElement> list = map.get(weight);
if (list == null) {
map.put(weight, list = new SmartList<LookupElement>());
@@ -132,10 +135,11 @@ public class StatisticsWeigher extends CompletionWeigher {
return map;
}
private int getWeight(LookupElement t, WeighingContext context) {
Integer w = myWeights.get(t);
private StatisticsComparable getWeight(LookupElement t, WeighingContext context) {
StatisticsComparable w = myWeights.get(t);
if (w == null) {
myWeights.put(t, w = weigh(t, getBaseStatisticsInfo(t, myLocation), context));
StatisticsInfo info = getBaseStatisticsInfo(t, myLocation);
myWeights.put(t, w = new StatisticsComparable(weigh(t, info, context), info));
}
return w;
}
@@ -151,21 +155,20 @@ public class StatisticsWeigher extends CompletionWeigher {
return minRecency == Integer.MAX_VALUE ? useCount : 100 - minRecency;
}
@NotNull
@Override
public void describeItems(LinkedHashMap<LookupElement, StringBuilder> map, ProcessingContext context) {
public List<Pair<LookupElement, Object>> getSortingWeights(@NotNull Iterable<LookupElement> items, @NotNull final ProcessingContext context) {
checkPrefixChanged(context);
for (LookupElement element : map.keySet()) {
StringBuilder builder = map.get(element);
if (builder.length() > 0) {
builder.append(", ");
return ContainerUtil.map(items, new Function<LookupElement, Pair<LookupElement, Object>>() {
@Override
public Pair<LookupElement, Object> fun(LookupElement lookupElement) {
return new Pair<LookupElement, Object>(lookupElement, getWeight(lookupElement, context.get(CompletionLookupArranger.WEIGHING_CONTEXT)));
}
builder.append("stats=").append(getWeight(element, context.get(CompletionLookupArranger.WEIGHING_CONTEXT)));
}
super.describeItems(map, context);
});
}
@Override
public void removeElement(LookupElement element, ProcessingContext context) {
public void removeElement(@NotNull LookupElement element, @NotNull ProcessingContext context) {
myWeights.remove(element);
myNoStats.remove(element);
super.removeElement(element, context);
@@ -19,6 +19,8 @@ import com.intellij.codeInsight.completion.CompletionUtil;
import com.intellij.codeInsight.lookup.Classifier;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Pair;
import com.intellij.util.Function;
import com.intellij.util.ProcessingContext;
import com.intellij.util.containers.*;
import gnu.trove.THashSet;
@@ -39,20 +41,18 @@ public class LiftShorterItemsClassifier extends Classifier<LookupElement> {
private final MultiMap<String, LookupElement> myElements = createMultiMap(false);
private final MultiMap<LookupElement, LookupElement> myToLift = createMultiMap(true);
private final MultiMap<LookupElement, LookupElement> myReversedToLift = createMultiMap(true);
private final String myName;
private final LiftingCondition myCondition;
private final boolean myLiftBefore;
private int myCount = 0;
public LiftShorterItemsClassifier(String name, Classifier<LookupElement> next, LiftingCondition condition, boolean liftBefore) {
super(next);
myName = name;
super(next, name);
myCondition = condition;
myLiftBefore = liftBefore;
}
@Override
public void addElement(LookupElement added, ProcessingContext context) {
public void addElement(@NotNull LookupElement added, @NotNull ProcessingContext context) {
myCount++;
for (String string : CompletionUtil.iterateLookupStrings(added)) {
@@ -96,8 +96,9 @@ public class LiftShorterItemsClassifier extends Classifier<LookupElement> {
}
}
@NotNull
@Override
public Iterable<LookupElement> classify(Iterable<LookupElement> source, ProcessingContext context) {
public Iterable<LookupElement> classify(@NotNull Iterable<LookupElement> source, @NotNull ProcessingContext context) {
return liftShorterElements(source, null, context);
}
@@ -113,25 +114,21 @@ public class LiftShorterItemsClassifier extends Classifier<LookupElement> {
return new LiftingIterable(srcSet, context, source, lifted);
}
@NotNull
@Override
public void describeItems(LinkedHashMap<LookupElement, StringBuilder> map, ProcessingContext context) {
public List<Pair<LookupElement, Object>> getSortingWeights(@NotNull Iterable<LookupElement> items, @NotNull ProcessingContext context) {
final THashSet<LookupElement> lifted = newIdentityTroveSet();
liftShorterElements(new ArrayList<LookupElement>(map.keySet()), lifted, context);
if (!lifted.isEmpty()) {
for (LookupElement element : map.keySet()) {
final StringBuilder builder = map.get(element);
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(myName).append("=").append(lifted.contains(element));
liftShorterElements(ContainerUtil.newArrayList(items), lifted, context);
return ContainerUtil.map(items, new Function<LookupElement, Pair<LookupElement, Object>>() {
@Override
public Pair<LookupElement, Object> fun(LookupElement element) {
return new Pair<LookupElement, Object>(element, lifted.contains(element));
}
}
super.describeItems(map, context);
});
}
@Override
public void removeElement(LookupElement element, ProcessingContext context) {
public void removeElement(@NotNull LookupElement element, @NotNull ProcessingContext context) {
for (String s : CompletionUtil.iterateLookupStrings(element)) {
myElements.remove(s, element);
if (myElements.get(s).isEmpty()) {
@@ -27,6 +27,7 @@ import com.intellij.codeInsight.daemon.ReferenceImporter;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.intention.impl.FileLevelIntentionComponent;
import com.intellij.codeInsight.intention.impl.IntentionHintComponent;
import com.intellij.diagnostic.ThreadDumper;
import com.intellij.ide.PowerSaveMode;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.Disposable;
@@ -343,7 +344,8 @@ public class DaemonCodeAnalyzerImpl extends DaemonCodeAnalyzerEx implements Pers
final DaemonProgressIndicator progress = createUpdateProgress();
myPassExecutorService.submitPasses(map, progress);
try {
while (progress.isRunning()) {
long start = System.currentTimeMillis();
while (progress.isRunning() && System.currentTimeMillis() < start + 5*60*1000) {
wrap(new ThrowableRunnable() {
@Override
public void run() throws Throwable {
@@ -358,6 +360,9 @@ public class DaemonCodeAnalyzerImpl extends DaemonCodeAnalyzerEx implements Pers
}
});
}
if (progress.isRunning()) {
throw new RuntimeException("Highlighting still running after "+(System.currentTimeMillis()-start)/1000+" seconds.\n"+ ThreadDumper.dumpThreadsToString());
}
final HighlightingSessionImpl session =
(HighlightingSessionImpl)HighlightingSessionImpl.getOrCreateHighlightingSession(file, textEditors.get(0).getEditor(), progress, null);

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