Merge remote-tracking branch 'origin/master'

This commit is contained in:
irengrig
2015-08-31 19:31:21 +02:00
412 changed files with 7803 additions and 4675 deletions
@@ -15,9 +15,9 @@
*/
package org.intellij.lang.regexp.psi.impl;
import com.intellij.codeInsight.lookup.LookupValueFactory;
import com.intellij.codeInsight.lookup.LookupValueWithPriority;
import com.intellij.codeInsight.lookup.LookupValueWithUIHint;
import com.intellij.codeInsight.completion.PrioritizedLookupElement;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
@@ -25,6 +25,7 @@ import com.intellij.psi.PsiReference;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.PlatformIcons;
import com.intellij.util.containers.ContainerUtil;
import org.intellij.lang.regexp.RegExpLanguageHosts;
import org.intellij.lang.regexp.RegExpTT;
import org.intellij.lang.regexp.psi.RegExpElementVisitor;
@@ -32,10 +33,10 @@ import org.intellij.lang.regexp.psi.RegExpProperty;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class RegExpPropertyImpl extends RegExpElementImpl implements RegExpProperty {
@@ -100,67 +101,40 @@ public class RegExpPropertyImpl extends RegExpElementImpl implements RegExpPrope
return false;
}
@NotNull
public Object[] getVariants() {
final ASTNode categoryNode = getCategoryNode();
if (categoryNode != null && categoryNode.getText().startsWith("In") && !categoryNode.getText().startsWith("Intelli")) {
return UNICODE_BLOCKS;
} else {
final String[][] knownProperties = RegExpLanguageHosts.getInstance().getAllKnownProperties(getElement());
final Object[] objects = new Object[knownProperties.length];
for (int i = 0; i < objects.length; i++) {
final String[] prop = knownProperties[i];
objects[i] = new MyLookupValue(prop);
}
return objects;
}
}
public boolean isSoft() {
return true;
}
private class MyLookupValue extends LookupValueFactory.LookupValueWithIcon implements LookupValueWithPriority, LookupValueWithUIHint {
private final String[] myProp;
public MyLookupValue(String[] prop) {
super(prop[0], PlatformIcons.PROPERTY_ICON);
myProp = prop;
}
public String getPresentation() {
final ASTNode categoryNode = getCategoryNode();
if (categoryNode != null) {
if (categoryNode.getText().startsWith("Is")) {
return "Is" + super.getPresentation();
}
}
return super.getPresentation();
}
public int getPriority() {
final String name = myProp[0];
if (name.equals("all")) return HIGH + 1;
if (name.startsWith("java")) return HIGHER;
return name.length() > 2 ? HIGH : NORMAL;
}
public String getTypeHint() {
return myProp.length > 1 ? myProp[1] : ("Character.is" + myProp[0].substring("java".length()) + "()");
}
@Nullable
public Color getColorHint() {
return null;
}
public boolean isBold() {
return false;
}
@NotNull
public Object[] getVariants() {
final ASTNode categoryNode = getCategoryNode();
if (categoryNode != null && categoryNode.getText().startsWith("In") && !categoryNode.getText().startsWith("Intelli")) {
return UNICODE_BLOCKS;
}
else {
boolean startsWithIs = categoryNode != null && categoryNode.getText().startsWith("Is");
Collection<LookupElement> result = ContainerUtil.newArrayList();
for (String[] properties : RegExpLanguageHosts.getInstance().getAllKnownProperties(getElement())) {
String name = ArrayUtil.getFirstElement(properties);
if (name != null) {
String typeText = properties.length > 1 ? properties[1] : ("Character.is" + name.substring("java".length()) + "()");
result.add(PrioritizedLookupElement.withPriority(LookupElementBuilder.create(name)
.withPresentableText(startsWithIs ? "Is" + name : name)
.withIcon(PlatformIcons.PROPERTY_ICON)
.withTypeText(typeText), getPriority(name)));
}
}
return ArrayUtil.toObjectArray(result);
}
}
private int getPriority(@NotNull String propertyName) {
if (propertyName.equals("all")) return 3;
if (propertyName.startsWith("java")) return 1;
if (propertyName.length() > 2) return 2;
return 0;
}
public boolean isSoft() {
return true;
}
}
private static final String[] UNICODE_BLOCKS;
static {
+8 -3
View File
@@ -107,13 +107,18 @@ else
fi
fi
if [ -z "$JDK" ]; then
JAVA_BIN="$JDK/bin/java"
if [ ! -x "$JAVA_BIN" ]; then
JAVA_BIN="$JDK/jre/bin/java"
fi
if [ -z "$JDK" ] || [ ! -x "$JAVA_BIN" ]; then
message "No JDK found. Please validate either @@product_uc@@_JDK, JDK_HOME or JAVA_HOME environment variable points to valid JDK installation."
exit 1
fi
VERSION_LOG=`"$MKTEMP" -t java.version.log.XXXXXX`
"$JDK/jre/bin/java" -version 2> "$VERSION_LOG"
"$JAVA_BIN" -version 2> "$VERSION_LOG"
"$GREP" "64-Bit|x86_64|amd64" "$VERSION_LOG" > /dev/null
BITS=$?
"$RM" -f "$VERSION_LOG"
@@ -175,7 +180,7 @@ fi
# ---------------------------------------------------------------------
# Run the IDE.
# ---------------------------------------------------------------------
LD_LIBRARY_PATH="$IDE_BIN_HOME:$LD_LIBRARY_PATH" "$JDK/jre/bin/java" \
LD_LIBRARY_PATH="$IDE_BIN_HOME:$LD_LIBRARY_PATH" "$JAVA_BIN" \
$AGENT \
"-Xbootclasspath/a:$IDE_HOME/lib/boot.jar" \
-classpath "$CLASSPATH" \
-1
View File
@@ -41,7 +41,6 @@ if (System.getProperty("os.name").toLowerCase().startsWith("mac")) {
if (vendor != null && vendor.toLowerCase().contains("apple")) {
args << "-d32"
}
args << "-Dfile.encoding=UTF-8"
};
args << "-Djna.nosys=true"
+1
View File
@@ -338,6 +338,7 @@ binding.setVariable("commonJvmArgsForTests", {
return [
"-ea",
"-Dfile.encoding=UTF-8",
"-Dio.netty.leakDetectionLevel=PARANOID",
"-server",
"-Xbootclasspath/p:${projectBuilder.moduleOutput(findModule("boot"))}",
@@ -913,7 +913,7 @@ public class BuildManager implements Disposable {
int sdkMinorVersion = 0;
JavaSdkVersion sdkVersion = null;
final Set<Sdk> candidates = new HashSet<Sdk>();
final Set<Sdk> candidates = new LinkedHashSet<Sdk>();
final Sdk defaultSdk = ProjectRootManager.getInstance(project).getProjectSdk();
if (defaultSdk != null && defaultSdk.getSdkType() instanceof JavaSdkType) {
candidates.add(defaultSdk);
@@ -126,6 +126,24 @@ public class JavaSmartStepIntoHandler extends JvmSmartStepIntoHandler {
}
}
@Override
public void visitField(PsiField field) {
TextRange range = field.getTextRange();
if (lineRange.intersects(range)) {
//textRange.set(textRange.get().union(range));
super.visitField(field);
}
}
@Override
public void visitMethod(PsiMethod method) {
TextRange range = method.getTextRange();
if (lineRange.intersects(range)) {
//textRange.set(textRange.get().union(range));
super.visitMethod(method);
}
}
@Override
public void visitStatement(PsiStatement statement) {
TextRange range = statement.getTextRange();
@@ -46,6 +46,7 @@ import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator;
import com.intellij.xdebugger.evaluation.XInstanceEvaluator;
import com.intellij.xdebugger.frame.*;
import com.intellij.xdebugger.frame.presentation.XErrorValuePresentation;
import com.intellij.xdebugger.frame.presentation.XValuePresentation;
import com.intellij.xdebugger.impl.breakpoints.XExpressionImpl;
import com.intellij.xdebugger.impl.evaluate.XValueCompactPresentation;
@@ -134,7 +135,7 @@ public class JavaValue extends XNamedValue implements NodeDescriptorProvider, XV
@Override
protected void commandCancelled() {
node.setPresentation(null, new JavaValuePresentation("", null, DebuggerBundle.message("error.context.has.changed"), myValueDescriptor), false);
node.setPresentation(null, new XErrorValuePresentation(DebuggerBundle.message("error.context.has.changed")), false);
}
@Override
@@ -484,6 +484,13 @@ public class EvaluatorBuilderImpl implements EvaluatorBuilder {
return lType instanceof PsiPrimitiveType && rType instanceof PsiClassType ||
lType instanceof PsiClassType && rType instanceof PsiPrimitiveType;
}
// concat with a String
if (opCode == JavaTokenType.PLUS) {
if ((lType instanceof PsiClassType && lType.equalsToText(CommonClassNames.JAVA_LANG_STRING)) ||
(rType instanceof PsiClassType && rType.equalsToText(CommonClassNames.JAVA_LANG_STRING))){
return false;
}
}
// all other operations at least one should be of class type
return lType instanceof PsiClassType || rType instanceof PsiClassType;
}
@@ -19,6 +19,7 @@ import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.openapi.util.Couple;
import com.intellij.psi.CommonClassNames;
import com.intellij.util.containers.HashMap;
import com.sun.jdi.ClassType;
import com.sun.jdi.Method;
@@ -39,14 +40,14 @@ public class UnBoxingEvaluator implements Evaluator{
private final Evaluator myOperand;
private static final Map<String, Couple<String>> TYPES_TO_CONVERSION_METHOD_MAP = new HashMap<String, Couple<String>>();
static {
TYPES_TO_CONVERSION_METHOD_MAP.put("java.lang.Boolean", Couple.of("booleanValue", "()Z"));
TYPES_TO_CONVERSION_METHOD_MAP.put("java.lang.Byte", Couple.of("byteValue", "()B"));
TYPES_TO_CONVERSION_METHOD_MAP.put("java.lang.Character", Couple.of("charValue", "()C"));
TYPES_TO_CONVERSION_METHOD_MAP.put("java.lang.Short", Couple.of("shortValue", "()S"));
TYPES_TO_CONVERSION_METHOD_MAP.put("java.lang.Integer", Couple.of("intValue", "()I"));
TYPES_TO_CONVERSION_METHOD_MAP.put("java.lang.Long", Couple.of("longValue", "()J"));
TYPES_TO_CONVERSION_METHOD_MAP.put("java.lang.Float", Couple.of("floatValue", "()F"));
TYPES_TO_CONVERSION_METHOD_MAP.put("java.lang.Double", Couple.of("doubleValue", "()D"));
TYPES_TO_CONVERSION_METHOD_MAP.put(CommonClassNames.JAVA_LANG_BOOLEAN, Couple.of("booleanValue", "()Z"));
TYPES_TO_CONVERSION_METHOD_MAP.put(CommonClassNames.JAVA_LANG_BYTE, Couple.of("byteValue", "()B"));
TYPES_TO_CONVERSION_METHOD_MAP.put(CommonClassNames.JAVA_LANG_CHARACTER, Couple.of("charValue", "()C"));
TYPES_TO_CONVERSION_METHOD_MAP.put(CommonClassNames.JAVA_LANG_SHORT, Couple.of("shortValue", "()S"));
TYPES_TO_CONVERSION_METHOD_MAP.put(CommonClassNames.JAVA_LANG_INTEGER, Couple.of("intValue", "()I"));
TYPES_TO_CONVERSION_METHOD_MAP.put(CommonClassNames.JAVA_LANG_LONG, Couple.of("longValue", "()J"));
TYPES_TO_CONVERSION_METHOD_MAP.put(CommonClassNames.JAVA_LANG_FLOAT, Couple.of("floatValue", "()F"));
TYPES_TO_CONVERSION_METHOD_MAP.put(CommonClassNames.JAVA_LANG_DOUBLE, Couple.of("doubleValue", "()D"));
}
public static boolean isTypeUnboxable(String typeName) {
@@ -34,8 +34,8 @@ import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementFactory;
import com.intellij.psi.PsiExpression;
import com.intellij.util.IncorrectOperationException;
import com.intellij.xdebugger.settings.XDebuggerSettingsManager;
import com.sun.jdi.*;
@@ -229,7 +229,7 @@ public class ClassRenderer extends NodeRendererImpl{
}
@Override
public PsiExpression getChildValueExpression(DebuggerTreeNode node, DebuggerContext context) throws EvaluateException {
public PsiElement getChildValueExpression(DebuggerTreeNode node, DebuggerContext context) throws EvaluateException {
FieldDescriptor fieldDescriptor = (FieldDescriptor)node.getDescriptor();
PsiElementFactory elementFactory = JavaPsiFacade.getInstance(node.getProject()).getElementFactory();
@@ -95,7 +95,8 @@ public class HighlightControlFlowUtil {
// do not compute constant expressions for if() statement condition
// see JLS 14.20 Unreachable Statements
try {
final ControlFlow controlFlow = getControlFlowNoConstantEvaluate(codeBlock);
AllVariablesControlFlowPolicy policy = AllVariablesControlFlowPolicy.getInstance();
final ControlFlow controlFlow = ControlFlowFactory.getInstance(codeBlock.getProject()).getControlFlow(codeBlock, policy, false, false);
final PsiElement unreachableStatement = ControlFlowUtil.getUnreachableStatement(controlFlow);
if (unreachableStatement != null) {
String description = JavaErrorMessages.message("unreachable.statement");
@@ -182,7 +182,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
highlight.run();
progress.checkCanceled();
HighlightingSession highlightingSession = HighlightingSessionImpl.getHighlightingSession(file, progress);
PostHighlightingVisitor highlightingVisitor = new PostHighlightingVisitor(file, document, refCountHolder, highlightingSession);
PostHighlightingVisitor highlightingVisitor = new PostHighlightingVisitor(file, document, refCountHolder);
highlightingVisitor.collectHighlights(file, holder, progress);
}
});
@@ -73,7 +73,6 @@ class PostHighlightingVisitor {
@NotNull private final Project myProject;
private final PsiFile myFile;
@NotNull private final Document myDocument;
@NotNull private final HighlightingSession myHighlightingSession;
private boolean myHasRedundantImports;
private int myCurrentEntryIndex;
@@ -94,19 +93,19 @@ class PostHighlightingVisitor {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
if (myProject.isDisposed() || !myFile.isValid()) return;
if (myProject.isDisposed() || !myFile.isValid() || !myFile.isWritable()) return;
IntentionAction optimizeImportsFix = QuickFixFactory.getInstance().createOptimizeImportsFix(true);
if (optimizeImportsFix.isAvailable(myProject, null, myFile) && myFile.isWritable()) {
if (optimizeImportsFix.isAvailable(myProject, null, myFile)) {
optimizeImportsFix.invoke(myProject, null, myFile);
}
}
});
}
};
Disposer.register(myHighlightingSession, invokeFixLater);
Disposer.register((DaemonProgressIndicator)progress, invokeFixLater);
if (progress.isCanceled()) {
Disposer.dispose(invokeFixLater);
Disposer.dispose(myHighlightingSession);
Disposer.dispose((DaemonProgressIndicator)progress);
progress.checkCanceled();
}
}
@@ -114,9 +113,7 @@ class PostHighlightingVisitor {
PostHighlightingVisitor(@NotNull PsiFile file,
@NotNull Document document,
@NotNull RefCountHolder refCountHolder,
@NotNull HighlightingSession highlightingSession) throws ProcessCanceledException {
myHighlightingSession = highlightingSession;
@NotNull RefCountHolder refCountHolder) throws ProcessCanceledException {
myProject = file.getProject();
myFile = file;
myDocument = document;
@@ -211,7 +211,7 @@ public class AnonymousCanBeLambdaInspection extends BaseJavaBatchLocalInspection
if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return null;
final PsiAnonymousClass anonymousClass = ((PsiNewExpression)element).getAnonymousClass();
LOG.assertTrue(anonymousClass != null);
if (anonymousClass == null) return null;
ChangeContextUtil.encodeContextInfo(anonymousClass, true);
final PsiElement lambdaContext = anonymousClass.getParent().getParent();
@@ -229,10 +229,10 @@ public class AnonymousCanBeLambdaInspection extends BaseJavaBatchLocalInspection
} else {
method = anonymousClass.getMethods()[0];
}
LOG.assertTrue(method != null);
if (method == null) return null;
final PsiCodeBlock body = method.getBody();
LOG.assertTrue(body != null);
if (body == null) return null;
final ForbiddenRefsChecker checker = new ForbiddenRefsChecker(method, anonymousClass);
body.accept(checker);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 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.
@@ -29,7 +29,6 @@ import com.intellij.openapi.extensions.impl.ExtensionPointImpl;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizableStringList;
import com.intellij.profile.codeInspection.InspectionProfileManager;
import com.intellij.psi.PsiDocCommentOwner;
@@ -140,7 +139,7 @@ public abstract class EntryPointsManagerBase extends EntryPointsManager implemen
try {
ADDITIONAL_ANNOTATIONS.readExternal(element);
}
catch (InvalidDataException ignored) {
catch (Throwable ignored) {
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 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.
@@ -51,7 +51,7 @@ public class JavaFindUsagesHelper {
private static final Logger LOG = Logger.getInstance("#com.intellij.find.findUsages.JavaFindUsagesHelper");
@NotNull
static Set<String> getElementNames(@NotNull final PsiElement element) {
public static Set<String> getElementNames(@NotNull final PsiElement element) {
if (element instanceof PsiDirectory) { // normalize a directory to a corresponding package
PsiPackage aPackage = ApplicationManager.getApplication().runReadAction(new Computable<PsiPackage>() {
@Override
@@ -90,6 +90,10 @@ public class FindSuperElementsHelper {
if (superInterface == null) {
continue;
}
if (containingClass.isInheritor(superInterface, true)) {
// if containingClass implements the superInterface then it's not a sibling inheritance but a pretty boring the usual one
continue;
}
// calculate substitutor of containingClass --> inheritor
PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(containingClass, inheritor, PsiSubstitutor.EMPTY);
@@ -100,10 +104,11 @@ public class FindSuperElementsHelper {
final MethodSignature derivedSignature = method.getSignature(PsiSubstitutor.EMPTY);
boolean isOverridden = MethodSignatureUtil.isSubsignature(superSignature, derivedSignature);
if (isOverridden) {
result[0] = superMethod;
return false;
if (!isOverridden) {
continue;
}
result[0] = superMethod;
return false;
}
}
return true;
@@ -16,7 +16,10 @@
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.guess.GuessManager;
import com.intellij.codeInsight.lookup.*;
import com.intellij.codeInsight.lookup.ExpressionLookupItem;
import com.intellij.codeInsight.lookup.KeywordLookupItem;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.VariableLookupItem;
import com.intellij.codeInsight.template.SmartCompletionContextType;
import com.intellij.codeInsight.template.impl.TemplateImpl;
import com.intellij.codeInsight.template.impl.TemplateSettings;
@@ -28,7 +31,6 @@ import com.intellij.psi.scope.BaseScopeProcessor;
import com.intellij.psi.scope.util.PsiScopesUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.Consumer;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -44,13 +46,7 @@ public class BasicExpressionCompletionContributor {
}
public static LookupElement createKeywordLookupItem(final PsiElement element, final String s) {
try {
final PsiKeyword keyword = JavaPsiFacade.getInstance(element.getProject()).getElementFactory().createKeyword(s, element);
return new KeywordLookupItem(keyword, element).setAutoCompletionPolicy(AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE);
}
catch (IncorrectOperationException e) {
throw new RuntimeException(e);
}
return new KeywordLookupItem(JavaPsiFacade.getElementFactory(element.getProject()).createKeyword(s, element), element);
}
public static void fillCompletionVariants(JavaSmartCompletionParameters parameters,
@@ -178,7 +178,7 @@ public class ConstructorInsertHandler implements InsertHandler<LookupElementDeco
if (newExpr != null) {
for (ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes(newExpr, true)) {
PsiType expected = info.getDefaultType();
if (expected.isAssignableFrom(delegate.getPsiType())) {
if (expected.isAssignableFrom(delegate.getType())) {
if (expected instanceof PsiClassType && ((PsiClassType)expected).isRaw()) {
return true;
}
@@ -108,8 +108,15 @@ class JavaClassNameInsertHandler implements InsertHandler<JavaPsiClassReferenceE
fillTypeArgs |= psiClass.hasTypeParameters() && PsiUtil.getLanguageLevel(file).isAtLeast(LanguageLevel.JDK_1_5);
}
}
else if (insertingAnnotationWithParameters(context, item)) {
JavaCompletionUtil.insertParentheses(context, item, false, true);
else if (insertingAnnotation(context, item)) {
if (shouldHaveAnnotationParameters(psiClass)) {
JavaCompletionUtil.insertParentheses(context, item, false, true);
}
CharSequence text = context.getDocument().getCharsSequence();
int tail = context.getTailOffset();
if (text.length() > tail && Character.isLetter(text.charAt(tail))) {
context.getDocument().insertString(tail, " ");
}
}
if (fillTypeArgs && context.getCompletionChar() != '(') {
@@ -164,15 +171,12 @@ class JavaClassNameInsertHandler implements InsertHandler<JavaPsiClassReferenceE
return false;
}
private static boolean insertingAnnotationWithParameters(InsertionContext context, LookupElement item) {
private static boolean insertingAnnotation(InsertionContext context, LookupElement item) {
final Object obj = item.getObject();
if (!(obj instanceof PsiClass) || !((PsiClass)obj).isAnnotationType()) return false;
PsiElement leaf = context.getFile().findElementAt(context.getStartOffset());
if (psiElement(PsiIdentifier.class).withParents(PsiJavaCodeReferenceElement.class, PsiAnnotation.class).accepts(leaf)) {
return shouldHaveAnnotationParameters((PsiClass)obj);
}
return false;
return psiElement(PsiIdentifier.class).withParents(PsiJavaCodeReferenceElement.class, PsiAnnotation.class).accepts(leaf);
}
static boolean shouldHaveAnnotationParameters(PsiClass annoClass) {
@@ -293,7 +293,7 @@ public class JavaCompletionContributor extends CompletionContributor {
}
private static void registerClassFromTypeElement(LookupElement element, InheritorsHolder inheritors) {
PsiType type = assertNotNull(element.as(PsiTypeLookupItem.CLASS_CONDITION_KEY)).getPsiType();
PsiType type = assertNotNull(element.as(PsiTypeLookupItem.CLASS_CONDITION_KEY)).getType();
PsiClass aClass =
type instanceof PsiClassType && ((PsiClassType)type).getParameterCount() == 0 ? ((PsiClassType)type).resolve() : null;
if (aClass != null) {
@@ -245,48 +245,10 @@ public class JavaCompletionUtil {
return null;
}
@Nullable
private static PsiType getPsiType(final Object o) {
if (o instanceof ResolveResult) {
return getPsiType(((ResolveResult)o).getElement());
}
if (o instanceof PsiVariable) {
return ((PsiVariable)o).getType();
}
else if (o instanceof PsiMethod) {
return ((PsiMethod)o).getReturnType();
}
else if (o instanceof PsiClass) {
final PsiClass psiClass = (PsiClass)o;
return JavaPsiFacade.getInstance(psiClass.getProject()).getElementFactory().createType(psiClass);
}
else if (o instanceof PsiExpression) {
return ((PsiExpression)o).getType();
}
return null;
}
@Nullable
public static PsiType getLookupElementType(final LookupElement element) {
TypedLookupItem typed = element.as(TypedLookupItem.CLASS_CONDITION_KEY);
if (typed != null) {
return typed.getType();
}
final PsiType qualifierType = getPsiType(element.getObject());
final LookupItem lookupItem = element.as(LookupItem.CLASS_CONDITION_KEY);
if (lookupItem != null) {
final Object o = lookupItem.getAttribute(LookupItem.TYPE);
if (o instanceof PsiType) {
return (PsiType)o;
}
final PsiSubstitutor substitutor = (PsiSubstitutor)lookupItem.getAttribute(LookupItem.SUBSTITUTOR);
if (substitutor != null) {
return substitutor.substitute(qualifierType);
}
}
return qualifierType;
return typed != null ? typed.getType() : null;
}
@Nullable
@@ -424,7 +386,7 @@ public class JavaCompletionUtil {
if (plainQualifier != null) {
Object o = item.getObject();
if (o instanceof PsiMethod) {
PsiType castType = castTypeItem.getPsiType();
PsiType castType = castTypeItem.getType();
if (plainQualifier instanceof PsiClassType && castType instanceof PsiClassType) {
PsiMethod method = (PsiMethod)o;
PsiClassType.ClassResolveResult plainResult = ((PsiClassType)plainQualifier).resolveGenerics();
@@ -575,13 +537,12 @@ public class JavaCompletionUtil {
}
LookupElement _ret = LookupItemUtil.objectToLookupItem(completion);
if (_ret == null || !(_ret instanceof LookupItem)) return Collections.emptyList();
final PsiSubstitutor substitutor = completionElement.getSubstitutor();
if (substitutor != null) {
((LookupItem<?>)_ret).setAttribute(LookupItem.SUBSTITUTOR, substitutor);
if (_ret instanceof LookupItem) {
final PsiSubstitutor substitutor = completionElement.getSubstitutor();
if (substitutor != null) {
((LookupItem<?>)_ret).setAttribute(LookupItem.SUBSTITUTOR, substitutor);
}
}
return Collections.singletonList(_ret);
}
@@ -89,7 +89,7 @@ public class JavaDocCompletionContributor extends CompletionContributor {
for (final CompletionElement _item : processor.getResults()) {
final Object element = _item.getElement();
LookupItem item = createLookupItem(element);
LookupElement item = createLookupItem(element);
if (onlyConstants) {
Object o = item.getObject();
if (!(o instanceof PsiField)) continue;
@@ -100,16 +100,20 @@ public class JavaDocCompletionContributor extends CompletionContributor {
item.putUserData(LookupItem.FORCE_SHOW_SIGNATURE_ATTR, Boolean.TRUE);
if (isArg) {
item.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
item = AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(item);
}
result.addElement(item);
}
JavaCompletionContributor.addAllClasses(parameters, result, new InheritorsHolder(result));
}
if (tag != null && "author".equals(tag.getName())) {
result.addElement(LookupElementBuilder.create(SystemProperties.getUserName()));
}
}
private LookupItem createLookupItem(final Object element) {
private LookupElement createLookupItem(final Object element) {
if (element instanceof PsiMethod) {
return new JavaMethodCallElement((PsiMethod)element) {
@Override
@@ -124,7 +128,7 @@ public class JavaDocCompletionContributor extends CompletionContributor {
return classElement;
}
return (LookupItem)LookupItemUtil.objectToLookupItem(element);
return LookupItemUtil.objectToLookupItem(element);
}
});
}
@@ -328,12 +328,12 @@ public class JavaKeywordCompletion {
result.consume(createKeyword(position, PsiKeyword.THIS));
}
final LookupItem superItem = (LookupItem)createKeyword(position, PsiKeyword.SUPER);
final LookupElement superItem = createKeyword(position, PsiKeyword.SUPER);
if (psiElement().afterLeaf(psiElement().withText("{").withSuperParent(2, psiMethod().constructor(true))).accepts(position)) {
final PsiMethod method = PsiTreeUtil.getParentOfType(position, PsiMethod.class, false, PsiClass.class);
assert method != null;
final boolean hasParams = superConstructorHasParameters(method);
superItem.setInsertHandler(new ParenthesesInsertHandler<LookupElement>() {
result.consume(LookupElementDecorator.withInsertHandler(superItem, new ParenthesesInsertHandler<LookupElement>() {
@Override
protected boolean placeCaretInsideParentheses(InsertionContext context, LookupElement item) {
return hasParams;
@@ -344,7 +344,8 @@ public class JavaKeywordCompletion {
super.handleInsert(context, item);
TailType.insertChar(context.getEditor(), context.getTailOffset(), ';');
}
});
}));
return;
}
result.consume(superItem);
@@ -468,6 +469,9 @@ public class JavaKeywordCompletion {
if (referenceList != null && referenceList.getParent() instanceof PsiClass) {
psiClass = (PsiClass)referenceList.getParent();
}
else if (prevLeaf.getParent() instanceof PsiTypeParameterList && prevLeaf.getParent().getParent() instanceof PsiClass) {
psiClass = (PsiClass)prevLeaf.getParent().getParent();
}
}
if (psiClass != null) {
@@ -643,7 +647,7 @@ public class JavaKeywordCompletion {
br = TailTypeDecorator.withTail(br, tailType);
cont = TailTypeDecorator.withTail(cont, tailType);
if (loop != null && new InsideElementFilter(new ClassFilter(PsiStatement.class)).isAcceptable(position, loop)) {
if (loop != null && PsiTreeUtil.isAncestor(loop.getBody(), position, false)) {
result.consume(br);
result.consume(cont);
}
@@ -16,10 +16,7 @@
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.lookup.DefaultLookupItemRenderer;
import com.intellij.codeInsight.lookup.LookupElementPresentation;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.PsiTypeLookupItem;
import com.intellij.codeInsight.lookup.*;
import com.intellij.codeInsight.lookup.impl.JavaElementLookupRenderer;
import com.intellij.openapi.util.ClassConditionKey;
import com.intellij.openapi.util.Comparing;
@@ -41,7 +38,7 @@ import java.util.Set;
/**
* @author peter
*/
public class JavaPsiClassReferenceElement extends LookupItem<Object> {
public class JavaPsiClassReferenceElement extends LookupItem<Object> implements TypedLookupItem {
public static final Key<String> PACKAGE_NAME = Key.create("PACKAGE_NAME");
public static final ClassConditionKey<JavaPsiClassReferenceElement> CLASS_CONDITION_KEY = ClassConditionKey.create(JavaPsiClassReferenceElement.class);
private final Object myClass;
@@ -63,6 +60,14 @@ public class JavaPsiClassReferenceElement extends LookupItem<Object> {
return myForcedPresentableName;
}
@Nullable
@Override
public PsiType getType() {
PsiClass psiClass = getObject();
final PsiSubstitutor substitutor = (PsiSubstitutor)getAttribute(LookupItem.SUBSTITUTOR);
return JavaPsiFacade.getElementFactory(psiClass.getProject()).createType(psiClass, substitutor == null ? PsiSubstitutor.EMPTY : substitutor);
}
@NotNull
@Override
public String getLookupString() {
@@ -16,11 +16,10 @@
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiKeyword;
import com.intellij.psi.PsiPrimitiveType;
import com.intellij.psi.PsiType;
import java.util.Collection;
import java.util.LinkedHashSet;
@@ -52,8 +51,7 @@ public class NullSmartCompletionContributor extends CompletionContributor{
for (final ExpectedTypeInfo info : infos) {
if (!(info.getType() instanceof PsiPrimitiveType)) {
final LookupItem item = (LookupItem)BasicExpressionCompletionContributor.createKeywordLookupItem(parameters.getPosition(), PsiKeyword.NULL);
item.setAttribute(LookupItem.TYPE, PsiType.NULL);
final LookupElement item = BasicExpressionCompletionContributor.createKeywordLookupItem(parameters.getPosition(), PsiKeyword.NULL);
result.addElement(JavaSmartCompletionContributor.decorate(item, infos));
return;
}
@@ -17,11 +17,8 @@ package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.lookup.ExpressionLookupItem;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Iconable;
import com.intellij.openapi.util.text.StringUtil;
@@ -34,7 +31,6 @@ import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.filters.*;
import com.intellij.psi.filters.element.ModifierFilter;
import com.intellij.psi.filters.types.AssignableFromFilter;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
@@ -254,10 +250,7 @@ public class ReferenceExpressionCompletionContributor {
final PsiExpression[] dimensions = newExpression.getArrayDimensions();
if (dimensions.length == 1 && "1".equals(dimensions[0].getText()) && newExpression.getArrayInitializer() == null) {
final String text = variable.getName() + "[0]";
final PsiExpression conversion = createExpression(text, element);
ExpressionLookupItem result = new ExpressionLookupItem(conversion);
result.setIcon(variable.getIcon(Iconable.ICON_FLAG_VISIBILITY));
return result;
return new ExpressionLookupItem(createExpression(text, element), variable.getIcon(Iconable.ICON_FLAG_VISIBILITY), text, text);
}
}
}
@@ -311,29 +304,17 @@ public class ReferenceExpressionCompletionContributor {
throws IncorrectOperationException {
if (itemType instanceof PsiArrayType && expectedType.isAssignableFrom(((PsiArrayType)itemType).getComponentType())) {
final PsiExpression conversion = createExpression(getQualifierText(qualifier) + prefix + "[0]", element);
final LookupItem item = new ExpressionLookupItem(conversion);
@NonNls final String presentable = prefix + "[...]";
item.setLookupString(prefix);
item.setPresentableText(presentable);
item.addLookupStrings(prefix);
item.setIcon(object.getIcon(Iconable.ICON_FLAG_VISIBILITY));
item.setInsertHandler(new InsertHandler<LookupElement>() {
result.consume(new ExpressionLookupItem(conversion, object.getIcon(Iconable.ICON_FLAG_VISIBILITY), prefix + "[...]", prefix) {
@Override
public void handleInsert(InsertionContext context, LookupElement item) {
public void handleInsert(InsertionContext context) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.SECOND_SMART_COMPLETION_ARRAY_MEMBER);
final Editor editor = context.getEditor();
final int startOffset = context.getStartOffset();
final Document document = editor.getDocument();
final int tailOffset = startOffset + item.getLookupString().length();
final int tailOffset = context.getTailOffset();
final String callSpace = getSpace(CodeStyleSettingsManager.getSettings(element.getProject()).SPACE_WITHIN_BRACKETS);
final String access = "[" + callSpace + callSpace + "]";
document.insertString(tailOffset, access);
editor.getCaretModel().moveToOffset(tailOffset + 1 + callSpace.length());
context.getDocument().insertString(tailOffset, "[" + callSpace + callSpace + "]");
context.getEditor().getCaretModel().moveToOffset(tailOffset + 1 + callSpace.length());
}
});
result.consume(item);
}
}
@@ -358,41 +339,23 @@ public class ReferenceExpressionCompletionContributor {
final String qualifierText = getQualifierText(qualifier);
final PsiExpression conversion = createExpression("java.util.Arrays." + methodName + "(" + qualifierText + prefix + ")", element);
final LookupItem item = new ExpressionLookupItem(conversion);
@NonNls final String presentable = "Arrays." + methodName + "(" + qualifierText + prefix + ")";
item.setLookupString(StringUtil.isEmpty(qualifierText) ? presentable : prefix);
item.setPresentableText(presentable);
item.addLookupStrings(prefix, presentable, methodName + "(" + prefix + ")");
item.setIcon(PlatformIcons.METHOD_ICON);
item.setInsertHandler(new InsertHandler<LookupElement>() {
final String presentable = "Arrays." + methodName + "(" + qualifierText + prefix + ")";
String[] lookupStrings = {StringUtil.isEmpty(qualifierText) ? presentable : prefix, prefix, presentable, methodName + "(" + prefix + ")"};
result.consume(new ExpressionLookupItem(conversion, PlatformIcons.METHOD_ICON, presentable, lookupStrings) {
@Override
public void handleInsert(InsertionContext context, LookupElement item) {
public void handleInsert(InsertionContext context) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.SECOND_SMART_COMPLETION_ASLIST);
final Editor editor = context.getEditor();
int startOffset = context.getStartOffset();
final Document document = editor.getDocument();
final int tailOffset = startOffset + item.getLookupString().length();
startOffset -= qualifierText.length();
int startOffset = context.getStartOffset() - qualifierText.length();
final Project project = element.getProject();
final String callSpace = getSpace(CodeStyleSettingsManager.getSettings(project).SPACE_WITHIN_METHOD_CALL_PARENTHESES);
@NonNls final String newText = "java.util.Arrays." + methodName + "(" + callSpace + qualifierText + prefix + callSpace + ")";
document.replaceString(startOffset, tailOffset, newText);
final String newText = "java.util.Arrays." + methodName + "(" + callSpace + qualifierText + prefix + callSpace + ")";
context.getDocument().replaceString(startOffset, context.getTailOffset(), newText);
PsiDocumentManager.getInstance(project).commitDocument(document);
final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
try {
JavaCodeStyleManager.getInstance(project)
.shortenClassReferences(file, startOffset, startOffset + CommonClassNames.JAVA_UTIL_ARRAYS.length());
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
PostprocessReformattingAspect.getInstance(project).doPostponedFormatting();
context.commitDocument();
JavaCodeStyleManager.getInstance(project).shortenClassReferences(context.getFile(), startOffset, startOffset + CommonClassNames.JAVA_UTIL_ARRAYS.length());
}
});
result.consume(item);
}
@Nullable
@@ -585,33 +548,16 @@ public class ReferenceExpressionCompletionContributor {
return;
}
final LookupItem item = new ExpressionLookupItem(conversion);
item.setLookupString(prefix + ".toArray(" + getSpace(callSpace) + expressionString + getSpace(callSpace) + ")");
item.setPresentableText(prefix + ".toArray(" + presentableString + ")");
item.addLookupStrings(presentableString);
item.setIcon(PlatformIcons.METHOD_ICON);
item.setInsertHandler(new InsertHandler<LookupItem>(){
@Override
public void handleInsert(InsertionContext context, LookupItem item) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.SECOND_SMART_COMPLETION_TOAR);
String[] lookupStrings = {prefix + ".toArray(" + getSpace(callSpace) + expressionString + getSpace(callSpace) + ")", presentableString};
result.consume(new ExpressionLookupItem(conversion, PlatformIcons.METHOD_ICON, prefix + ".toArray(" + presentableString + ")", lookupStrings) {
@Override
public void handleInsert(InsertionContext context) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.SECOND_SMART_COMPLETION_TOAR);
final Editor editor = context.getEditor();
final int startOffset = context.getStartOffset();
final Document document = editor.getDocument();
final int tailOffset = startOffset + item.getLookupString().length();
final Project project = editor.getProject();
context.commitDocument();
final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
try {
JavaCodeStyleManager.getInstance(project).shortenClassReferences(file, startOffset, tailOffset);
context.commitDocument();
JavaCodeStyleManager.getInstance(context.getProject()).shortenClassReferences(context.getFile(), context.getStartOffset(), context.getTailOffset());
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
PostprocessReformattingAspect.getInstance(project).doPostponedFormatting();
}
});
result.consume(item);
});
}
private static boolean isEmptyArrayInitializer(@Nullable PsiElement element) {
@@ -217,7 +217,7 @@ class TypeArgumentCompletionProvider extends CompletionProvider<CompletionParame
public void registerSingleClass(@Nullable InheritorsHolder inheritors) {
if (inheritors != null && myTypeItems.size() == 1) {
PsiType type = myTypeItems.get(0).getPsiType();
PsiType type = myTypeItems.get(0).getType();
PsiClass aClass = PsiUtil.resolveClassInClassTypeOnly(type);
if (aClass != null && !aClass.hasTypeParameters()) {
JavaCompletionUtil.setShowFQN(myTypeItems.get(0));
@@ -61,9 +61,18 @@ public class MarkerType {
private final GutterIconNavigationHandler<PsiElement> handler;
private final Function<PsiElement, String> myTooltip;
@NotNull private final String myDebugName;
/**
* @deprecated use {@link #MarkerType(String, Function, LineMarkerNavigator)} instead
*/
public MarkerType(@NotNull Function<PsiElement, String> tooltip, @NotNull final LineMarkerNavigator navigator) {
this("Unknown", tooltip, navigator);
}
public MarkerType(@NotNull String debugName, @NotNull Function<PsiElement, String> tooltip, @NotNull final LineMarkerNavigator navigator) {
myTooltip = tooltip;
myDebugName = debugName;
handler = new GutterIconNavigationHandler<PsiElement>() {
@Override
public void navigate(final MouseEvent e, final PsiElement elt) {
@@ -77,6 +86,11 @@ public class MarkerType {
};
}
@Override
public String toString() {
return myDebugName;
}
@NotNull
public GutterIconNavigationHandler<PsiElement> getNavigationHandler() {
return handler;
@@ -87,7 +101,7 @@ public class MarkerType {
return myTooltip;
}
static final MarkerType OVERRIDING_METHOD = new MarkerType(new NullableFunction<PsiElement, String>() {
static final MarkerType OVERRIDING_METHOD = new MarkerType("OVERRIDING_METHOD", new NullableFunction<PsiElement, String>() {
@Override
public String fun(PsiElement element) {
PsiElement parent = getParentMethod(element);
@@ -169,7 +183,7 @@ public class MarkerType {
}
public static final String SEARCHING_FOR_OVERRIDING_METHODS = "Searching for Overriding Methods";
static final MarkerType OVERRIDDEN_METHOD = new MarkerType(new NullableFunction<PsiElement, String>() {
static final MarkerType OVERRIDDEN_METHOD = new MarkerType("OVERRIDDEN_METHOD", new NullableFunction<PsiElement, String>() {
@Override
public String fun(PsiElement element) {
PsiElement parent = element.getParent();
@@ -257,7 +271,7 @@ public class MarkerType {
}
private static final String SEARCHING_FOR_OVERRIDDEN_METHODS = "Searching for Overridden Methods";
static final MarkerType SUBCLASSED_CLASS = new MarkerType(new NullableFunction<PsiElement, String>() {
static final MarkerType SUBCLASSED_CLASS = new MarkerType("SUBCLASSED_CLASS", new NullableFunction<PsiElement, String>() {
@Override
public String fun(PsiElement element) {
PsiElement parent = element.getParent();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 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.
@@ -25,6 +25,7 @@ import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.ig.psiutils.ParenthesesUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
@@ -117,7 +118,9 @@ public class ConvertSwitchToIfIntention implements IntentionAction {
else {
hadSideEffects = false;
declarationString = null;
expressionText = switchExpression.getText();
expressionText = ParenthesesUtils.getPrecedence(switchExpression) > ParenthesesUtils.EQUALITY_PRECEDENCE
? '(' + switchExpression.getText() + ')'
: switchExpression.getText();
}
final PsiCodeBlock body = switchStatement.getBody();
if (body == null) {
@@ -44,7 +44,7 @@ public class MethodCallFixer implements Fixer {
if (args != null && !hasRParenth(args)) {
int caret = editor.getCaretModel().getOffset();
PsiCallExpression innermostCall = PsiTreeUtil.findElementOfClassAtOffset(psiElement.getContainingFile(), caret, PsiCallExpression.class, false);
PsiCallExpression innermostCall = PsiTreeUtil.findElementOfClassAtOffset(psiElement.getContainingFile(), caret - 1, PsiCallExpression.class, false);
if (innermostCall == null) return;
args = innermostCall.getArgumentList();
@@ -29,7 +29,6 @@ import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.PackageIndex;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.JDOMUtil;
@@ -42,6 +41,7 @@ import com.intellij.psi.*;
import com.intellij.psi.impl.JavaConstantExpressionEvaluator;
import com.intellij.psi.impl.source.tree.JavaDocElementType;
import com.intellij.psi.javadoc.*;
import com.intellij.psi.search.EverythingGlobalScope;
import com.intellij.psi.util.PsiFormatUtil;
import com.intellij.psi.util.PsiFormatUtilBase;
import com.intellij.psi.util.PsiTreeUtil;
@@ -385,7 +385,7 @@ public class JavaDocInfoGenerator {
return null;
if (docURLs != null) {
if (elementHasSourceCode()) {
if (buffer.length() > 0 && elementHasSourceCode()) {
LOG.debug("Documentation for " + myElement + " was generated from source code, it wasn't found at following URLs: ", docURLs);
}
else {
@@ -408,25 +408,24 @@ public class JavaDocInfoGenerator {
}
private boolean elementHasSourceCode() {
VirtualFile[] files;
PsiFileSystemItem[] items;
if (myElement instanceof PsiDirectory) {
final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage((PsiDirectory)myElement);
if (aPackage == null) return false;
files = PackageIndex.getInstance(myProject).getDirectoriesByPackageName(aPackage.getQualifiedName(), true);
items = aPackage.getDirectories(new EverythingGlobalScope(myProject));
}
else if (myElement instanceof PsiPackage) {
files = PackageIndex.getInstance(myProject).getDirectoriesByPackageName(((PsiPackage)myElement).getQualifiedName(), true);
items = ((PsiPackage)myElement).getDirectories(new EverythingGlobalScope(myProject));
}
else {
PsiFile containingFile = myElement.getNavigationElement().getContainingFile();
if (containingFile == null) return false;
VirtualFile virtualFile = containingFile.getVirtualFile();
if (virtualFile == null) return false;
files = new VirtualFile[] {virtualFile};
items = new PsiFileSystemItem[] {containingFile};
}
ProjectFileIndex projectFileIndex = ProjectFileIndex.SERVICE.getInstance(myProject);
for (VirtualFile file : files) {
if (projectFileIndex.isInSource(file)) return true;
for (PsiFileSystemItem item : items) {
VirtualFile file = item.getVirtualFile();
if (file != null && projectFileIndex.isInSource(file)) return true;
}
return false;
}
@@ -683,10 +682,7 @@ public class JavaDocInfoGenerator {
}
private void generatePackageJavaDoc(final StringBuilder buffer, final PsiPackage psiPackage, boolean generatePrologueAndEpilogue) {
VirtualFile[] dirs = PackageIndex.getInstance(myProject).getDirectoriesByPackageName(psiPackage.getQualifiedName(), true);
for (VirtualFile dir : dirs) {
PsiDirectory directory = PsiManager.getInstance(myProject).findDirectory(dir);
if (directory == null) continue;
for (PsiDirectory directory : psiPackage.getDirectories(new EverythingGlobalScope(myProject))) {
final PsiFile packageInfoFile = directory.findFile(PsiPackage.PACKAGE_INFO_FILE);
if (packageInfoFile != null) {
final ASTNode node = packageInfoFile.getNode();
@@ -17,38 +17,87 @@ package com.intellij.codeInsight.lookup;
import com.intellij.psi.*;
import com.intellij.util.PlatformIcons;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.Collections;
import java.util.Set;
/**
* @author peter
*/
public class ExpressionLookupItem extends LookupItem<PsiExpression> implements TypedLookupItem {
public ExpressionLookupItem(final PsiExpression expression) {
super(expression, expression.getText());
public class ExpressionLookupItem extends LookupElement implements TypedLookupItem {
private final PsiExpression myExpression;
private final Icon myIcon;
private final String myPresentableText;
private final String myLookupString;
private final Set<String> myAllLookupStrings;
public ExpressionLookupItem(final PsiExpression expression) {
this(expression, getExpressionIcon(expression), expression.getText(), expression.getText());
}
public ExpressionLookupItem(final PsiExpression expression, @Nullable Icon icon, String presentableText, String... lookupStrings) {
myExpression = expression;
myPresentableText = presentableText;
myIcon = icon;
myLookupString = lookupStrings[0];
myAllLookupStrings = Collections.unmodifiableSet(ContainerUtil.newHashSet(lookupStrings));
}
@Nullable
private static Icon getExpressionIcon(@NotNull PsiExpression expression) {
if (expression instanceof PsiReferenceExpression) {
final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)expression;
final PsiElement element = referenceExpression.resolve();
final PsiElement element = ((PsiReferenceExpression)expression).resolve();
if (element != null) {
setIcon(element.getIcon(0));
return element.getIcon(0);
}
}
if (expression instanceof PsiMethodCallExpression) {
setIcon(PlatformIcons.METHOD_ICON);
return PlatformIcons.METHOD_ICON;
}
return null;
}
@NotNull
@Override
public PsiExpression getObject() {
return myExpression;
}
@Override
public void renderElement(LookupElementPresentation presentation) {
presentation.setIcon(myIcon);
presentation.setItemText(myPresentableText);
PsiType type = getType();
presentation.setTypeText(type == null ? null : type.getPresentableText());
}
@Override
public PsiType getType() {
return getObject().getType();
return myExpression.getType();
}
@Override
public boolean equals(final Object o) {
return o instanceof ExpressionLookupItem && getLookupString().equals(((ExpressionLookupItem)o).getLookupString());
return o instanceof ExpressionLookupItem && myLookupString.equals(((ExpressionLookupItem)o).myLookupString);
}
@Override
public int hashCode() {
return getLookupString().hashCode();
return myLookupString.hashCode();
}
@NotNull
@Override
public String getLookupString() {
return myLookupString;
}
@Override
public Set<String> getAllLookupStrings() {
return myAllLookupStrings;
}
}
@@ -24,14 +24,32 @@ import org.jetbrains.annotations.NotNull;
/**
* @author peter
*/
public class KeywordLookupItem extends LookupItem<PsiKeyword> implements TypedLookupItem {
public class KeywordLookupItem extends LookupElement implements TypedLookupItem {
private final PsiElement myPosition;
private final PsiKeyword myKeyword;
public KeywordLookupItem(final PsiKeyword keyword, @NotNull PsiElement position) {
super(keyword, keyword.getText());
myKeyword = keyword;
myPosition = position;
}
@NotNull
@Override
public Object getObject() {
return myKeyword;
}
@NotNull
@Override
public String getLookupString() {
return myKeyword.getText();
}
@Override
public AutoCompletionPolicy getAutoCompletionPolicy() {
return AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE;
}
@Override
public boolean equals(final Object o) {
return o instanceof KeywordLookupItem && getLookupString().equals(((KeywordLookupItem)o).getLookupString());
@@ -71,6 +71,7 @@ public class LookupItemUtil{
* @deprecated
* @see LookupElementBuilder
*/
@NotNull
public static LookupElement objectToLookupItem(Object object) {
if (object instanceof LookupElement) return (LookupElement)object;
if (object instanceof PsiClass) {
@@ -82,9 +83,6 @@ public class LookupItemUtil{
if (object instanceof PsiVariable) {
return new VariableLookupItem((PsiVariable)object);
}
if (object instanceof PsiKeyword) {
return new KeywordLookupItem((PsiKeyword)object, (PsiKeyword)object);
}
if (object instanceof PsiExpression) {
return new ExpressionLookupItem((PsiExpression) object);
}
@@ -19,21 +19,51 @@ import com.intellij.codeInsight.AutoPopupController;
import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.completion.InsertionContext;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaCodeReferenceCodeFragment;
import com.intellij.psi.PsiPackage;
import com.intellij.util.PlatformIcons;
import org.jetbrains.annotations.NotNull;
/**
* @author peter
*/
class PackageLookupItem extends LookupItem<PsiPackage> {
class PackageLookupItem extends LookupElement {
private final PsiPackage myPackage;
private final String myString;
public PackageLookupItem(PsiPackage pkg) {
super(pkg, StringUtil.notNullize(pkg.getName()));
setTailType(TailType.DOT);
myPackage = pkg;
myString = StringUtil.notNullize(myPackage.getName());
}
@NotNull
@Override
public Object getObject() {
return myPackage;
}
@NotNull
@Override
public String getLookupString() {
return myString;
}
@Override
public void renderElement(LookupElementPresentation presentation) {
super.renderElement(presentation);
presentation.setIcon(PlatformIcons.PACKAGE_ICON);
}
@Override
public void handleInsert(InsertionContext context) {
super.handleInsert(context);
if (getTailType() == TailType.DOT || context.getCompletionChar() == '.') {
PsiFile file = context.getFile();
boolean addDot = !(file instanceof PsiJavaCodeReferenceCodeFragment) || ((PsiJavaCodeReferenceCodeFragment)file).isClassesAccepted();
if (addDot) {
context.setAddCompletionChar(false);
TailType.DOT.processTail(context.getEditor(), context.getTailOffset());
}
if (addDot || context.getCompletionChar() == '.') {
AutoPopupController.getInstance(context.getProject()).scheduleAutoPopup(context.getEditor());
}
}
@@ -39,7 +39,7 @@ import java.util.Set;
/**
* @author peter
*/
public class PsiTypeLookupItem extends LookupItem {
public class PsiTypeLookupItem extends LookupItem implements TypedLookupItem {
private static final InsertHandler<PsiTypeLookupItem> DEFAULT_IMPORT_FIXER = new InsertHandler<PsiTypeLookupItem>() {
@Override
public void handleInsert(InsertionContext context, PsiTypeLookupItem item) {
@@ -65,13 +65,14 @@ public class PsiTypeLookupItem extends LookupItem {
}
@NotNull
public PsiType getPsiType() {
@Override
public PsiType getType() {
Object object = getObject();
PsiType type = object instanceof PsiType ? (PsiType)object : JavaPsiFacade.getElementFactory(((PsiClass) object).getProject()).createType((PsiClass)object);
for (int i = 0; i < getBracketsCount(); i++) {
type = new PsiArrayType(type);
}
return type;
return getSubstitutor().substitute(type);
}
@@ -191,18 +192,14 @@ public class PsiTypeLookupItem extends LookupItem {
}
public static PsiTypeLookupItem createLookupItem(@NotNull PsiType type, @Nullable PsiElement context, boolean isDiamond, InsertHandler<PsiTypeLookupItem> importFixer) {
final PsiType original = type;
public static PsiTypeLookupItem createLookupItem(@NotNull PsiType type, @Nullable PsiElement context, boolean isDiamond, InsertHandler<PsiTypeLookupItem> importFixer) {
int dim = 0;
while (type instanceof PsiArrayType) {
type = ((PsiArrayType)type).getComponentType();
dim++;
}
PsiTypeLookupItem item = doCreateItem(type, context, dim, isDiamond, importFixer);
item.setAttribute(TYPE, original);
return item;
return doCreateItem(type, context, dim, isDiamond, importFixer);
}
private static PsiTypeLookupItem doCreateItem(final PsiType type,
@@ -19,7 +19,6 @@ import com.intellij.codeInsight.completion.JavaCompletionUtil;
import com.intellij.codeInsight.lookup.DefaultLookupItemRenderer;
import com.intellij.codeInsight.lookup.LookupElementPresentation;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.beanProperties.BeanPropertyElement;
import com.intellij.psi.util.PsiUtilCore;
@@ -33,63 +32,19 @@ import java.util.List;
public class JavaElementLookupRenderer implements ElementLookupRenderer {
@Override
public boolean handlesItem(final Object element) {
return element instanceof PsiKeyword || element instanceof PsiExpression ||
element instanceof PsiTypeElement || element instanceof BeanPropertyElement;
return element instanceof BeanPropertyElement;
}
@Override
public void renderElement(final LookupItem item, final Object element, final LookupElementPresentation presentation) {
presentation.setIcon(DefaultLookupItemRenderer.getRawIcon(item, presentation.isReal()));
presentation.setItemText(getName(element, item));
presentation.setItemText(PsiUtilCore.getName((PsiElement)element));
presentation.setStrikeout(isToStrikeout(item));
presentation.setTailText((String)item.getAttribute(LookupItem.TAIL_TEXT_ATTR), item.getAttribute(LookupItem.TAIL_TEXT_SMALL_ATTR) != null);
presentation.setTypeText(getTypeText(element, item));
}
private static String getName(final Object o, final LookupItem<?> item) {
final String presentableText = item.getPresentableText();
if (presentableText != null) {
return presentableText;
}
String name = "";
if (o instanceof PsiElement) {
final PsiElement element = (PsiElement)o;
if (element.isValid()) {
if (element instanceof PsiKeyword || element instanceof PsiExpression || element instanceof PsiTypeElement) {
name = element.getText();
} else {
name = PsiUtilCore.getName(element);
}
}
}
return StringUtil.notNullize(name);
}
@Nullable
private static String getTypeText(final Object o, final LookupItem item) {
String text = null;
if (o instanceof PsiElement) {
final PsiElement element = (PsiElement)o;
if (element.isValid()) {
if (element instanceof PsiExpression){
PsiExpression expression = (PsiExpression)element;
PsiType type = expression.getType();
if (type != null){
text = type.getPresentableText();
}
}
else if (element instanceof BeanPropertyElement) {
return getTypeText(item, ((BeanPropertyElement)element).getPropertyType());
}
}
}
return text;
presentation.setTypeText(getTypeText(item, ((BeanPropertyElement)element).getPropertyType()));
}
@Nullable
@@ -15,12 +15,14 @@
*/
package com.intellij.codeInsight.navigation;
import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator;
import com.intellij.codeInsight.generation.actions.PresentableCodeInsightActionHandler;
import com.intellij.codeInsight.navigation.actions.GotoSuperAction;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.util.MethodCellRenderer;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
@@ -33,7 +35,7 @@ import com.intellij.psi.util.PsiUtil;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NotNull;
public class JavaGotoSuperHandler implements CodeInsightActionHandler {
public class JavaGotoSuperHandler implements PresentableCodeInsightActionHandler {
@Override
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(GotoSuperAction.FEATURE_ID);
@@ -93,4 +95,19 @@ public class JavaGotoSuperHandler implements CodeInsightActionHandler {
public boolean startInWriteAction() {
return false;
}
@Override
public void update(@NotNull Editor editor, @NotNull PsiFile file, Presentation presentation) {
final PsiElement element = getElement(file, editor.getCaretModel().getOffset());
final PsiElement containingElement = PsiTreeUtil.getParentOfType(element, PsiFunctionalExpression.class, PsiMember.class);
if (containingElement instanceof PsiClass) {
presentation.setText(ActionsBundle.actionText("GotoSuperClass"));
presentation.setDescription(ActionsBundle.actionText("GotoSuperClass"));
}
else {
presentation.setText(ActionsBundle.actionText("GotoSuperMethod"));
presentation.setDescription(ActionsBundle.actionText("GotoSuperMethod"));
}
}
}
@@ -20,7 +20,6 @@ import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.PsiTypeLookupItem;
import com.intellij.codeInsight.template.*;
import com.intellij.psi.PsiArrayType;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiType;
import com.intellij.util.containers.ContainerUtil;
@@ -49,7 +48,7 @@ public class ComponentTypeOfMacro extends Macro {
for (LookupElement element : lookupItems) {
PsiTypeLookupItem lookupItem = element.as(PsiTypeLookupItem.CLASS_CONDITION_KEY);
if (lookupItem != null) {
PsiType psiType = lookupItem.getPsiType();
PsiType psiType = lookupItem.getType();
if (psiType instanceof PsiArrayType) {
result.add(PsiTypeLookupItem.createLookupItem(((PsiArrayType)psiType).getComponentType(), null));
}
@@ -83,7 +82,7 @@ public class ComponentTypeOfMacro extends Macro {
for (LookupElement element : elements) {
PsiTypeLookupItem typeLookupItem = element.as(PsiTypeLookupItem.CLASS_CONDITION_KEY);
if (typeLookupItem != null) {
PsiType psiType = typeLookupItem.getPsiType();
PsiType psiType = typeLookupItem.getType();
if (psiType instanceof PsiArrayType) {
return new PsiTypeResult(((PsiArrayType)psiType).getComponentType(), context.getProject());
}
@@ -78,12 +78,21 @@ public class MoveToPackageFix implements LocalQuickFix {
private void chooseDirectoryAndMove(Project project, PsiFile myFile) {
try {
PsiDirectory directory = MoveClassesOrPackagesUtil.chooseDestinationPackage(project, myTargetPackage, myFile.getContainingDirectory());
String error;
PsiDirectory directory = null;
try {
directory = MoveClassesOrPackagesUtil.chooseDestinationPackage(project, myTargetPackage, myFile.getContainingDirectory());
if (directory == null) {
return;
if (directory == null) {
return;
}
error = RefactoringMessageUtil.checkCanCreateFile(directory, myFile.getName());
}
String error = RefactoringMessageUtil.checkCanCreateFile(directory, myFile.getName());
catch (IncorrectOperationException e) {
error = e.getLocalizedMessage();
}
if (error != null) {
Messages.showMessageDialog(project, error, CommonBundle.getErrorTitle(), Messages.getErrorIcon());
return;
@@ -56,8 +56,7 @@ public class GuavaFluentIterableInspection extends BaseJavaBatchLocalInspectionT
return null;
}
final Project project = manager.getProject();
final PsiClass fluentIterable = JavaPsiFacade.getInstance(project)
.findClass(GUAVA_FLUENT_ITERABLE, GlobalSearchScope.allScope(project));
final PsiClass fluentIterable = JavaPsiFacade.getInstance(project).findClass(GUAVA_FLUENT_ITERABLE, file.getResolveScope());
if (fluentIterable == null) {
return null;
}
@@ -394,7 +393,7 @@ public class GuavaFluentIterableInspection extends BaseJavaBatchLocalInspectionT
if (parameterType instanceof PsiClassType) {
final PsiClass resolvedParameterClass = ((PsiClassType)parameterType).resolve();
final JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(methodCallExpression.getProject());
final GlobalSearchScope scope = GlobalSearchScope.allScope(methodCallExpression.getProject());
final GlobalSearchScope scope = methodCallExpression.getResolveScope();
final PsiClass optional = javaPsiFacade.findClass(GUAVA_OPTIONAL, scope);
final PsiClass immutableMap = javaPsiFacade.findClass(GUAVA_IMMUTABLE_MAP, scope);
if (resolvedParameterClass != null &&
@@ -474,16 +473,20 @@ public class GuavaFluentIterableInspection extends BaseJavaBatchLocalInspectionT
final JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
final PsiElementFactory elementFactory = javaPsiFacade.getElementFactory();
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
final GuavaFluentIterableMethodConverters converters = new GuavaFluentIterableMethodConverters(elementFactory);
for (SmartPsiElementPointer<PsiExpression> usage : myFoundUsages) {
final PsiExpression element = usage.getElement();
if (element != null) {
GuavaFluentIterableMethodConverters.convert(element, elementFactory, codeStyleManager);
PsiElement converted = converters.convert(element);
if (converted != null) {
codeStyleManager.shortenClassReferences(converted);
}
}
}
if (myVariable != null) {
final PsiLocalVariable element = myVariable.getElement();
if (element != null) {
GuavaFluentIterableMethodConverters.convert(element, elementFactory, codeStyleManager);
codeStyleManager.shortenClassReferences(converters.convert(element));
}
}
}
@@ -18,9 +18,7 @@ package com.intellij.codeInspection.java18StreamApi;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
@@ -42,6 +40,11 @@ public class GuavaFluentIterableMethodConverters {
private static final Map<String, FluentIterableMethodTransformer> METHOD_INDEX = new HashMap<String, FluentIterableMethodTransformer>();
private static final Map<String, String> TO_OTHER_COLLECTION_METHODS = new HashMap<String, String>();
private static final Set<String> STOP_METHODS = new HashSet<String>();
private final PsiElementFactory myElementFactory;
public GuavaFluentIterableMethodConverters(PsiElementFactory elementFactory) {
myElementFactory = elementFactory;
}
static {
METHOD_INDEX.put("allMatch", new FluentIterableMethodTransformer.OneParameterMethodTransformer(StreamApiConstants.ALL_MATCH + "(%s)", true));
@@ -86,52 +89,44 @@ public class GuavaFluentIterableMethodConverters {
return STOP_METHODS.contains(methodName);
}
public static void convert(final PsiLocalVariable localVariable,
final PsiElementFactory elementFactory,
final JavaCodeStyleManager codeStyleManager) {
public PsiLocalVariable convert(final PsiLocalVariable localVariable) {
final PsiTypeElement typeElement = localVariable.getTypeElement();
final PsiReferenceParameterList generics = PsiTreeUtil.findChildOfType(typeElement, PsiReferenceParameterList.class);
typeElement.replace(elementFactory.createTypeElementFromText(
typeElement.replace(myElementFactory.createTypeElementFromText(
StreamApiConstants.JAVA_UTIL_STREAM_STREAM + (generics == null ? "" : generics.getText()), null));
final PsiExpression initializer = localVariable.getInitializer();
if (initializer != null) {
PsiMethodCallExpression initializerMethodCall = (PsiMethodCallExpression)initializer;
convertMethodCallDeep(elementFactory, initializerMethodCall);
convertMethodCallDeep((PsiMethodCallExpression)initializer);
}
codeStyleManager.shortenClassReferences(localVariable);
return localVariable;
}
public static void convert(PsiExpression expression,
final PsiElementFactory elementFactory,
final JavaCodeStyleManager codeStyleManager) {
public PsiElement convert(PsiExpression expression) {
if (expression instanceof PsiReferenceExpression) {
final PsiElement expressionParent = expression.getParent();
if (expressionParent instanceof PsiReturnStatement || isIterableMethodParameter(expressionParent, expression)) {
expression = (PsiExpression)expression.replace(
elementFactory.createExpressionFromText(expression.getText() + ".collect(java.util.stream.Collectors.toList())", null));
codeStyleManager.shortenClassReferences(expression);
return addCollectionToList(expression);
}
return;
return null;
}
final PsiMethodCallExpression parentMethodCall = PsiTreeUtil.getParentOfType(expression, PsiMethodCallExpression.class);
if (parentMethodCall != null && parentMethodCall.getMethodExpression().getQualifierExpression() == expression) {
final PsiMethod seqTailMethod = parentMethodCall.resolveMethod();
if (seqTailMethod == null) {
return;
return null;
}
final PsiClass seqTailMethodClass = seqTailMethod.getContainingClass();
if (seqTailMethodClass != null && GuavaFluentIterableInspection.GUAVA_OPTIONAL.equals(seqTailMethodClass.getQualifiedName())) {
final PsiMethodCallExpression newParentMethodCall =
GuavaOptionalConverter.convertGuavaOptionalToJava(parentMethodCall, elementFactory);
final PsiMethodCallExpression newParentMethodCall = GuavaOptionalConverter.convertGuavaOptionalToJava(parentMethodCall, myElementFactory);
expression = newParentMethodCall.getMethodExpression().getQualifierExpression();
}
}
if (expression instanceof PsiMethodCallExpression) {
expression = convertMethodCallDeep(elementFactory, (PsiMethodCallExpression)expression);
expression = convertMethodCallDeep((PsiMethodCallExpression)expression);
}
if (expression == null) {
return;
return null;
}
final PsiElement parent = expression.getParent();
if (parent instanceof PsiExpressionList) {
@@ -142,28 +137,28 @@ public class GuavaFluentIterableMethodConverters {
final PsiMethod method = methodCall.resolveMethod();
LOG.assertTrue(method != null);
final PsiType parameterType = method.getParameterList().getParameters()[index].getType();
expression = addCollectToListIfNeed(expression, parameterType, elementFactory);
} else if (parent instanceof PsiReturnStatement) {
return addCollectToListIfNeed(expression, parameterType);
}
else if (parent instanceof PsiReturnStatement) {
final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(parent, PsiMethod.class);
LOG.assertTrue(containingMethod != null);
final PsiType returnType = containingMethod.getReturnType();
expression = addCollectToListIfNeed(expression, returnType, elementFactory);
}
codeStyleManager.shortenClassReferences(expression);
}
private static PsiExpression addCollectToListIfNeed(PsiExpression expression, PsiType type, PsiElementFactory elementFactory) {
if (type instanceof PsiClassType) {
PsiClass resolvedParamClass = ((PsiClassType)type).resolve();
if (resolvedParamClass != null && CommonClassNames.JAVA_LANG_ITERABLE.equals(resolvedParamClass.getQualifiedName())) {
final PsiExpression newExpression =
elementFactory.createExpressionFromText(expression.getText() + ".collect(java.util.stream.Collectors.toList())", null);
return (PsiExpression) expression.replace(newExpression);
}
return addCollectToListIfNeed(expression, returnType);
}
return expression;
}
private PsiExpression addCollectToListIfNeed(PsiExpression expression, PsiType type) {
if (type instanceof PsiClassType && ((PsiClassType)type).rawType().equalsToText(CommonClassNames.JAVA_LANG_ITERABLE)) {
return (PsiExpression)addCollectionToList(expression);
}
return expression;
}
private PsiElement addCollectionToList(PsiElement expression) {
return expression.replace(myElementFactory.createExpressionFromText(expression.getText() + ".collect(java.util.stream.Collectors.toList())", null));
}
private static boolean isIterableMethodParameter(PsiElement listExpression, PsiExpression parameterExpression) {
if (!(listExpression instanceof PsiExpressionList)) {
return false;
@@ -172,28 +167,38 @@ public class GuavaFluentIterableMethodConverters {
return false;
}
final Project project = parameterExpression.getProject();
final PsiClass fluentIterable = JavaPsiFacade.getInstance(project)
.findClass(GuavaFluentIterableInspection.GUAVA_FLUENT_ITERABLE, GlobalSearchScope.allScope(project));
final PsiClass fluentIterable = JavaPsiFacade.getInstance(project).findClass(GuavaFluentIterableInspection.GUAVA_FLUENT_ITERABLE,
listExpression.getResolveScope());
return GuavaFluentIterableInspection.isMethodWithParamAcceptsConversion((PsiMethodCallExpression)listExpression.getParent(), parameterExpression, fluentIterable);
}
@Nullable
private static PsiMethodCallExpression convertMethodCallDeep(PsiElementFactory elementFactory,
@NotNull PsiMethodCallExpression methodCall) {
private PsiMethodCallExpression convertMethodCallDeep(@NotNull PsiMethodCallExpression methodCall) {
PsiMethodCallExpression newMethodCall = methodCall;
PsiMethodCallExpression returnCall = null;
while (true) {
final Pair<PsiMethodCallExpression, Boolean> converted = convertMethodCall(elementFactory, newMethodCall);
if (converted.getSecond()) {
final PsiReferenceExpression methodExpression = newMethodCall.getMethodExpression();
final String name = methodExpression.getReferenceName();
PsiMethodCallExpression converted = convertFromMethodCall(newMethodCall);
if (converted != null) {
return returnCall;
}
if (TO_OTHER_COLLECTION_METHODS.containsKey(name)) {
converted = convertToCollection(newMethodCall, name);
}
else {
final FluentIterableMethodTransformer transformer = METHOD_INDEX.get(name);
LOG.assertTrue(transformer != null, name);
converted = transformer.transform(newMethodCall, myElementFactory);
}
if (converted == null) {
return returnCall;
}
if (returnCall == null) {
returnCall = converted.getFirst();
returnCall = converted;
}
if (converted.getFirst() == null) {
return returnCall;
}
newMethodCall = converted.getFirst();
newMethodCall = converted;
final PsiExpression expression = newMethodCall.getMethodExpression().getQualifierExpression();
if (expression instanceof PsiMethodCallExpression) {
newMethodCall = (PsiMethodCallExpression)expression;
@@ -203,42 +208,30 @@ public class GuavaFluentIterableMethodConverters {
}
}
}
public static Pair<PsiMethodCallExpression, Boolean> convertMethodCall(PsiElementFactory elementFactory, PsiMethodCallExpression methodCall) {
final PsiReferenceExpression methodExpression = methodCall.getMethodExpression();
final String name = methodExpression.getReferenceName();
if (TO_OTHER_COLLECTION_METHODS.containsKey(name)) {
return Pair.create(convertToCollection(methodCall, name, elementFactory), false);
}
else if (GuavaFluentIterableInspection.FLUENT_ITERABLE_FROM.equals(name)) {
private PsiMethodCallExpression convertFromMethodCall(PsiMethodCallExpression methodCall) {
if (GuavaFluentIterableInspection.FLUENT_ITERABLE_FROM.equals(methodCall.getMethodExpression().getReferenceName())) {
final PsiExpression[] argumentList = methodCall.getArgumentList().getExpressions();
LOG.assertTrue(argumentList.length == 1);
final PsiExpression expression = argumentList[0];
final PsiType type = expression.getType();
LOG.assertTrue(type instanceof PsiClassType);
final PsiClass resolvedClass = ((PsiClassType)type).resolve();
final String newExpressionText;
if (InheritanceUtil.isInheritor(resolvedClass, CommonClassNames.JAVA_UTIL_COLLECTION)) {
if (InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_UTIL_COLLECTION)) {
newExpressionText = expression.getText() + ".stream()";
} else {
newExpressionText = "java.util.stream.StreamSupport.stream(" + expression.getText() + ".spliterator(), false)";
}
return Pair.create((PsiMethodCallExpression)methodCall.replace(elementFactory.createExpressionFromText(newExpressionText, null)), true);
}
else {
final FluentIterableMethodTransformer transformer = METHOD_INDEX.get(name);
LOG.assertTrue(transformer != null, name);
final PsiMethodCallExpression transformedExpression = transformer.transform(methodCall, elementFactory);
return Pair.create(transformedExpression, false);
return (PsiMethodCallExpression)methodCall.replace(myElementFactory.createExpressionFromText(newExpressionText, null));
}
return null;
}
private static PsiMethodCallExpression convertToCollection(final PsiMethodCallExpression methodCall,
final String methodName,
final PsiElementFactory elementFactory) {
private PsiMethodCallExpression convertToCollection(final PsiMethodCallExpression methodCall,
final String methodName) {
final PsiExpression[] expressions = methodCall.getArgumentList().getExpressions();
assert expressions.length < 2;
LOG.assertTrue(expressions.length < 2);
String template = TO_OTHER_COLLECTION_METHODS.get(methodName);
if (expressions.length == 1) {
template = String.format(template, expressions[0].getText());
@@ -247,8 +240,7 @@ public class GuavaFluentIterableMethodConverters {
if (qualifier == null) {
return null;
}
final String text = qualifier.getText() + "." + template;
final PsiExpression expression = elementFactory.createExpressionFromText(text, null);
final PsiExpression expression = myElementFactory.createExpressionFromText(qualifier.getText() + "." + template, null);
return (PsiMethodCallExpression)methodCall.replace(expression);
}
}
@@ -22,7 +22,6 @@ import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.impl.PsiDiamondTypeUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.*;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
@@ -156,16 +155,17 @@ class PseudoLambdaReplaceTemplate {
return null;
}
final PsiMethod method = expression.resolveMethod();
if (method == null) {
final JavaResolveResult result = expression.getMethodExpression().advancedResolve(false);
final PsiElement element = result.getElement();
if (!(element instanceof PsiMethod)) {
return null;
}
final PsiParameter[] expectedParameters = method.getParameterList().getParameters();
final PsiParameter[] expectedParameters = ((PsiMethod)element).getParameterList().getParameters();
if (argumentTypes.length != expectedParameters.length) {
return null;
}
final JavaResolveResult result = expression.getMethodExpression().advancedResolve(false);
final PsiSubstitutor methodSubstitutor = result.getSubstitutor();
return validate(argumentTypes, methodReturnType, methodSubstitutor, expression);
}
@@ -202,6 +202,9 @@ class PseudoLambdaReplaceTemplate {
for (int i = 0; i < arguments.length; i++) {
PsiType type = arguments[i];
if (type == null) {
return null;
}
if (isFunction(type, methodReturnType, methodSubstitutor, context)) {
if (lambdaPosition == -1) {
lambdaPosition = i;
@@ -357,8 +360,7 @@ class PseudoLambdaReplaceTemplate {
}
@NotNull
public PsiExpression convertToStream(final PsiMethodCallExpression expression, PsiMethod method, boolean force) {
LOG.assertTrue(expression != null);
public PsiExpression convertToStream(@NotNull final PsiMethodCallExpression expression, @Nullable PsiMethod method, boolean force) {
if (method == null) {
method = expression.resolveMethod();
if (method == null) {
@@ -489,7 +491,16 @@ class PseudoLambdaReplaceTemplate {
LOG.assertTrue(method != null);
return JavaPsiFacade.getElementFactory(expression.getProject()).createExpressionFromText(expression.getText() + "::" + method.getName(), null);
}
return AnonymousCanBeLambdaInspection.replacePsiElementWithLambda(expression, true);
final PsiType psiType = expression.getType();
if (psiType != null) {
PsiNewExpression newArrayExpression = (PsiNewExpression)JavaPsiFacade.getElementFactory(expression.getProject())
.createExpressionFromText("new " + psiType.getCanonicalText() + "[]{" + expression.getText() + "}", expression);
PsiArrayInitializerExpression initializer = newArrayExpression.getArrayInitializer();
LOG.assertTrue(initializer != null);
return AnonymousCanBeLambdaInspection.replacePsiElementWithLambda(initializer.getInitializers()[0], true);
}
return null;
}
@NotNull
@@ -547,15 +558,9 @@ class PseudoLambdaReplaceTemplate {
private static boolean isIterableOrArray(final PsiType type) {
if (type instanceof PsiClassType) {
final PsiClass resolvedClass = ((PsiClassType)type).resolve();
if (resolvedClass != null) {
return InheritanceUtil.isInheritor(resolvedClass, CommonClassNames.JAVA_LANG_ITERABLE);
}
return InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_LANG_ITERABLE);
}
else if (type instanceof PsiArrayType) {
return true;
}
return false;
return type instanceof PsiArrayType;
}
@Override
@@ -15,6 +15,8 @@
*/
package com.intellij.codeInspection.java18StreamApi;
import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInspection.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
@@ -61,47 +63,46 @@ public class StaticPseudoFunctionalStyleMethodInspection extends BaseJavaBatchLo
if (!PsiUtil.isLanguageLevel8OrHigher(holder.getFile())) {
return PsiElementVisitor.EMPTY_VISITOR;
}
return new PsiElementVisitor() {
return new JavaElementVisitor() {
@Override
public void visitElement(PsiElement element) {
if (element instanceof PsiMethodCallExpression) {
final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)element;
String qName = methodCallExpression.getMethodExpression().getQualifiedName();
if (qName == null) {
return;
}
qName = StringUtil.getShortName(qName);
final Collection<StaticPseudoFunctionalStyleMethodOptions.PipelineElement> handlerInfos = myOptions.findElementsByMethodName(qName);
if (handlerInfos.isEmpty()) {
return;
}
final PsiMethod method = methodCallExpression.resolveMethod();
if (method == null) {
return;
}
final PsiClass aClass = method.getContainingClass();
if (aClass == null) {
return;
}
final String classQualifiedName = aClass.getQualifiedName();
if (classQualifiedName == null) {
return;
}
StaticPseudoFunctionalStyleMethodOptions.PipelineElement suitableHandler = null;
for (StaticPseudoFunctionalStyleMethodOptions.PipelineElement h : handlerInfos) {
if (h.getHandlerClass().equals(classQualifiedName)) {
suitableHandler = h;
break;
}
}
if (suitableHandler == null) {
return;
}
final PseudoLambdaReplaceTemplate.ValidationInfo validationInfo = suitableHandler.getTemplate().validate(methodCallExpression);
if (validationInfo != null) {
holder.registerProblem(methodCallExpression.getMethodExpression(), "Pseudo functional style code", new ReplacePseudoLambdaWithLambda(suitableHandler));
public void visitMethodCallExpression(PsiMethodCallExpression methodCallExpression) {
String qName = methodCallExpression.getMethodExpression().getQualifiedName();
if (qName == null) {
return;
}
qName = StringUtil.getShortName(qName);
final Collection<StaticPseudoFunctionalStyleMethodOptions.PipelineElement> handlerInfos = myOptions.findElementsByMethodName(qName);
if (handlerInfos.isEmpty()) {
return;
}
final PsiMethod method = methodCallExpression.resolveMethod();
if (method == null) {
return;
}
final PsiClass aClass = method.getContainingClass();
if (aClass == null) {
return;
}
final String classQualifiedName = aClass.getQualifiedName();
if (classQualifiedName == null) {
return;
}
StaticPseudoFunctionalStyleMethodOptions.PipelineElement suitableHandler = null;
for (StaticPseudoFunctionalStyleMethodOptions.PipelineElement h : handlerInfos) {
if (h.getHandlerClass().equals(classQualifiedName)) {
suitableHandler = h;
break;
}
}
if (suitableHandler == null) {
return;
}
final PseudoLambdaReplaceTemplate.ValidationInfo validationInfo = suitableHandler.getTemplate().validate(methodCallExpression);
if (validationInfo != null) {
holder.registerProblem(methodCallExpression.getMethodExpression(),
"Pseudo functional style code",
new ReplacePseudoLambdaWithLambda(suitableHandler));
}
}
};
}
@@ -128,9 +129,16 @@ public class StaticPseudoFunctionalStyleMethodInspection extends BaseJavaBatchLo
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
PsiMethodCallExpression expression = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiMethodCallExpression.class);
LOG.assertTrue(expression != null);
myHandler.getTemplate().convertToStream(expression, null, false);
final PsiElement psiElement = descriptor.getPsiElement();
if (!FileModificationService.getInstance().preparePsiElementsForWrite(psiElement)) {
return;
}
if (psiElement instanceof PsiReferenceExpression) {
PsiElement parent = psiElement.getParent();
if (parent instanceof PsiMethodCallExpression) {
myHandler.getTemplate().convertToStream((PsiMethodCallExpression)parent, null, false);
}
}
}
}
}
@@ -31,6 +31,8 @@ import java.util.Collections;
* project model. Since importing the changes to IDEA's project model may take a while the method work asynchronously and returns
* {@link Promise} objects which may be used to be notified when the project configuration is finally updated.
*
* @see ProjectModelModifier
*
* @author nik
*/
public abstract class ProjectModelModificationService {
@@ -26,6 +26,10 @@ import java.util.Collection;
/**
* Register implementation of this extension to support custom dependency management system for {@link ProjectModelModificationService}.
* The default implementation which modify IDEA's project model directly is registered as the last extension so it'll be executed if all other
* extensions refuse to handle modification by returning {@code null}.
*
* @see ProjectModelModificationService
*
* @author nik
*/
@@ -26,18 +26,12 @@ import com.intellij.psi.infos.CandidateInfo;
* To change this template use Options | File Templates.
*/
public class ElementExtractorFilter implements ElementFilter{
ElementFilter myFilter;
public ElementExtractorFilter(){}
private final ElementFilter myFilter;
public ElementExtractorFilter(ElementFilter filter){
myFilter = filter;
}
public void setFilter(ElementFilter filter){
myFilter = filter;
}
public ElementFilter getFilter(){
return myFilter;
}
@@ -1,59 +0,0 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.filters.classes;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiManager;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.reference.SoftReference;
import com.intellij.util.ReflectionUtil;
/**
* Created by IntelliJ IDEA.
* User: ik
* Date: 26.03.2003
* Time: 21:01:47
* To change this template use Options | File Templates.
*/
public abstract class ClassAssignableFilter implements ElementFilter{
protected String myClassName = null;
protected PsiClass myClass = null;
private SoftReference myCachedClass = new SoftReference(null);
@Override
public abstract boolean isAcceptable(Object aClass, PsiElement context);
public abstract String toString();
@Override
public boolean isClassAcceptable(Class hintClass){
return ReflectionUtil.isAssignable(PsiClass.class, hintClass);
}
protected PsiClass getPsiClass(PsiManager manager, GlobalSearchScope scope){
if(myClass != null){
return myClass;
}
if(myCachedClass.get() == null && manager != null){
myCachedClass = new SoftReference(JavaPsiFacade.getInstance(manager.getProject()).findClass(myClassName, scope));
}
return (PsiClass) myCachedClass.get();
}
}
@@ -1,43 +0,0 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.filters.classes;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.util.ReflectionUtil;
import org.jetbrains.annotations.NonNls;
public class EnumOrAnnotationTypeFilter implements ElementFilter{
@Override
public boolean isClassAcceptable(Class hintClass){
return ReflectionUtil.isAssignable(PsiClass.class, hintClass);
}
@Override
public boolean isAcceptable(Object element, PsiElement context){
if(element instanceof PsiClass){
return ((PsiClass)element).isEnum() || ((PsiClass)element).isAnnotationType();
}
return false;
}
@NonNls
public String toString(){
return "enum or annotation type";
}
}
@@ -1,44 +0,0 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.filters.classes;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.util.ReflectionUtil;
/**
* Created by IntelliJ IDEA.
* User: ik
* Date: 28.01.2003
* Time: 21:00:45
* To change this template use Options | File Templates.
*/
public class InterfaceFilter implements ElementFilter{
@Override
public boolean isClassAcceptable(Class hintClass){
return ReflectionUtil.isAssignable(PsiClass.class, hintClass);
}
@Override
public boolean isAcceptable(Object element, PsiElement context){
return element instanceof PsiClass && ((PsiClass)element).isInterface();
}
public String toString(){
return "interface";
}
}
@@ -1,53 +0,0 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.filters.getters;
import com.intellij.codeInsight.completion.CompletionContext;
import com.intellij.psi.PsiElement;
import com.intellij.psi.filters.ContextGetter;
import com.intellij.psi.filters.ElementFilter;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: ik
* Date: 15.04.2003
* Time: 17:18:58
* To change this template use Options | File Templates.
*/
public class FilterGetter implements ContextGetter{
private final ContextGetter myBaseGetter;
private final ElementFilter myFilter;
public FilterGetter(ContextGetter baseGetter, ElementFilter filter){
myBaseGetter = baseGetter;
myFilter = filter;
}
@Override
public Object[] get(PsiElement context, CompletionContext completionContext){
final List results = new ArrayList();
final Object[] elements = myBaseGetter.get(context, completionContext);
for (final Object element : elements) {
if (myFilter.isClassAcceptable(element.getClass()) && myFilter.isAcceptable(element, context)) {
results.add(element);
}
}
return results.toArray();
}
}
@@ -15,9 +15,7 @@
*/
package com.intellij.psi.filters.getters;
import com.intellij.codeInsight.completion.CompletionContext;
import com.intellij.psi.*;
import com.intellij.psi.filters.ContextGetter;
import com.intellij.util.IncorrectOperationException;
import java.util.ArrayList;
@@ -30,11 +28,7 @@ import java.util.List;
* Time: 14:02:59
* To change this template use Options | File Templates.
*/
public class ThisGetter implements ContextGetter{
@Override
public Object[] get(PsiElement context, CompletionContext completionContext) {
return getThisExpressionVariants(context).toArray();
}
public class ThisGetter {
public static List<PsiExpression> getThisExpressionVariants(PsiElement context) {
boolean first = true;
@@ -1,52 +0,0 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.filters.position;
import com.intellij.psi.PsiElement;
import com.intellij.psi.filters.ElementFilter;
/**
* Created by IntelliJ IDEA.
* User: ik
* Date: 03.02.2003
* Time: 18:29:13
* To change this template use Options | File Templates.
*/
public class BeforeElementFilter extends PositionElementFilter{
public BeforeElementFilter(ElementFilter filter){
setFilter(filter);
}
public BeforeElementFilter(){}
@Override
public boolean isAcceptable(Object element, PsiElement scope){
if (!(element instanceof PsiElement)) return false;
final PsiElement ownerChild = getOwnerChild(scope, (PsiElement) element);
if(ownerChild == null) return false;
PsiElement currentChild = ownerChild.getNextSibling();
while(currentChild != null){
if(getFilter().isAcceptable(currentChild, scope)){
return true;
}
currentChild = currentChild.getNextSibling();
}
return false;
}
public String toString(){
return "before(" + getFilter().toString() + ")";
}
}
@@ -1,45 +0,0 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.filters.position;
import com.intellij.psi.PsiElement;
import com.intellij.psi.filters.ElementFilter;
/**
* Created by IntelliJ IDEA.
* User: ik
* Date: 25.03.2003
* Time: 12:11:40
* To change this template use Options | File Templates.
*/
public class InsideElementFilter extends PositionElementFilter{
public InsideElementFilter(ElementFilter filter){
setFilter(filter);
}
public InsideElementFilter(){}
@Override
public boolean isAcceptable(Object element, PsiElement scope){
if (!(element instanceof PsiElement)) return false;
PsiElement currentChild = getOwnerChild(scope, (PsiElement) element);
return getFilter().isAcceptable(currentChild, scope);
}
public String toString(){
return "in(" + getFilter().toString() + ")";
}
}
@@ -31,9 +31,7 @@ import com.intellij.util.ReflectionUtil;
* To change this template use Options | File Templates.
*/
public class TokenTypeFilter implements ElementFilter{
private IElementType myType = null;
public TokenTypeFilter(){}
private final IElementType myType;
public TokenTypeFilter(IElementType type){
myType = type;
@@ -42,8 +42,6 @@ public class AssignableFromFilter implements ElementFilter{
myClassName = className;
}
public AssignableFromFilter(){}
@Override
public boolean isClassAcceptable(Class hintClass){
return true;
@@ -31,11 +31,6 @@ import com.intellij.psi.filters.OrFilter;
* To change this template use Options | File Templates.
*/
public class AssignableGroupFilter extends OrFilter implements InitializableFilter{
public AssignableGroupFilter(){}
public AssignableGroupFilter(PsiClass[] classes){
init(classes);
}
@Override
public void init(Object[] classes){
@@ -69,6 +69,23 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
private Map<IElementType, Wrap> myPreferredWraps;
private AbstractJavaBlock myParentBlock;
private BlockFactory myBlockFactory = new BlockFactory() {
@Override
public Block createBlock(ASTNode node, Indent indent, Alignment alignment, Wrap wrap) {
return new SimpleJavaBlock(node, wrap, AlignmentStrategy.wrap(alignment), indent, mySettings, myJavaSettings);
}
@Override
public CommonCodeStyleSettings getSettings() {
return mySettings;
}
@Override
public JavaCodeStyleSettings getJavaSettings() {
return myJavaSettings;
}
};
protected AbstractJavaBlock(@NotNull final ASTNode node,
final Wrap wrap,
final Alignment alignment,
@@ -476,12 +493,11 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
if (nodeType == JavaElementType.POLYADIC_EXPRESSION) nodeType = JavaElementType.BINARY_EXPRESSION;
if (childType == JavaTokenType.LBRACE && nodeType == JavaElementType.ARRAY_INITIALIZER_EXPRESSION) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.ARRAY_INITIALIZER_WRAP), false);
child = processParenthesisBlock(JavaTokenType.LBRACE, JavaTokenType.RBRACE,
result,
child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION);
ArrayInitializerBlocksBuilder builder = new ArrayInitializerBlocksBuilder(myNode, myBlockFactory);
List<Block> newlyCreated = builder.buildBlocks();
child = myNode.getLastChildNode();
result.addAll(newlyCreated);
}
else if (childType == JavaTokenType.LBRACE && nodeType == JavaElementType.ANNOTATION_ARRAY_INITIALIZER) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.ARRAY_INITIALIZER_WRAP), false);
@@ -514,10 +530,11 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
mySettings.ALIGN_MULTILINE_RESOURCES);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.ANNOTATION_PARAMETER_LIST) {
Wrap wrap = Wrap.createWrap(getWrapType(myJavaSettings.ANNOTATION_PARAMETER_WRAP), false);
child = processParenthesisBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
myJavaSettings.ALIGN_MULTILINE_ANNOTATION_PARAMETERS);
AnnotationInitializerBlocksBuilder builder = new AnnotationInitializerBlocksBuilder(myNode, myBlockFactory);
List<Block> newlyCreated = builder.buildBlocks();
child = myNode.getLastChildNode();
result.addAll(newlyCreated);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARENTH_EXPRESSION) {
child = processParenthesisBlock(result, child,
@@ -0,0 +1,75 @@
/*
* 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.formatter.java;
import com.intellij.formatting.Alignment;
import com.intellij.formatting.Block;
import com.intellij.formatting.Indent;
import com.intellij.formatting.Wrap;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNameValuePair;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.codeStyle.JavaCodeStyleSettings;
import com.intellij.psi.util.PsiTreeUtil;
import java.util.List;
import static com.intellij.psi.formatter.java.JavaFormatterUtil.getWrapType;
public class AnnotationInitializerBlocksBuilder {
private final BlockFactory myFactory;
private final ASTNode myNode;
private final JavaCodeStyleSettings myJavaSettings;
public AnnotationInitializerBlocksBuilder(ASTNode node, BlockFactory factory) {
myNode = node;
myFactory = factory;
myJavaSettings = myFactory.getJavaSettings();
}
public List<Block> buildBlocks() {
final Wrap wrap = Wrap.createWrap(getWrapType(myJavaSettings.ANNOTATION_PARAMETER_WRAP), false);
final Alignment alignment = myJavaSettings.ALIGN_MULTILINE_ANNOTATION_PARAMETERS ? Alignment.createAlignment() : null;
ChildrenBlocksBuilder.Config config = new ChildrenBlocksBuilder.Config()
.setDefaultIndent(Indent.getContinuationWithoutFirstIndent())
.setIndent(JavaTokenType.RPARENTH, Indent.getNoneIndent())
.setIndent(JavaTokenType.LPARENTH, Indent.getNoneIndent())
.setDefaultWrap(wrap)
.setNoWrap(JavaTokenType.COMMA)
.setNoWrap(JavaTokenType.RPARENTH)
.setNoWrap(JavaTokenType.LPARENTH)
.setDefaultAlignment(alignment)
.setNoAlignment(JavaTokenType.COMMA)
.setNoAlignment(JavaTokenType.LPARENTH)
.setNoAlignmentIf(JavaTokenType.RPARENTH, new Condition<ASTNode>() {
@Override
public boolean value(ASTNode node) {
PsiElement prev = PsiTreeUtil.skipSiblingsBackward(node.getPsi(), PsiWhiteSpace.class);
if (prev == null) return false;
return prev instanceof PsiNameValuePair && !PsiTreeUtil.hasErrorElements(prev);
}
});
return config.createBuilder().buildNodeChildBlocks(myNode, myFactory);
}
}
@@ -0,0 +1,73 @@
/*
* 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.formatter.java;
import com.intellij.formatting.Alignment;
import com.intellij.formatting.Block;
import com.intellij.formatting.Indent;
import com.intellij.formatting.Wrap;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.util.PsiTreeUtil;
import java.util.List;
import static com.intellij.psi.formatter.java.JavaFormatterUtil.getWrapType;
public class ArrayInitializerBlocksBuilder {
private final ASTNode myNode;
private final BlockFactory myBlockFactory;
private final CommonCodeStyleSettings mySettings;
public ArrayInitializerBlocksBuilder(ASTNode node, BlockFactory blockFactory) {
myNode = node;
myBlockFactory = blockFactory;
mySettings = myBlockFactory.getSettings();
}
public List<Block> buildBlocks() {
Wrap wrap = Wrap.createWrap(getWrapType(mySettings.ARRAY_INITIALIZER_WRAP), false);
Alignment alignment = mySettings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION ? Alignment.createAlignment() : null;
ChildrenBlocksBuilder.Config config = new ChildrenBlocksBuilder.Config()
.setDefaultIndent(Indent.getContinuationWithoutFirstIndent())
.setIndent(JavaTokenType.RBRACE, Indent.getNoneIndent())
.setIndent(JavaTokenType.LBRACE, Indent.getNoneIndent())
.setDefaultWrap(wrap)
.setNoWrap(JavaTokenType.COMMA)
.setNoWrap(JavaTokenType.RBRACE)
.setNoWrap(JavaTokenType.LBRACE)
.setDefaultAlignment(alignment)
.setNoAlignment(JavaTokenType.COMMA)
.setNoAlignment(JavaTokenType.LBRACE)
.setNoAlignmentIf(JavaTokenType.RBRACE, new Condition<ASTNode>() {
@Override
public boolean value(ASTNode node) {
PsiElement prev = PsiTreeUtil.skipSiblingsBackward(node.getPsi(), PsiWhiteSpace.class);
if (prev == null) return false;
return prev.getNode().getElementType() != JavaTokenType.COMMA;
}
});
return config.createBuilder().buildNodeChildBlocks(myNode, myBlockFactory);
}
}
@@ -17,9 +17,7 @@ package com.intellij.psi.formatter.java;
import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.PsiStatement;
import com.intellij.psi.PsiTypeElement;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.codeStyle.JavaCodeStyleSettings;
import com.intellij.psi.formatter.FormatterUtil;
@@ -255,8 +253,8 @@ public class BlockContainingJavaBlock extends AbstractJavaBlock{
if (prevBlock instanceof ASTBlock && nextBlock instanceof ASTBlock) {
ASTNode prevNode = ((ASTBlock)prevBlock).getNode();
ASTNode nextNode = ((ASTBlock)nextBlock).getNode();
if (prevNode != null && nextNode != null && prevNode.getElementType() == JavaTokenType.RPARENTH
&& nextNode.getElementType() != JavaTokenType.LBRACE)
if (prevNode != null && nextNode != null && prevNode.getElementType() == JavaTokenType.RPARENTH
&& nextNode.getElementType() != JavaTokenType.LBRACE)
{
useExternalIndent = true;
}
@@ -267,7 +265,7 @@ public class BlockContainingJavaBlock extends AbstractJavaBlock{
return new ChildAttributes(getCodeBlockChildExternalIndent(newChildIndex), null);
}
else {
return new ChildAttributes(myIndentsBefore.get(newChildIndex), null);
return new ChildAttributes(myIndentsBefore.get(newChildIndex), getUsedAlignment(newChildIndex));
}
}
@@ -0,0 +1,34 @@
/*
* 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.formatter.java;
import com.intellij.formatting.Alignment;
import com.intellij.formatting.Block;
import com.intellij.formatting.Indent;
import com.intellij.formatting.Wrap;
import com.intellij.lang.ASTNode;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.codeStyle.JavaCodeStyleSettings;
public interface BlockFactory {
Block createBlock(ASTNode node, Indent indent, Alignment alignment, Wrap wrap);
CommonCodeStyleSettings getSettings();
JavaCodeStyleSettings getJavaSettings();
}
@@ -0,0 +1,144 @@
/*
* 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.formatter.java;
import com.intellij.formatting.Alignment;
import com.intellij.formatting.Block;
import com.intellij.formatting.Indent;
import com.intellij.formatting.Wrap;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.formatter.FormatterUtil;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
public class ChildrenBlocksBuilder {
private Config myConfig;
private ChildrenBlocksBuilder(Config builder) {
myConfig = builder;
}
public List<Block> buildNodeChildBlocks(ASTNode node, BlockFactory factory) {
List<Block> blocks = ContainerUtil.newArrayList();
for (ASTNode child : node.getChildren(null)) {
if (FormatterUtil.isWhitespaceOrEmpty(child) || child.getTextLength() == 0) {
continue;
}
Alignment alignment = myConfig.getAlignment(child);
IElementType type = child.getElementType();
Indent indent = myConfig.getIndent(type);
Wrap wrap = myConfig.getWrap(type);
blocks.add(factory.createBlock(child, indent, alignment, wrap));
}
return blocks;
}
public static class Config {
private static final Alignment NO_ALIGNMENT = Alignment.createAlignment();
private static final Wrap NO_WRAP = Wrap.createWrap(0, false);
private Map<IElementType, Alignment> myAlignments = ContainerUtil.newHashMap();
private Map<IElementType, Indent> myIndents = ContainerUtil.newHashMap();
private Map<IElementType, Wrap> myWraps = ContainerUtil.newHashMap();
private Map<IElementType, Condition<ASTNode>> myNoneAlignmentCondition = ContainerUtil.newHashMap();
private Alignment myDefaultAlignment;
private Indent myDefaultIndent;
private Wrap myDefaultWrap;
public ChildrenBlocksBuilder createBuilder() {
return new ChildrenBlocksBuilder(this);
}
public Config setDefaultAlignment(Alignment alignment) {
myDefaultAlignment = alignment;
return this;
}
public Config setDefaultWrap(Wrap wrap) {
myDefaultWrap = wrap;
return this;
}
public Config setDefaultIndent(Indent indent) {
myDefaultIndent = indent;
return this;
}
public Config setAlignment(@NotNull IElementType elementType, @NotNull Alignment alignment) {
myAlignments.put(elementType, alignment);
return this;
}
public Config setNoAlignment(IElementType elementType) {
myAlignments.put(elementType, NO_ALIGNMENT);
return this;
}
public Config setNoAlignmentIf(IElementType elementType, Condition<ASTNode> applyAlignCondition) {
myNoneAlignmentCondition.put(elementType, applyAlignCondition);
return this;
}
public Config setIndent(IElementType elementType, Indent indent) {
myIndents.put(elementType, indent);
return this;
}
private Indent getIndent(IElementType elementType) {
Indent indent = myIndents.get(elementType);
return indent != null ? indent : myDefaultIndent;
}
private Alignment getAlignment(ASTNode node) {
IElementType elementType = node.getElementType();
Condition<ASTNode> noneAlignmentCondition = myNoneAlignmentCondition.get(elementType);
if (noneAlignmentCondition != null && noneAlignmentCondition.value(node)) {
return null;
}
Alignment alignment = myAlignments.get(elementType);
if (alignment == null) {
return myDefaultAlignment;
}
return alignment == NO_ALIGNMENT ? null : alignment;
}
private Wrap getWrap(IElementType elementType) {
Wrap wrap = myWraps.get(elementType);
if (wrap == NO_WRAP) return null;
return wrap != null ? wrap : myDefaultWrap;
}
public Config setNoWrap(IElementType elementType) {
myWraps.put(elementType, NO_WRAP);
return this;
}
}
}
@@ -333,8 +333,8 @@ public class ConvertToInstanceMethodProcessor extends BaseRefactoringProcessor {
final PsiReference reference = usage.getReferenceExpression();
if (reference instanceof PsiReferenceExpression) {
final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)reference;
if (referenceExpression.getParent() instanceof PsiReferenceExpression) {
// todo: check for correctness
PsiElement parent = referenceExpression.getParent();
if (parent instanceof PsiReferenceExpression && sameUnqualified(parent)) {
referenceExpression.delete();
}
else {
@@ -350,6 +350,16 @@ public class ConvertToInstanceMethodProcessor extends BaseRefactoringProcessor {
}
}
private static boolean sameUnqualified(PsiElement parent) {
PsiElement resolve = ((PsiReferenceExpression)parent).resolve();
if (resolve instanceof PsiField) {
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(resolve.getProject());
final PsiExpression unqualifiedFieldReference = elementFactory.createExpressionFromText(((PsiField)resolve).getName(), parent);
return resolve == ((PsiReferenceExpression)unqualifiedFieldReference).resolve();
}
return true;
}
private void processMethodCall(MethodCallUsageInfo usageInfo) throws IncorrectOperationException {
PsiMethodCallExpression methodCall = usageInfo.getMethodCall();
PsiParameterList parameterList = myMethod.getParameterList();
@@ -108,13 +108,6 @@ public class JavaInvertBooleanDelegate extends InvertBooleanDelegate {
elementsToInvert.add(refElement);
}
}
if (namedElement instanceof PsiVariable) {
final PsiExpression initializer = ((PsiVariable)namedElement).getInitializer();
if (initializer != null) {
elementsToInvert.add(initializer);
}
}
}
public PsiElement getElementToInvert(PsiElement namedElement, PsiElement element) {
@@ -172,16 +165,21 @@ public class JavaInvertBooleanDelegate extends InvertBooleanDelegate {
}
@Override
public void invertDefaultElementInitializer(final PsiElement element) {
public void invertElementInitializer(final PsiElement element) {
if (element instanceof PsiField && ((PsiField)element).getInitializer() == null) {
((PsiField)element).setInitializer(JavaPsiFacade.getElementFactory(element.getProject()).createExpressionFromText("true", element));
} else if (element instanceof PsiVariable) {
final PsiExpression initializer = ((PsiVariable)element).getInitializer();
if (initializer != null) {
replaceWithNegatedExpression(initializer);
}
}
}
public void collectRefElements(final PsiElement element,
final Collection<PsiElement> elementsToInvert,
final RenameProcessor renameProcessor,
@NotNull final String newName) {
@NotNull final String newName,
final Collection<PsiElement> elementsToInvert) {
collectRefsToInvert(element, elementsToInvert);
if (element instanceof PsiMethod) {
@@ -255,7 +253,7 @@ public class JavaInvertBooleanDelegate extends InvertBooleanDelegate {
}
@Override
public void findConflicts(MultiMap<PsiElement, String> conflicts, UsageInfo[] usageInfos) {
public void findConflicts(UsageInfo[] usageInfos, MultiMap<PsiElement, String> conflicts) {
for (UsageInfo info : usageInfos) {
final PsiElement element = info.getElement();
if (element instanceof PsiMethodReferenceExpression) {
@@ -16,16 +16,23 @@
package com.intellij.testIntegration;
import com.intellij.codeInsight.TestFrameworks;
import com.intellij.execution.TestStateStorage;
import com.intellij.execution.lineMarker.ExecutorAction;
import com.intellij.execution.lineMarker.RunLineMarkerContributor;
import com.intellij.execution.testframework.TestIconMapper;
import com.intellij.execution.testframework.sm.runner.states.TestStateInfo;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiIdentifier;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.Function;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
/**
* @author Dmitry Avdeev
*/
@@ -46,7 +53,8 @@ public class TestRunLineMarkerProvider extends RunLineMarkerContributor {
if (element instanceof PsiClass) {
TestFramework framework = TestFrameworks.detectFramework((PsiClass)element);
if (framework != null && framework.isTestClass(element)) {
return new Info(framework.getIcon(), TOOLTIP_PROVIDER, ExecutorAction.getActions(1));
String url = "java:suite://" + ((PsiClass)element).getQualifiedName();
return getInfo(url, framework, e.getProject());
}
}
if (element instanceof PsiMethod) {
@@ -54,8 +62,8 @@ public class TestRunLineMarkerProvider extends RunLineMarkerContributor {
if (psiClass != null) {
TestFramework framework = TestFrameworks.detectFramework(psiClass);
if (framework != null && framework.isTestMethod(element)) {
// String url = "java:test://" + psiClass.getQualifiedName() + "." + ((PsiMethod)element).getName();
return new Info(framework.getIcon(), TOOLTIP_PROVIDER, ExecutorAction.getActions(1));
String url = "java:test://" + psiClass.getQualifiedName() + "." + ((PsiMethod)element).getName();
return getInfo(url, framework, e.getProject());
}
}
}
@@ -63,7 +71,20 @@ public class TestRunLineMarkerProvider extends RunLineMarkerContributor {
return null;
}
@NotNull
protected Info getInfo(String url, TestFramework framework, Project project) {
Icon icon = getTestStateIcon(url, project);
return new Info(icon == null ? framework.getIcon() : icon, TOOLTIP_PROVIDER, ExecutorAction.getActions(1));
}
protected boolean isIdentifier(PsiElement e) {
return e instanceof PsiIdentifier;
}
private static Icon getTestStateIcon(String url, Project project) {
TestStateStorage.Record state = TestStateStorage.getInstance(project).getState(url);
if (state == null) return null;
TestStateInfo.Magnitude magnitude = TestIconMapper.getMagnitude(state.magnitude);
return TestIconMapper.getIcon(magnitude);
}
}
@@ -1301,29 +1301,39 @@ class ControlFlowAnalyzer extends JavaElementVisitor {
if (rExpr != null) {
rExpr.accept(this);
}
final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)lExpr;
PsiExpression qualifierExpression = referenceExpression.getQualifierExpression();
PsiVariable variable = getUsedVariable(referenceExpression);
if (qualifierExpression == null ||
qualifierExpression instanceof PsiThisExpression ||
variable instanceof PsiField && variable.hasModifierProperty(PsiModifier.STATIC)) {
if (variable != null) {
if (myAssignmentTargetsAreElements) {
startElement(lExpr);
}
if (expression.getOperationTokenType() != JavaTokenType.EQ) {
generateReadInstruction(variable);
}
generateWriteInstruction(variable);
if (myAssignmentTargetsAreElements) finishElement(lExpr);
PsiVariable variable = getUsedVariable((PsiReferenceExpression)lExpr);
if (variable != null) {
if (myAssignmentTargetsAreElements) {
startElement(lExpr);
}
if (expression.getOperationTokenType() != JavaTokenType.EQ) {
generateReadInstruction(variable);
}
generateWriteInstruction(variable);
if (myAssignmentTargetsAreElements) finishElement(lExpr);
}
else {
lExpr.accept(this); //?
}
}
else if (lExpr instanceof PsiArrayAccessExpression &&
((PsiArrayAccessExpression)lExpr).getArrayExpression() instanceof PsiReferenceExpression){
PsiVariable variable = getUsedVariable((PsiReferenceExpression)((PsiArrayAccessExpression)lExpr).getArrayExpression());
if (variable != null) {
generateReadInstruction(variable);
final PsiExpression indexExpression = ((PsiArrayAccessExpression)lExpr).getIndexExpression();
if (indexExpression != null) {
indexExpression.accept(this);
}
} else {
lExpr.accept(this);
}
if (rExpr != null) {
rExpr.accept(this);
}
}
else if (lExpr != null) {
lExpr.accept(this);
if (rExpr != null) {
@@ -1,84 +0,0 @@
/*
* 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.impl;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiSubstitutor;
import com.intellij.psi.PsiType;
import com.intellij.psi.PsiTypeParameter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
public class DelegateSubstitutor implements PsiSubstitutor {
private final @NotNull PsiSubstitutor myDelegate;
public DelegateSubstitutor(@NotNull PsiSubstitutor delegate) {
myDelegate = delegate;
}
@Override
@Nullable
public PsiType substitute(@NotNull PsiTypeParameter typeParameter) {
return myDelegate.substitute(typeParameter);
}
@Override
public PsiType substitute(@Nullable PsiType type) {
return myDelegate.substitute(type);
}
@Override
public PsiType substituteWithBoundsPromotion(@NotNull PsiTypeParameter typeParameter) {
return myDelegate.substituteWithBoundsPromotion(typeParameter);
}
@Override
@NotNull
public PsiSubstitutor put(@NotNull PsiTypeParameter classParameter, PsiType mapping) {
return myDelegate.put(classParameter, mapping);
}
@Override
@NotNull
public PsiSubstitutor putAll(@NotNull PsiClass parentClass, PsiType[] mappings) {
return myDelegate.putAll(parentClass, mappings);
}
@Override
@NotNull
public PsiSubstitutor putAll(@NotNull PsiSubstitutor another) {
return myDelegate.putAll(another);
}
@Override
@NotNull
public Map<PsiTypeParameter, PsiType> getSubstitutionMap() {
return myDelegate.getSubstitutionMap();
}
@Override
public boolean isValid() {
return myDelegate.isValid();
}
@Override
public void ensureValid() {
myDelegate.ensureValid();
}
}
@@ -313,9 +313,8 @@ public class PsiSuperMethodImplUtil {
return false;
}
if (superMethod.hasModifierProperty(PsiModifier.DEFAULT) ||
method.hasModifierProperty(PsiModifier.DEFAULT)) {
return !InheritanceUtil.isInheritorOrSelf(superClass, containingClass, true);
if (superMethod.hasModifierProperty(PsiModifier.DEFAULT) || method.hasModifierProperty(PsiModifier.DEFAULT)) {
return superMethod.equals(method) || !InheritanceUtil.isInheritorOrSelf(superClass, containingClass, true);
}
return true;
}
@@ -1290,10 +1290,9 @@ public class InferenceSession {
// the type to search is the result of capture conversion (5.1.10) applied to T;
// otherwise, the type to search is the same as the type of the first search. Again, the type arguments, if any, are given by the method reference.
if (PsiUtil.isRawSubstitutor(containingClass, psiSubstitutor)) {
final PsiClassType.ClassResolveResult pResult = PsiUtil.resolveGenericsClassInType(PsiImplUtil.normalizeWildcardTypeByPosition(pType, (PsiExpression)myContext));
final PsiClass pClass = pResult.getElement();
final PsiSubstitutor receiverSubstitutor = pClass != null ? TypeConversionUtil
.getClassSubstitutor(containingClass, pClass, pResult.getSubstitutor()) : null;
PsiType normalizedPType = PsiImplUtil.normalizeWildcardTypeByPosition(pType, (PsiExpression)myContext);
final PsiSubstitutor receiverSubstitutor = PsiMethodReferenceCompatibilityConstraint
.getParameterizedTypeSubstitutor(containingClass, normalizedPType);
if (receiverSubstitutor != null) {
if (!method.hasTypeParameters()) {
if (signature.getParameterTypes().length == 1 || PsiUtil.isRawSubstitutor(containingClass, receiverSubstitutor)) {
@@ -22,10 +22,7 @@ import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfacePa
import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession;
import com.intellij.psi.impl.source.resolve.graphInference.PsiPolyExpressionUtil;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.util.MethodSignature;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.psi.util.*;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nullable;
@@ -219,13 +216,8 @@ public class PsiMethodReferenceCompatibilityConstraint implements ConstraintForm
// otherwise, the type to search is the same as the type of the first search. Again, the type arguments, if any, are given by the method reference.
if ( PsiUtil.isRawSubstitutor(qContainingClass, psiSubstitutor)) {
if (member instanceof PsiMethod && PsiMethodReferenceUtil.isSecondSearchPossible(signature.getParameterTypes(), qualifierResolveResult, myExpression)) {
final PsiType pType = signature.getParameterTypes()[0];
PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(
PsiImplUtil.normalizeWildcardTypeByPosition(pType, myExpression));
PsiClass paramClass = resolveResult.getElement();
LOG.assertTrue(paramClass != null);
psiSubstitutor = TypeConversionUtil.getClassSubstitutor(qContainingClass, paramClass, resolveResult.getSubstitutor());
LOG.assertTrue(psiSubstitutor != null);
final PsiType pType = PsiImplUtil.normalizeWildcardTypeByPosition(signature.getParameterTypes()[0], myExpression);
psiSubstitutor = getParameterizedTypeSubstitutor(qContainingClass, pType);
}
else if (member instanceof PsiMethod && ((PsiMethod)member).isConstructor() || member instanceof PsiClass) {
//15.13.1
@@ -253,6 +245,24 @@ public class PsiMethodReferenceCompatibilityConstraint implements ConstraintForm
return psiSubstitutor;
}
public static PsiSubstitutor getParameterizedTypeSubstitutor(PsiClass qContainingClass, PsiType pType) {
if (pType instanceof PsiIntersectionType) {
for (PsiType type : ((PsiIntersectionType)pType).getConjuncts()) {
PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(type);
if (InheritanceUtil.isInheritorOrSelf(resolveResult.getElement(), qContainingClass, true)) {
return getParameterizedTypeSubstitutor(qContainingClass, type);
}
}
}
PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(pType);
PsiClass paramClass = resolveResult.getElement();
LOG.assertTrue(paramClass != null);
PsiSubstitutor psiSubstitutor = TypeConversionUtil.getClassSubstitutor(qContainingClass, paramClass, resolveResult.getSubstitutor());
LOG.assertTrue(psiSubstitutor != null);
return psiSubstitutor;
}
@Override
public void apply(PsiSubstitutor substitutor, boolean cache) {
myT = substitutor.substitute(myT);
@@ -0,0 +1,2 @@
class A<T> <caret> {
}
@@ -0,0 +1,5 @@
@interface AbcdAnno {}
class Foo {
void foo(@Abc<caret>Foo f) {}
}
@@ -0,0 +1,5 @@
@interface AbcdAnno {}
class Foo {
void foo(@AbcdAnno<caret> Foo f) {}
}
@@ -0,0 +1,8 @@
class Main {
public void test() {
double[] d = new double[si<caret>];
}
int size();
int size2();
}
@@ -0,0 +1,8 @@
class Main {
public void test() {
double[] d = new double[size()];<caret>
}
int size();
int size2();
}
@@ -0,0 +1,31 @@
class Test {
String[] days = {"",""};
public static void foo1() {
for (; ; ) {
break;
<error descr="Unreachable statement">new Test().days = null;</error>
}
}
void bar1() {
for (; ; ) {
break;
<error descr="Unreachable statement">days = null;</error>
}
}
static void foo2() {
for (; ; ) {
break;
<error descr="Unreachable statement">new Test().days[0] = null;</error>
}
}
void bar2() {
for (;;) {
break;
<error descr="Unreachable statement">days[0] = null;</error>
}
}
}
@@ -12,3 +12,12 @@ interface F {
}
interface <error descr="G inherits abstract and default for foo() from types E and F">G</error> extends E, F {}
interface H {
default void m() {}
}
interface K {
default void m() {}
}
class L implements H {}
class <error descr="M inherits unrelated defaults for m() from types H and K">M</error> extends L implements H, K {}
@@ -0,0 +1,23 @@
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
abstract class Constraint<ConstraintType extends Constraint<ConstraintType>> {
protected abstract Stream<Event> evStream();
private void foo(final Set<CConstraint> ctrlSTCs,
final Set<BConstraint> probCstrs) {
ArrayList<Event> a = new ArrayList<Event>(Stream
.concat(ctrlSTCs.stream(), probCstrs.stream())
.flatMap(Constraint::evStream)
.collect(Collectors.toSet()));
}
private abstract class CConstraint extends Constraint<CConstraint> implements I {}
private abstract class BConstraint extends Constraint<BConstraint> implements I {}
interface I {}
interface Event {}
}
@@ -0,0 +1,13 @@
// "Replace 'switch' with 'if'" "true"
class Precedence {
void m() {
int a = 10;
if ((a & 1) == 0) {
System.out.println("0");
} else if ((a & 1) == 1) {
System.out.println("1");
}
}
}
@@ -0,0 +1,14 @@
// "Replace 'switch' with 'if'" "true"
class Precedence {
void m() {
int a = 10;
switch<caret>(a & 1) {
case 0:
System.out.println("0");
break;
case 1:
System.out.println("1");
}
}
}
@@ -0,0 +1,17 @@
package z;
interface FileType {
String getName();
}
abstract class LanguageFileType implements FileType {
}
abstract class OCBaseLanguageFileType extends LanguageFileType {
public String <caret>getName() {
return "";
}
}
public class XibFileType extends OCBaseLanguageFileType implements FileType {
}
@@ -27,6 +27,6 @@ searchInProjectFiles =false
[[<a>]]b
--
RangeHighlighter: (0,1); layer:5999; tooltip: null : [null,java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
RangeHighlighter: (0,1); layer:5999; tooltip: null : [java.awt.Color[r=0,g=0,b=0],java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
RangeHighlighter: (0,1); layer:5999; tooltip: null : [null,null,0,ROUNDED_BOX,java.awt.Color[r=0,g=0,b=0],null]
------------
@@ -28,9 +28,9 @@ searchInProjectFiles =false
[[<a>]]
[a]b
--
RangeHighlighter: (0,1); layer:5999; tooltip: null : [null,java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
RangeHighlighter: (0,1); layer:5999; tooltip: null : [java.awt.Color[r=0,g=0,b=0],java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
RangeHighlighter: (0,1); layer:5999; tooltip: null : [null,null,0,ROUNDED_BOX,java.awt.Color[r=0,g=0,b=0],null]
RangeHighlighter: (2,3); layer:5999; tooltip: null : [null,java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
RangeHighlighter: (2,3); layer:5999; tooltip: null : [java.awt.Color[r=0,g=0,b=0],java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
------------
--- FIND MODEL ---
myStringToFind =ab
@@ -62,7 +62,7 @@ searchInProjectFiles =false
a
[[<ab>]]
--
RangeHighlighter: (2,4); layer:5999; tooltip: null : [null,java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
RangeHighlighter: (2,4); layer:5999; tooltip: null : [java.awt.Color[r=0,g=0,b=0],java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
RangeHighlighter: (2,4); layer:5999; tooltip: null : [null,null,0,ROUNDED_BOX,java.awt.Color[r=0,g=0,b=0],null]
------------
--- FIND MODEL ---
@@ -95,7 +95,7 @@ searchInProjectFiles =false
[[<a>]]
[a]b
--
RangeHighlighter: (0,1); layer:5999; tooltip: null : [null,java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
RangeHighlighter: (0,1); layer:5999; tooltip: null : [java.awt.Color[r=0,g=0,b=0],java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
RangeHighlighter: (0,1); layer:5999; tooltip: null : [null,null,0,ROUNDED_BOX,java.awt.Color[r=0,g=0,b=0],null]
RangeHighlighter: (2,3); layer:5999; tooltip: null : [null,java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
RangeHighlighter: (2,3); layer:5999; tooltip: null : [java.awt.Color[r=0,g=0,b=0],java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
------------
@@ -57,7 +57,7 @@ searchInProjectFiles =false
[[<a>]]
--
RangeHighlighter: (0,1); layer:5999; tooltip: null : [null,java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
RangeHighlighter: (0,1); layer:5999; tooltip: null : [java.awt.Color[r=0,g=0,b=0],java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
RangeHighlighter: (0,1); layer:5999; tooltip: null : [null,null,0,ROUNDED_BOX,java.awt.Color[r=0,g=0,b=0],null]
------------
--- FIND MODEL ---
@@ -91,7 +91,7 @@ Replacement Preview: <Empty string>
[[<a>]]
--
RangeHighlighter: (0,1); layer:5999; tooltip: null : [null,java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
RangeHighlighter: (0,1); layer:5999; tooltip: null : [java.awt.Color[r=0,g=0,b=0],java.awt.Color[r=255,g=255,b=0],0,BOXED,null,java.awt.Color[r=113,g=179,b=98]]
RangeHighlighter: (0,1); layer:5999; tooltip: null : [null,null,0,ROUNDED_BOX,java.awt.Color[r=0,g=0,b=0],null]
------------
--- FIND MODEL ---
@@ -0,0 +1,15 @@
class Foo {
public String bar;
private String baz;
public static void set<caret>Bar(Foo foo, String bar) {
foo.bar = bar;
foo.baz = bar;
foo.bar();
}
private void bar() {
}
}
@@ -0,0 +1,15 @@
class Foo {
public String bar;
private String baz;
public void setBar(String bar) {
this.bar = bar;
baz = bar;
bar();
}
private void bar() {
}
}
@@ -1,8 +1,8 @@
public class A {
public void testInlineRefactoring() {
int[] array = ar();
arr<caret>ay[1] = 22;
int[] ar<caret>ray = ar();
array[1] = 22;
}
private int[] ar() {
@@ -545,4 +545,13 @@ class Test {
registrar.unregisterReferenceProvider(PsiDocTag.class, provider);
}
}
public void "test complete author name"() {
def userName = SystemProperties.userName
assert userName
myFixture.configureByText 'a.java', "/** @author <caret> */"
myFixture.completeBasic()
myFixture.type('\n')
myFixture.checkResult "/** @author $userName<caret> */"
}
}
@@ -64,6 +64,7 @@ public class KeywordCompletionTest extends LightCompletionTestCase {
public void testExtends11() throws Exception { doTest(false); }
public void testExtends12() throws Exception { doTest(false); }
public void testExtends13() throws Exception { doTest(false); }
public void testExtendsAfterClassGenerics() throws Exception { doTest(2, "extends", "implements"); }
public void testSynchronized1() throws Exception { doTest(false); }
public void testSynchronized2() throws Exception {
@@ -935,6 +935,7 @@ public class ListUtils {
public void testSmartEnterNoNewLine() { doTest(Lookup.COMPLETE_STATEMENT_SELECT_CHAR as String) }
public void testSmartEnterWithNewLine() { doTest(Lookup.COMPLETE_STATEMENT_SELECT_CHAR as String) }
public void testSmartEnterGuessArgumentCount() throws Throwable { doTest(Lookup.COMPLETE_STATEMENT_SELECT_CHAR as String) }
public void testSmartEnterInsideArrayBrackets() { doTest(Lookup.COMPLETE_STATEMENT_SELECT_CHAR as String) }
public void testTabReplacesMethodNameWithLocalVariableName() throws Throwable { doTest('\t'); }
public void testMethodParameterAnnotationClass() throws Throwable { doTest(); }
@@ -1004,6 +1005,7 @@ public class ListUtils {
public void testOnlyAnnotationsAfterAt() throws Throwable { doTest() }
public void testOnlyAnnotationsAfterAt2() throws Throwable { doTest('\n') }
public void testAnnotationBeforeIdentifier() { doTest('\n') }
public void testOnlyExceptionsInCatch1() throws Exception { doTest('\n') }
public void testOnlyExceptionsInCatch2() throws Exception { doTest('\n') }
@@ -1,9 +1,7 @@
package com.intellij.codeInsight.completion;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.lookup.LookupElementDecorator;
import com.intellij.codeInsight.lookup.LookupElementPresentation;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.util.ThrowableRunnable;
@@ -115,8 +113,8 @@ public class SecondSmartTypeCompletionTest extends LightFixtureCompletionTestCas
configure();
checkResultByFile(getTestName(false) + ".java");
assertStringItems("bar()", "foo()");
assertEquals("Arrays.asList(f.bar())", ((LookupItem)((LookupElementDecorator)myItems[0]).getDelegate()).getPresentableText());
assertEquals("Arrays.asList(f.foo())", ((LookupItem)((LookupElementDecorator)myItems[1]).getDelegate()).getPresentableText());
assertEquals("Arrays.asList(f.bar())", LookupElementPresentation.renderElement(myItems[0]).getItemText());
assertEquals("Arrays.asList(f.foo())", LookupElementPresentation.renderElement(myItems[1]).getItemText());
selectItem(myItems[1]);
checkResult();
}
@@ -58,4 +58,5 @@ public class LightAdvHighlightingJdk6Test extends LightDaemonAnalyzerTestCase {
public void testGenericArrayCreationWithGenericTypeWithOneUnboundedWildcardOneNormalParams() { doTest(false, false); }
public void testAgentPremain() { doTest(false, false); }
public void testInitializedBeforeUsed() { doTest(false, false); }
public void testUnreachableAssignments() { doTest(false, false); }
}
@@ -117,4 +117,25 @@ public class JavaGotoSuperTest extends LightDaemonAnalyzerTestCase {
checkResultByFile(getBasePath() + "SiblingInheritance.java");
}
public void testDoNotShowSiblingInheritanceLineMarkerIfSubclassImplementsTheSameInterfaceAsTheCurrentClass() throws Throwable {
configureByFile(getBasePath() + "DeceivingSiblingInheritance.java");
PsiJavaFile file = (PsiJavaFile)getFile();
PsiClass OCBaseLanguageFileType = JavaPsiFacade.getInstance(getProject()).findClass("z.OCBaseLanguageFileType", GlobalSearchScope.fileScope(file));
PsiMethod getName = OCBaseLanguageFileType.getMethods()[0];
assertEquals("getName", getName.getName());
doHighlighting();
Document document = getEditor().getDocument();
List<LineMarkerInfo> markers = DaemonCodeAnalyzerImpl.getLineMarkers(document, getProject());
List<LineMarkerInfo> inMyClass = ContainerUtil.filter(markers, info -> {
return OCBaseLanguageFileType.getTextRange().containsRange(info.startOffset, info.endOffset);
});
assertTrue(inMyClass.toString(), inMyClass.size() == 2);
LineMarkerInfo iMarker = findMarkerWithElement(inMyClass, getName.getNameIdentifier());
assertSame(MarkerType.OVERRIDING_METHOD.getNavigationHandler(), iMarker.getNavigationHandler());
LineMarkerInfo aMarker = findMarkerWithElement(inMyClass, OCBaseLanguageFileType.getNameIdentifier());
assertSame(MarkerType.SUBCLASSED_CLASS.getNavigationHandler(), aMarker.getNavigationHandler());
}
}
@@ -106,6 +106,10 @@ public class MethodRefHighlightingTest extends LightDaemonAnalyzerTestCase {
doTest();
}
public void testIntersectionTypesInReceiverPosition() throws Exception {
doTest();
}
private void doTest() {
doTest(false);
}
@@ -194,10 +194,9 @@ public class FindManagerTest extends DaemonAnalyzerTestCase {
}
private List<UsageInfo> findUsages(@NotNull FindModel findModel) {
PsiDirectory psiDirectory = FindInProjectUtil.getPsiDirectory(findModel, myProject);
List<UsageInfo> result = new ArrayList<>();
final CommonProcessors.CollectProcessor<UsageInfo> collector = new CommonProcessors.CollectProcessor<>(result);
FindInProjectUtil.findUsages(findModel, psiDirectory, myProject, collector, new FindUsagesProcessPresentation(FindInProjectUtil.setupViewPresentation(true, findModel)));
FindInProjectUtil.findUsages(findModel, myProject, collector, new FindUsagesProcessPresentation(FindInProjectUtil.setupViewPresentation(true, findModel)));
return result;
}
@@ -661,6 +660,20 @@ public class FindManagerTest extends DaemonAnalyzerTestCase {
}
}
public void testFindInExcludedDirectory() throws Exception {
VirtualFile root = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(createTempDirectory());
addSourceContentToRoots(myModule, root);
VirtualFile excluded = createChildDirectory(root, "excluded");
createFile(myModule, excluded, "a.txt", "foo bar foo");
PsiTestUtil.addExcludedRoot(myModule, excluded);
FindModel findModel = FindManagerTestUtils.configureFindModel("foo");
findModel.setWholeWordsOnly(true);
findModel.setProjectScope(false);
findModel.setDirectoryName(excluded.getPath());
assertSize(2, findUsages(findModel));
}
public void testFindInJavaDocs() {
FindModel findModel = FindManagerTestUtils.configureFindModel("done");
String text = "/** done done done */";
@@ -0,0 +1,104 @@
/*
* 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.formatter.java;
import com.intellij.codeInsight.AbstractEnterActionTestCase;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.JavaCodeStyleSettings;
import java.io.IOException;
public class JavaEnterActionTest extends AbstractEnterActionTestCase {
public void testEnterInsideAnnotationParameters() throws IOException {
CodeStyleSettings settings = getCodeStyleSettings();
JavaCodeStyleSettings javaSettings = settings.getCustomSettings(JavaCodeStyleSettings.class);
javaSettings.ALIGN_MULTILINE_ANNOTATION_PARAMETERS = true;
setCodeStyleSettings(settings);
doTextTest("java",
"public class T {\n" +
"\n" +
" @Configurable(order = 25, \n" +
" validator = BigDecimalPercentValidator.class, <caret>)\n" +
" public void run() {\n" +
" }\n" +
" \n" +
" \n" +
"}",
"public class T {\n" +
"\n" +
" @Configurable(order = 25, \n" +
" validator = BigDecimalPercentValidator.class, \n" +
" <caret>)\n" +
" public void run() {\n" +
" }\n" +
" \n" +
" \n" +
"}");
doTextTest("java",
"public class T {\n" +
"\n" +
" @Configurable(order = 25, \n" +
" validator = BigDecimalPercentValidator.class, <caret>\n" +
" )\n" +
" public void run() {\n" +
" }\n" +
" \n" +
" \n" +
"}",
"public class T {\n" +
"\n" +
" @Configurable(order = 25, \n" +
" validator = BigDecimalPercentValidator.class, \n" +
" <caret>\n" +
" )\n" +
" public void run() {\n" +
" }\n" +
" \n" +
" \n" +
"}");
}
public void testEnterInsideAnnotationParameters_AfterNameValuePairBeforeLparenth() throws IOException {
CodeStyleSettings settings = getCodeStyleSettings();
JavaCodeStyleSettings javaSettings = settings.getCustomSettings(JavaCodeStyleSettings.class);
javaSettings.ALIGN_MULTILINE_ANNOTATION_PARAMETERS = true;
setCodeStyleSettings(settings);
doTextTest("java",
"public class T {\n" +
"\n" +
" @Configurable(order = 25, \n" +
" validator = BigDecimalPercentValidator.class<caret>)\n" +
" public void run() {\n" +
" }\n" +
" \n" +
" \n" +
"}",
"public class T {\n" +
"\n" +
" @Configurable(order = 25, \n" +
" validator = BigDecimalPercentValidator.class\n" +
" <caret>)\n" +
" public void run() {\n" +
" }\n" +
" \n" +
" \n" +
"}");
}
}
@@ -3204,4 +3204,19 @@ public void testSCR260() throws Exception {
"}"
);
}
public void testReformatCodeWithErrorElementsWithoutAssertions() {
doTextTest("class RedTest { \n\n\n\n\n\n\n\n " +
"String [ ] [ ] test = { { \n\n\n\n\n { \"\"} \n\n\n\n\n }; " +
"String [ ] [ ] test = { { \n\n\n\n\n { \"\"} \n\n\n\n\n }; " +
" \n\n\n\n\n\n\n\n } ",
"class RedTest {\n\n\n" +
" String[][] test = {{\n\n\n" +
" {\"\"}\n\n\n" +
" };\n" +
" String[][] test = {{\n\n\n" +
" {\"\"}\n\n\n" +
" };\n\n\n" +
"} ");
}
}
@@ -86,7 +86,7 @@ public class SearchInLibsTest extends PsiTestCase {
model.setProjectScope(false);
List<UsageInfo> usages = new ArrayList<UsageInfo>();
FindInProjectUtil.findUsages(model, aClass.getContainingFile().getContainingDirectory(), getProject(),
FindInProjectUtil.findUsages(model, getProject(),
new CommonProcessors.CollectProcessor<UsageInfo>(
usages), FindInProjectUtil
.setupProcessPresentation(getProject(), false, FindInProjectUtil.setupViewPresentation(false, model)));

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