Merge branch 'master' into upsource-master

This commit is contained in:
Evgeny Pasynkov
2012-07-03 10:28:50 +02:00
700 changed files with 146269 additions and 141471 deletions
@@ -1,62 +0,0 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.Consumer;
/**
* @author nik
*/
public abstract class AbstractBasicToClassNameDelegator extends CompletionContributor {
protected abstract boolean isClassNameCompletionSupported(CompletionResultSet result, PsiFile file, PsiElement position);
protected void updateProperties(LookupElement lookupElement) {
}
@Override
public void fillCompletionVariants(final CompletionParameters parameters, final CompletionResultSet result) {
if (parameters.getCompletionType() != CompletionType.BASIC || parameters.getInvocationCount() == 0) return;
final PsiFile file = parameters.getOriginalFile();
final PsiElement position = parameters.getPosition();
if (!isClassNameCompletionSupported(result, file, position)) return;
final boolean empty = result.runRemainingContributors(parameters, true).isEmpty();
final CompletionParameters classParams;
final int invocationCount = parameters.getInvocationCount();
if (empty) {
classParams = parameters.withType(CompletionType.CLASS_NAME);
}
else if (invocationCount > 1) {
classParams = parameters.withType(CompletionType.CLASS_NAME).withInvocationCount(invocationCount - 1);
} else {
return;
}
CompletionService.getCompletionService().getVariantsFromContributors(classParams, null, new Consumer<CompletionResult>() {
public void consume(final CompletionResult lookupElement) {
updateProperties(lookupElement.getLookupElement());
result.passResult(lookupElement);
}
});
}
}
@@ -1,306 +1,246 @@
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.ExpectedTypesProvider;
import com.intellij.codeInsight.generation.GenerateMembersUtil;
import com.intellij.codeInsight.generation.OverrideImplementUtil;
import com.intellij.codeInsight.generation.PsiGenerationInfo;
import com.intellij.codeInsight.generation.PsiMethodMember;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupElementDecorator;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.PsiTypeLookupItem;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.util.MemberChooser;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @author peter
*/
public class ConstructorInsertHandler implements InsertHandler<LookupElementDecorator<LookupItem>> {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.ConstructorInsertHandler");
public static final ConstructorInsertHandler SMART_INSTANCE = new ConstructorInsertHandler(true);
public static final ConstructorInsertHandler BASIC_INSTANCE = new ConstructorInsertHandler(false);
static final OffsetKey PARAM_LIST_START = OffsetKey.create("paramListStart");
static final OffsetKey PARAM_LIST_END = OffsetKey.create("paramListEnd");
private final boolean mySmart;
private ConstructorInsertHandler(boolean smart) {
mySmart = smart;
}
public void handleInsert(InsertionContext context, LookupElementDecorator<LookupItem> item) {
@SuppressWarnings({"unchecked"}) final LookupItem<PsiClass> delegate = item.getDelegate();
PsiClass psiClass = (PsiClass)item.getObject();
boolean isAbstract = psiClass.hasModifierProperty(PsiModifier.ABSTRACT);
if (Lookup.REPLACE_SELECT_CHAR == context.getCompletionChar()) {
final int plStart = context.getOffset(PARAM_LIST_START);
final int plEnd = context.getOffset(PARAM_LIST_END);
if (plStart >= 0 && plEnd >= 0) {
context.getDocument().deleteString(plStart, plEnd);
}
}
context.commitDocument();
OffsetKey insideRef = context.trackOffset(context.getTailOffset(), false);
final PsiElement position = SmartCompletionDecorator.getPosition(context, delegate);
final PsiExpression enclosing = PsiTreeUtil.getContextOfType(position, PsiExpression.class, true);
final PsiAnonymousClass anonymousClass = PsiTreeUtil.getParentOfType(position, PsiAnonymousClass.class);
final boolean inAnonymous = anonymousClass != null && anonymousClass.getParent() == enclosing;
boolean fillTypeArgs = false;
if (delegate instanceof PsiTypeLookupItem) {
fillTypeArgs = !isRawTypeExpected(context, (PsiTypeLookupItem)delegate) &&
psiClass.getTypeParameters().length > 0 &&
((PsiTypeLookupItem)delegate).calcGenerics(position, context).isEmpty() &&
context.getCompletionChar() != '(';
if (context.getDocument().getTextLength() > context.getTailOffset() &&
context.getDocument().getCharsSequence().charAt(context.getTailOffset()) == '<') {
PsiJavaCodeReferenceElement ref = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getTailOffset(), PsiJavaCodeReferenceElement.class, false);
if (ref != null) {
PsiReferenceParameterList parameterList = ref.getParameterList();
if (parameterList != null && context.getTailOffset() == parameterList.getTextRange().getStartOffset()) {
context.getDocument().deleteString(parameterList.getTextRange().getStartOffset(), parameterList.getTextRange().getEndOffset());
context.commitDocument();
}
}
}
delegate.handleInsert(context);
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider());
}
if (item.getDelegate() instanceof JavaPsiClassReferenceElement) {
PsiTypeLookupItem.addImportForItem(context, psiClass);
}
insertParentheses(context, delegate, psiClass, !inAnonymous && isAbstract);
if (inAnonymous) {
return;
}
if (isAbstract) {
if (mySmart) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW_ANONYMOUS);
}
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider());
final Editor editor = context.getEditor();
final int offset = context.getTailOffset();
editor.getDocument().insertString(offset, " {}");
editor.getCaretModel().moveToOffset(offset + 2);
if (fillTypeArgs && JavaCompletionUtil.promptTypeArgs(context, context.getOffset(insideRef))) return;
context.setLaterRunnable(generateAnonymousBody(editor, context.getFile()));
}
else {
PsiDocumentManager.getInstance(context.getProject()).commitAllDocuments();
final PsiNewExpression newExpression =
PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiNewExpression.class, false);
if (newExpression != null) {
final PsiJavaCodeReferenceElement classReference = newExpression.getClassOrAnonymousClassReference();
if (classReference != null) {
CodeStyleManager.getInstance(context.getProject()).reformat(classReference);
}
}
if (mySmart) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW);
}
if (fillTypeArgs && JavaCompletionUtil.promptTypeArgs(context, context.getOffset(insideRef))) return;
}
}
static boolean isRawTypeExpected(InsertionContext context, PsiTypeLookupItem delegate) {
PsiNewExpression newExpr =
PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiNewExpression.class, false);
if (newExpr != null) {
for (ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes(newExpr, true)) {
PsiType expected = info.getDefaultType();
if (expected.isAssignableFrom(delegate.getPsiType())) {
if (expected instanceof PsiClassType && ((PsiClassType)expected).isRaw()) {
return true;
}
}
}
}
return false;
}
public static boolean insertParentheses(InsertionContext context,
LookupItem delegate,
final PsiClass psiClass,
final boolean forAnonymous) {
if (context.getCompletionChar() == '[') {
return false;
}
final PsiElement place = context.getFile().findElementAt(context.getStartOffset());
assert place != null;
boolean hasParams = hasConstructorParameters(psiClass, place);
JavaCompletionUtil.insertParentheses(context, delegate, false, hasParams, forAnonymous);
return true;
}
static boolean hasConstructorParameters(PsiClass psiClass, @NotNull PsiElement place) {
final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(place.getProject()).getResolveHelper();
boolean hasParams = false;
for (PsiMethod constructor : psiClass.getConstructors()) {
if (!resolveHelper.isAccessible(constructor, place, null)) continue;
if (constructor.getParameterList().getParametersCount() > 0) {
hasParams = true;
break;
}
}
return hasParams;
}
@Nullable
private static Runnable generateAnonymousBody(final Editor editor, final PsiFile file) {
final Project project = file.getProject();
PsiDocumentManager.getInstance(project).commitAllDocuments();
int offset = editor.getCaretModel().getOffset();
PsiElement element = file.findElementAt(offset);
if (element == null) return null;
PsiElement parent = element.getParent();
if (!(parent instanceof PsiAnonymousClass)) return null;
return genAnonymousBodyFor((PsiAnonymousClass)parent, editor, file, project);
}
public static Runnable genAnonymousBodyFor(PsiAnonymousClass parent,
final Editor editor,
final PsiFile file,
final Project project) {
try {
CodeStyleManager.getInstance(project).reformat(parent);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
int offset = parent.getTextRange().getEndOffset() - 1;
editor.getCaretModel().moveToOffset(offset);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
editor.getSelectionModel().removeSelection();
return new Runnable() {
public void run(){
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
final PsiAnonymousClass aClass = PsiTreeUtil.findElementOfClassAtOffset(file, editor.getCaretModel().getOffset(), PsiAnonymousClass.class, false);
if (aClass == null) return;
final Collection<CandidateInfo> candidatesToImplement = OverrideImplementUtil.getMethodsToOverrideImplement(aClass, true);
boolean invokeOverride = candidatesToImplement.isEmpty();
if (invokeOverride){
chooseAndOverrideMethodsInAdapter(project, editor, aClass);
}
else{
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try{
List<PsiMethod> methods = OverrideImplementUtil.overrideOrImplementMethodCandidates(aClass, candidatesToImplement, false);
List<PsiGenerationInfo<PsiMethod>> prototypes = OverrideImplementUtil.convert2GenerationInfos(methods);
List<PsiGenerationInfo<PsiMethod>> resultMembers = GenerateMembersUtil.insertMembersBeforeAnchor(aClass, null, prototypes);
resultMembers.get(0).positionCaret(editor, true);
}
catch(IncorrectOperationException ioe){
LOG.error(ioe);
}
}
});
}
}
}, CompletionBundle.message("completion.smart.type.generate.anonymous.body"), null, UndoConfirmationPolicy.DEFAULT, editor.getDocument());
}
};
}
private static void chooseAndOverrideMethodsInAdapter(final Project project, final Editor editor, final PsiAnonymousClass aClass) {
PsiClass baseClass = aClass.getBaseClassType().resolve();
if (baseClass == null) return;
PsiMethod[] allBaseMethods = baseClass.getMethods();
if(allBaseMethods.length == 0) return;
List<PsiMethodMember> methods = new ArrayList<PsiMethodMember>();
for (final PsiMethod method : allBaseMethods) {
if (OverrideImplementUtil.isOverridable(method)) {
methods.add(new PsiMethodMember(method, PsiSubstitutor.UNKNOWN));
}
}
boolean canInsertOverride = PsiUtil.isLanguageLevel5OrHigher(aClass) && (PsiUtil.isLanguageLevel6OrHigher(aClass) || !aClass.isInterface());
final PsiMethodMember[] array = methods.toArray(new PsiMethodMember[methods.size()]);
final MemberChooser<PsiMethodMember> chooser = new MemberChooser<PsiMethodMember>(array, false, true, project, canInsertOverride);
chooser.setTitle(CompletionBundle.message("completion.smarttype.select.methods.to.override"));
chooser.setCopyJavadocVisible(true);
chooser.show();
List<PsiMethodMember> selected = chooser.getSelectedElements();
if (selected == null || selected.isEmpty()) return;
try{
final List<PsiGenerationInfo<PsiMethod>> prototypes = OverrideImplementUtil.overrideOrImplementMethods(aClass, selected, chooser.isCopyJavadoc(), chooser.isInsertOverrideAnnotation());
final int offset = editor.getCaretModel().getOffset();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try{
for (PsiGenerationInfo<PsiMethod> prototype : prototypes) {
PsiStatement[] statements = prototype.getPsiMember().getBody().getStatements();
if (statements.length > 0 && PsiType.VOID.equals(prototype.getPsiMember().getReturnType())) {
statements[0].delete(); // remove "super(..)" call
}
}
List<PsiGenerationInfo<PsiMethod>> resultMembers = GenerateMembersUtil.insertMembersAtOffset(aClass.getContainingFile(), offset, prototypes);
resultMembers.get(0).positionCaret(editor, true);
}
catch(IncorrectOperationException e){
LOG.error(e);
}
}
});
}
catch(IncorrectOperationException ioe){
LOG.error(ioe);
}
}
}
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.ExpectedTypesProvider;
import com.intellij.codeInsight.generation.GenerateMembersUtil;
import com.intellij.codeInsight.generation.OverrideImplementUtil;
import com.intellij.codeInsight.generation.PsiGenerationInfo;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupElementDecorator;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.PsiTypeLookupItem;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.List;
/**
* @author peter
*/
public class ConstructorInsertHandler implements InsertHandler<LookupElementDecorator<LookupItem>> {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.ConstructorInsertHandler");
public static final ConstructorInsertHandler SMART_INSTANCE = new ConstructorInsertHandler(true);
public static final ConstructorInsertHandler BASIC_INSTANCE = new ConstructorInsertHandler(false);
static final OffsetKey PARAM_LIST_START = OffsetKey.create("paramListStart");
static final OffsetKey PARAM_LIST_END = OffsetKey.create("paramListEnd");
private final boolean mySmart;
private ConstructorInsertHandler(boolean smart) {
mySmart = smart;
}
public void handleInsert(InsertionContext context, LookupElementDecorator<LookupItem> item) {
@SuppressWarnings({"unchecked"}) final LookupItem<PsiClass> delegate = item.getDelegate();
PsiClass psiClass = (PsiClass)item.getObject();
boolean isAbstract = psiClass.hasModifierProperty(PsiModifier.ABSTRACT);
if (Lookup.REPLACE_SELECT_CHAR == context.getCompletionChar()) {
final int plStart = context.getOffset(PARAM_LIST_START);
final int plEnd = context.getOffset(PARAM_LIST_END);
if (plStart >= 0 && plEnd >= 0) {
context.getDocument().deleteString(plStart, plEnd);
}
}
context.commitDocument();
OffsetKey insideRef = context.trackOffset(context.getTailOffset(), false);
final PsiElement position = SmartCompletionDecorator.getPosition(context, delegate);
final PsiExpression enclosing = PsiTreeUtil.getContextOfType(position, PsiExpression.class, true);
final PsiAnonymousClass anonymousClass = PsiTreeUtil.getParentOfType(position, PsiAnonymousClass.class);
final boolean inAnonymous = anonymousClass != null && anonymousClass.getParent() == enclosing;
boolean fillTypeArgs = false;
if (delegate instanceof PsiTypeLookupItem) {
fillTypeArgs = !isRawTypeExpected(context, (PsiTypeLookupItem)delegate) &&
psiClass.getTypeParameters().length > 0 &&
((PsiTypeLookupItem)delegate).calcGenerics(position, context).isEmpty() &&
context.getCompletionChar() != '(';
if (context.getDocument().getTextLength() > context.getTailOffset() &&
context.getDocument().getCharsSequence().charAt(context.getTailOffset()) == '<') {
PsiJavaCodeReferenceElement ref = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getTailOffset(), PsiJavaCodeReferenceElement.class, false);
if (ref != null) {
PsiReferenceParameterList parameterList = ref.getParameterList();
if (parameterList != null && context.getTailOffset() == parameterList.getTextRange().getStartOffset()) {
context.getDocument().deleteString(parameterList.getTextRange().getStartOffset(), parameterList.getTextRange().getEndOffset());
context.commitDocument();
}
}
}
delegate.handleInsert(context);
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider());
}
if (item.getDelegate() instanceof JavaPsiClassReferenceElement) {
PsiTypeLookupItem.addImportForItem(context, psiClass);
}
insertParentheses(context, delegate, psiClass, !inAnonymous && isAbstract);
if (inAnonymous) {
return;
}
if (mySmart) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW);
}
if (isAbstract) {
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider());
final Editor editor = context.getEditor();
final int offset = context.getTailOffset();
editor.getDocument().insertString(offset, " {}");
editor.getCaretModel().moveToOffset(offset + 2);
if (fillTypeArgs && JavaCompletionUtil.promptTypeArgs(context, context.getOffset(insideRef))) return;
context.setLaterRunnable(generateAnonymousBody(editor, context.getFile()));
}
else {
PsiDocumentManager.getInstance(context.getProject()).commitAllDocuments();
final PsiNewExpression newExpression =
PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiNewExpression.class, false);
if (newExpression != null) {
final PsiJavaCodeReferenceElement classReference = newExpression.getClassOrAnonymousClassReference();
if (classReference != null) {
CodeStyleManager.getInstance(context.getProject()).reformat(classReference);
}
}
if (mySmart) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW);
}
if (fillTypeArgs && JavaCompletionUtil.promptTypeArgs(context, context.getOffset(insideRef))) return;
}
}
static boolean isRawTypeExpected(InsertionContext context, PsiTypeLookupItem delegate) {
PsiNewExpression newExpr =
PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiNewExpression.class, false);
if (newExpr != null) {
for (ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes(newExpr, true)) {
PsiType expected = info.getDefaultType();
if (expected.isAssignableFrom(delegate.getPsiType())) {
if (expected instanceof PsiClassType && ((PsiClassType)expected).isRaw()) {
return true;
}
}
}
}
return false;
}
public static boolean insertParentheses(InsertionContext context,
LookupItem delegate,
final PsiClass psiClass,
final boolean forAnonymous) {
if (context.getCompletionChar() == '[') {
return false;
}
final PsiElement place = context.getFile().findElementAt(context.getStartOffset());
assert place != null;
boolean hasParams = hasConstructorParameters(psiClass, place);
JavaCompletionUtil.insertParentheses(context, delegate, false, hasParams, forAnonymous);
return true;
}
static boolean hasConstructorParameters(PsiClass psiClass, @NotNull PsiElement place) {
final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(place.getProject()).getResolveHelper();
boolean hasParams = false;
for (PsiMethod constructor : psiClass.getConstructors()) {
if (!resolveHelper.isAccessible(constructor, place, null)) continue;
if (constructor.getParameterList().getParametersCount() > 0) {
hasParams = true;
break;
}
}
return hasParams;
}
@Nullable
private static Runnable generateAnonymousBody(final Editor editor, final PsiFile file) {
final Project project = file.getProject();
PsiDocumentManager.getInstance(project).commitAllDocuments();
int offset = editor.getCaretModel().getOffset();
PsiElement element = file.findElementAt(offset);
if (element == null) return null;
PsiElement parent = element.getParent();
if (!(parent instanceof PsiAnonymousClass)) return null;
return genAnonymousBodyFor((PsiAnonymousClass)parent, editor, file, project);
}
public static Runnable genAnonymousBodyFor(PsiAnonymousClass parent,
final Editor editor,
final PsiFile file,
final Project project) {
try {
CodeStyleManager.getInstance(project).reformat(parent);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
int offset = parent.getTextRange().getEndOffset() - 1;
editor.getCaretModel().moveToOffset(offset);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
editor.getSelectionModel().removeSelection();
return new Runnable() {
public void run(){
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
final PsiAnonymousClass aClass = PsiTreeUtil.findElementOfClassAtOffset(file, editor.getCaretModel().getOffset(), PsiAnonymousClass.class, false);
if (aClass == null) return;
final Collection<CandidateInfo> candidatesToImplement = OverrideImplementUtil.getMethodsToOverrideImplement(aClass, true);
boolean invokeOverride = candidatesToImplement.isEmpty();
if (invokeOverride){
OverrideImplementUtil.chooseAndOverrideOrImplementMethods(project, editor, aClass, false);
}
else{
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try{
List<PsiMethod> methods = OverrideImplementUtil.overrideOrImplementMethodCandidates(aClass, candidatesToImplement, false);
List<PsiGenerationInfo<PsiMethod>> prototypes = OverrideImplementUtil.convert2GenerationInfos(methods);
List<PsiGenerationInfo<PsiMethod>> resultMembers = GenerateMembersUtil.insertMembersBeforeAnchor(aClass, null, prototypes);
resultMembers.get(0).positionCaret(editor, true);
}
catch(IncorrectOperationException ioe){
LOG.error(ioe);
}
}
});
}
}
}, CompletionBundle.message("completion.smart.type.generate.anonymous.body"), null, UndoConfirmationPolicy.DEFAULT, editor.getDocument());
}
};
}
}
@@ -1,193 +1,184 @@
/*
* 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.codeInsight.completion;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.ExpectedTypesProvider;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.lang.LangBundle;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.patterns.PsiJavaElementPattern;
import com.intellij.psi.*;
import com.intellij.psi.filters.ClassFilter;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.psi.filters.TrueFilter;
import com.intellij.psi.filters.element.ExcludeDeclaredFilter;
import com.intellij.psi.filters.types.AssignableFromFilter;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Consumer;
import com.intellij.util.ProcessingContext;
import com.intellij.util.SmartList;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static com.intellij.patterns.PsiJavaPatterns.psiElement;
/**
* @author peter
*/
public class JavaClassNameCompletionContributor extends CompletionContributor {
public static final PsiJavaElementPattern.Capture<PsiElement> AFTER_NEW = psiElement().afterLeaf(PsiKeyword.NEW);
private static final PsiJavaElementPattern.Capture<PsiElement> IN_TYPE_PARAMETER =
psiElement().afterLeaf(PsiKeyword.EXTENDS, PsiKeyword.SUPER, "&").withParent(
psiElement(PsiReferenceList.class).withParent(PsiTypeParameter.class));
public JavaClassNameCompletionContributor() {
extend(CompletionType.CLASS_NAME, psiElement(), new CompletionProvider<CompletionParameters>() {
public void addCompletions(@NotNull final CompletionParameters parameters, final ProcessingContext matchingContext, @NotNull final CompletionResultSet _result) {
if (shouldShowSecondSmartCompletionHint(parameters) &&
CompletionUtil.shouldShowFeature(parameters, CodeCompletionFeatures.SECOND_CLASS_NAME_COMPLETION)) {
CompletionService.getCompletionService().setAdvertisementText(CompletionBundle.message("completion.class.name.hint.2", getActionShortcut(IdeActions.ACTION_CLASS_NAME_COMPLETION)));
}
CompletionResultSet result = _result.withPrefixMatcher(CompletionUtil.findReferenceOrAlphanumericPrefix(parameters));
addAllClasses(parameters, parameters.getInvocationCount() <= 1,
JavaCompletionSorting.addJavaSorting(parameters, result).getPrefixMatcher(), new Consumer<LookupElement>() {
@Override
public void consume(LookupElement element) {
_result.addElement(element);
}
});
}
});
}
public static void addAllClasses(CompletionParameters parameters,
final boolean filterByScope,
@NotNull final PrefixMatcher matcher,
@NotNull final Consumer<LookupElement> consumer) {
final PsiElement insertedElement = parameters.getPosition();
final ElementFilter filter;
if (JavaSmartCompletionContributor.AFTER_THROW_NEW.accepts(insertedElement) ||
JavaCompletionContributor.INSIDE_METHOD_THROWS_CLAUSE.accepts(insertedElement) ||
JavaCompletionContributor.IN_CATCH_TYPE.accepts(insertedElement) ||
JavaCompletionContributor.IN_MULTI_CATCH_TYPE.accepts(insertedElement)) {
filter = new AssignableFromFilter(CommonClassNames.JAVA_LANG_THROWABLE);
}
else if (JavaCompletionContributor.IN_RESOURCE_TYPE.accepts(insertedElement)) {
filter = new AssignableFromFilter(CommonClassNames.JAVA_LANG_AUTO_CLOSEABLE);
}
else if (IN_TYPE_PARAMETER.accepts(insertedElement)) {
filter = new ExcludeDeclaredFilter(new ClassFilter(PsiTypeParameter.class));
}
else {
filter = TrueFilter.INSTANCE;
}
final boolean inJavaContext = parameters.getPosition() instanceof PsiIdentifier;
final boolean afterNew = AFTER_NEW.accepts(insertedElement);
if (afterNew) {
final PsiExpression expr = PsiTreeUtil.getContextOfType(insertedElement, PsiExpression.class, true);
for (final ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes(expr, true)) {
final PsiType type = info.getType();
final PsiClass psiClass = PsiUtil.resolveClassInType(type);
if (psiClass != null) {
consumer.consume(createClassLookupItem(psiClass, inJavaContext));
}
final PsiType defaultType = info.getDefaultType();
if (!defaultType.equals(type)) {
final PsiClass defClass = PsiUtil.resolveClassInType(defaultType);
if (defClass != null) {
consumer.consume(createClassLookupItem(defClass, true));
}
}
}
}
final boolean lookingForAnnotations = psiElement().afterLeaf("@").accepts(insertedElement);
final boolean pkgContext = JavaCompletionUtil.inSomePackage(insertedElement);
AllClassesGetter.processJavaClasses(parameters, matcher, filterByScope, new Consumer<PsiClass>() {
@Override
public void consume(PsiClass psiClass) {
if (lookingForAnnotations && !psiClass.isAnnotationType()) return;
if (filter.isAcceptable(psiClass, insertedElement)) {
if (!inJavaContext) {
consumer.consume(AllClassesGetter.createLookupItem(psiClass, AllClassesGetter.TRY_SHORTENING));
} else {
for (JavaPsiClassReferenceElement element : createClassLookupItems(psiClass, afterNew,
JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER, new Condition<PsiClass>() {
@Override
public boolean value(PsiClass psiClass) {
return filter.isAcceptable(psiClass, insertedElement) &&
AllClassesGetter.isAcceptableInContext(insertedElement, psiClass, filterByScope, pkgContext);
}
})) {
consumer.consume(element);
}
}
}
}
});
}
public static JavaPsiClassReferenceElement createClassLookupItem(final PsiClass psiClass, final boolean inJavaContext) {
return AllClassesGetter.createLookupItem(psiClass, inJavaContext ? JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER
: AllClassesGetter.TRY_SHORTENING);
}
public static List<JavaPsiClassReferenceElement> createClassLookupItems(final PsiClass psiClass,
boolean withInners,
InsertHandler<JavaPsiClassReferenceElement> insertHandler,
Condition<PsiClass> condition) {
List<JavaPsiClassReferenceElement> result = new SmartList<JavaPsiClassReferenceElement>();
if (condition.value(psiClass)) {
result.add(AllClassesGetter.createLookupItem(psiClass, insertHandler));
}
String name = psiClass.getName();
if (withInners && name != null) {
for (PsiClass inner : psiClass.getInnerClasses()) {
if (inner.hasModifierProperty(PsiModifier.STATIC)) {
for (JavaPsiClassReferenceElement lookupInner : createClassLookupItems(inner, withInners, insertHandler, condition)) {
String forced = lookupInner.getForcedPresentableName();
lookupInner.setForcedPresentableName(name + "." + (forced != null ? forced : inner.getName()));
result.add(lookupInner);
}
}
}
}
return result;
}
@Override
public String handleEmptyLookup(@NotNull final CompletionParameters parameters, final Editor editor) {
if (!(parameters.getOriginalFile() instanceof PsiJavaFile)) return null;
if (shouldShowSecondSmartCompletionHint(parameters)) {
return LangBundle.message("completion.no.suggestions") +
"; " +
StringUtil.decapitalize(
CompletionBundle.message("completion.class.name.hint.2", getActionShortcut(IdeActions.ACTION_CLASS_NAME_COMPLETION)));
}
return null;
}
private static boolean shouldShowSecondSmartCompletionHint(final CompletionParameters parameters) {
return parameters.getCompletionType() == CompletionType.CLASS_NAME &&
parameters.getInvocationCount() == 1 &&
parameters.getOriginalFile().getLanguage().isKindOf(JavaLanguage.INSTANCE);
}
}
/*
* 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.codeInsight.completion;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.ExpectedTypesProvider;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.lang.LangBundle;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileTypes.impl.CustomSyntaxTableFileType;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.patterns.PsiJavaElementPattern;
import com.intellij.psi.*;
import com.intellij.psi.filters.ClassFilter;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.psi.filters.TrueFilter;
import com.intellij.psi.filters.element.ExcludeDeclaredFilter;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Consumer;
import com.intellij.util.SmartList;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static com.intellij.patterns.PsiJavaPatterns.psiElement;
/**
* @author peter
*/
public class JavaClassNameCompletionContributor extends CompletionContributor {
public static final PsiJavaElementPattern.Capture<PsiElement> AFTER_NEW = psiElement().afterLeaf(PsiKeyword.NEW);
private static final PsiJavaElementPattern.Capture<PsiElement> IN_TYPE_PARAMETER =
psiElement().afterLeaf(PsiKeyword.EXTENDS, PsiKeyword.SUPER, "&").withParent(
psiElement(PsiReferenceList.class).withParent(PsiTypeParameter.class));
@Override
public void fillCompletionVariants(CompletionParameters parameters, final CompletionResultSet _result) {
if (parameters.getCompletionType() == CompletionType.CLASS_NAME ||
parameters.isExtendedCompletion() && mayContainClassName(parameters)) {
CompletionResultSet result = _result.withPrefixMatcher(CompletionUtil.findReferenceOrAlphanumericPrefix(parameters));
addAllClasses(parameters, parameters.getInvocationCount() <= 1, result.getPrefixMatcher(), new Consumer<LookupElement>() {
@Override
public void consume(LookupElement element) {
_result.addElement(element);
}
});
}
}
private static boolean mayContainClassName(CompletionParameters parameters) {
PsiElement position = parameters.getPosition();
PsiFile file = position.getContainingFile();
if (file instanceof PsiPlainTextFile || file.getFileType() instanceof CustomSyntaxTableFileType) {
return true;
}
if (SkipAutopopupInStrings.isInStringLiteral(position)) {
return true;
}
if (PsiTreeUtil.getParentOfType(position, PsiComment.class, false) != null) {
return true;
}
return false;
}
public static void addAllClasses(CompletionParameters parameters,
final boolean filterByScope,
@NotNull final PrefixMatcher matcher,
@NotNull final Consumer<LookupElement> consumer) {
final PsiElement insertedElement = parameters.getPosition();
final ElementFilter filter =
IN_TYPE_PARAMETER.accepts(insertedElement) ? new ExcludeDeclaredFilter(new ClassFilter(PsiTypeParameter.class)) : TrueFilter.INSTANCE;
final boolean inJavaContext = parameters.getPosition() instanceof PsiIdentifier;
final boolean afterNew = AFTER_NEW.accepts(insertedElement);
if (afterNew) {
final PsiExpression expr = PsiTreeUtil.getContextOfType(insertedElement, PsiExpression.class, true);
for (final ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes(expr, true)) {
final PsiType type = info.getType();
final PsiClass psiClass = PsiUtil.resolveClassInType(type);
if (psiClass != null) {
consumer.consume(createClassLookupItem(psiClass, inJavaContext));
}
final PsiType defaultType = info.getDefaultType();
if (!defaultType.equals(type)) {
final PsiClass defClass = PsiUtil.resolveClassInType(defaultType);
if (defClass != null) {
consumer.consume(createClassLookupItem(defClass, true));
}
}
}
}
final boolean pkgContext = JavaCompletionUtil.inSomePackage(insertedElement);
AllClassesGetter.processJavaClasses(parameters, matcher, filterByScope, new Consumer<PsiClass>() {
@Override
public void consume(PsiClass psiClass) {
if (filter.isAcceptable(psiClass, insertedElement)) {
if (!inJavaContext) {
consumer.consume(AllClassesGetter.createLookupItem(psiClass, AllClassesGetter.TRY_SHORTENING));
} else {
for (JavaPsiClassReferenceElement element : createClassLookupItems(psiClass, afterNew,
JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER, new Condition<PsiClass>() {
@Override
public boolean value(PsiClass psiClass) {
return filter.isAcceptable(psiClass, insertedElement) &&
AllClassesGetter.isAcceptableInContext(insertedElement, psiClass, filterByScope, pkgContext);
}
})) {
consumer.consume(element);
}
}
}
}
});
}
public static JavaPsiClassReferenceElement createClassLookupItem(final PsiClass psiClass, final boolean inJavaContext) {
return AllClassesGetter.createLookupItem(psiClass, inJavaContext ? JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER
: AllClassesGetter.TRY_SHORTENING);
}
public static List<JavaPsiClassReferenceElement> createClassLookupItems(final PsiClass psiClass,
boolean withInners,
InsertHandler<JavaPsiClassReferenceElement> insertHandler,
Condition<PsiClass> condition) {
List<JavaPsiClassReferenceElement> result = new SmartList<JavaPsiClassReferenceElement>();
if (condition.value(psiClass)) {
result.add(AllClassesGetter.createLookupItem(psiClass, insertHandler));
}
String name = psiClass.getName();
if (withInners && name != null) {
for (PsiClass inner : psiClass.getInnerClasses()) {
if (inner.hasModifierProperty(PsiModifier.STATIC)) {
for (JavaPsiClassReferenceElement lookupInner : createClassLookupItems(inner, withInners, insertHandler, condition)) {
String forced = lookupInner.getForcedPresentableName();
lookupInner.setForcedPresentableName(name + "." + (forced != null ? forced : inner.getName()));
result.add(lookupInner);
}
}
}
}
return result;
}
@Override
public String handleEmptyLookup(@NotNull final CompletionParameters parameters, final Editor editor) {
if (!(parameters.getOriginalFile() instanceof PsiJavaFile)) return null;
if (shouldShowSecondSmartCompletionHint(parameters)) {
return LangBundle.message("completion.no.suggestions") +
"; " +
StringUtil.decapitalize(
CompletionBundle.message("completion.class.name.hint.2", getActionShortcut(IdeActions.ACTION_CODE_COMPLETION)));
}
return null;
}
private static boolean shouldShowSecondSmartCompletionHint(final CompletionParameters parameters) {
return parameters.getCompletionType() == CompletionType.BASIC &&
parameters.getInvocationCount() == 2 &&
parameters.getOriginalFile().getLanguage().isKindOf(JavaLanguage.INSTANCE);
}
}
File diff suppressed because it is too large Load Diff
@@ -1,31 +1,30 @@
/*
* 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.codeInsight.completion;
import org.jetbrains.annotations.NonNls;
/**
* @author peter
*/
public interface JavaCompletionFeatures {
@NonNls String SECOND_SMART_COMPLETION_CHAIN = "editing.completion.second.smarttype.chain";
@NonNls String SECOND_SMART_COMPLETION_TOAR = "editing.completion.second.smarttype.toar";
@NonNls String SECOND_SMART_COMPLETION_ASLIST = "editing.completion.second.smarttype.aslist";
@NonNls String SECOND_SMART_COMPLETION_ARRAY_MEMBER = "editing.completion.second.smarttype.array.member";
@NonNls String GLOBAL_MEMBER_NAME = "editing.completion.global.member.name";
@NonNls String AFTER_NEW = "editing.completion.smarttype.afternew";
@NonNls String AFTER_NEW_ANONYMOUS = "editing.completion.smarttype.afternew";
}
/*
* 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.codeInsight.completion;
import org.jetbrains.annotations.NonNls;
/**
* @author peter
*/
public interface JavaCompletionFeatures {
@NonNls String SECOND_SMART_COMPLETION_CHAIN = "editing.completion.second.smarttype.chain";
@NonNls String SECOND_SMART_COMPLETION_TOAR = "editing.completion.second.smarttype.toar";
@NonNls String SECOND_SMART_COMPLETION_ASLIST = "editing.completion.second.smarttype.aslist";
@NonNls String SECOND_SMART_COMPLETION_ARRAY_MEMBER = "editing.completion.second.smarttype.array.member";
@NonNls String GLOBAL_MEMBER_NAME = "editing.completion.global.member.name";
@NonNls String AFTER_NEW = "editing.completion.smarttype.afternew";
}
File diff suppressed because it is too large Load Diff
@@ -1,77 +0,0 @@
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.VariableLookupItem;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/**
* @author peter
*/
public class JavaGlobalMemberNameCompletionContributor extends CompletionContributor {
@Override
public void fillCompletionVariants(CompletionParameters parameters, final CompletionResultSet result) {
if (parameters.getCompletionType() != CompletionType.CLASS_NAME) {
return;
}
if (result.getPrefixMatcher().getPrefix().length() == 0) {
return;
}
final PsiElement position = parameters.getPosition();
final PsiElement parent = position.getParent();
if (!(parent instanceof PsiReferenceExpression)) {
return;
}
final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)parent;
if (referenceExpression.isQualified()) {
return;
}
completeStaticMembers(parameters).processStaticMethodsGlobally(result);
}
public static StaticMemberProcessor completeStaticMembers(CompletionParameters parameters) {
final PsiElement position = parameters.getPosition();
final PsiElement originalPosition = parameters.getOriginalPosition();
final StaticMemberProcessor processor = new StaticMemberProcessor(position) {
@NotNull
@Override
protected LookupElement createLookupElement(@NotNull PsiMember member, @NotNull final PsiClass containingClass, boolean shouldImport) {
shouldImport |= originalPosition != null && PsiTreeUtil.isAncestor(containingClass, originalPosition, false);
if (member instanceof PsiMethod) {
return new JavaMethodCallElement((PsiMethod)member, shouldImport, false);
}
return new VariableLookupItem((PsiField)member, shouldImport);
}
@Override
protected LookupElement createLookupElement(@NotNull List<PsiMethod> overloads,
@NotNull PsiClass containingClass,
boolean shouldImport) {
shouldImport |= originalPosition != null && PsiTreeUtil.isAncestor(containingClass, originalPosition, false);
final JavaMethodCallElement element = new JavaMethodCallElement(overloads.get(0), shouldImport, true);
element.putUserData(JavaCompletionUtil.ALL_METHODS_ATTRIBUTE, overloads);
return element;
}
};
final PsiFile file = position.getContainingFile();
if (file instanceof PsiJavaFile) {
final PsiImportList importList = ((PsiJavaFile)file).getImportList();
if (importList != null) {
for (PsiImportStaticStatement statement : importList.getImportStaticStatements()) {
processor.importMembersOf(statement.resolveTargetClass());
}
}
}
return processor;
}
}
@@ -0,0 +1,69 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.VariableLookupItem;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/**
* @author peter
*/
public class JavaStaticMemberProcessor extends StaticMemberProcessor {
private final PsiElement myOriginalPosition;
public JavaStaticMemberProcessor(CompletionParameters parameters) {
super(parameters.getPosition());
myOriginalPosition = parameters.getOriginalPosition();
final PsiFile file = parameters.getPosition().getContainingFile();
if (file instanceof PsiJavaFile) {
final PsiImportList importList = ((PsiJavaFile)file).getImportList();
if (importList != null) {
for (PsiImportStaticStatement statement : importList.getImportStaticStatements()) {
importMembersOf(statement.resolveTargetClass());
}
}
}
}
@NotNull
@Override
protected LookupElement createLookupElement(@NotNull PsiMember member, @NotNull final PsiClass containingClass, boolean shouldImport) {
shouldImport |= myOriginalPosition != null && PsiTreeUtil.isAncestor(containingClass, myOriginalPosition, false);
if (member instanceof PsiMethod) {
return AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(new JavaMethodCallElement((PsiMethod)member, shouldImport, false));
}
return AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(new VariableLookupItem((PsiField)member, shouldImport));
}
@Override
protected LookupElement createLookupElement(@NotNull List<PsiMethod> overloads,
@NotNull PsiClass containingClass,
boolean shouldImport) {
shouldImport |= myOriginalPosition != null && PsiTreeUtil.isAncestor(containingClass, myOriginalPosition, false);
final JavaMethodCallElement element = new JavaMethodCallElement(overloads.get(0), shouldImport, true);
element.putUserData(JavaCompletionUtil.ALL_METHODS_ATTRIBUTE, overloads);
return element;
}
}
@@ -1,135 +1,140 @@
/*
* 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.codeInsight.completion;
import com.intellij.codeInsight.completion.scope.JavaCompletionProcessor;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementWeigher;
import com.intellij.psi.*;
import com.intellij.psi.filters.getters.MembersGetter;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Set;
/**
* @author peter
*/
public class PreferLocalVariablesLiteralsAndAnnoMethodsWeigher extends LookupElementWeigher {
private final CompletionType myCompletionType;
private final PsiElement myPosition;
private final Set<PsiField> myNonInitializedFields;
public PreferLocalVariablesLiteralsAndAnnoMethodsWeigher(CompletionType completionType, PsiElement position) {
super("local");
myCompletionType = completionType;
myPosition = position;
myNonInitializedFields = JavaCompletionProcessor.getNonInitializedFields(position);
}
enum MyResult {
annoMethod,
probableKeyword,
localOrParameter,
qualifiedWithField,
qualifiedWithGetter,
superMethodParameters,
normal,
collectionFactory,
expectedTypeMember,
nonInitialized,
classLiteral,
className,
}
@NotNull
@Override
public MyResult weigh(@NotNull LookupElement item) {
final Object object = item.getObject();
if (object instanceof PsiKeyword) {
String keyword = ((PsiKeyword)object).getText();
if (PsiKeyword.RETURN.equals(keyword) && isLastStatement(PsiTreeUtil.getParentOfType(myPosition, PsiStatement.class))) {
return MyResult.probableKeyword;
}
if (PsiKeyword.ELSE.equals(keyword) || PsiKeyword.FINALLY.equals(keyword)) {
return MyResult.probableKeyword;
}
}
if (object instanceof PsiLocalVariable || object instanceof PsiParameter || object instanceof PsiThisExpression) {
return MyResult.localOrParameter;
}
if (object instanceof String && item.getUserData(JavaCompletionUtil.SUPER_METHOD_PARAMETERS) == Boolean.TRUE) {
return MyResult.superMethodParameters;
}
if (myCompletionType == CompletionType.SMART) {
if (item.getUserData(CollectionsUtilityMethodsProvider.COLLECTION_FACTORY) != null) {
return MyResult.collectionFactory;
}
if (Boolean.TRUE.equals(item.getUserData(MembersGetter.EXPECTED_TYPE_INHERITOR_MEMBER))) {
return MyResult.expectedTypeMember;
}
final JavaChainLookupElement chain = item.as(JavaChainLookupElement.CLASS_CONDITION_KEY);
if (chain != null) {
Object qualifier = chain.getQualifier().getObject();
if (qualifier instanceof PsiLocalVariable || qualifier instanceof PsiParameter) {
return MyResult.localOrParameter;
}
if (qualifier instanceof PsiField) {
return MyResult.qualifiedWithField;
}
if (qualifier instanceof PsiMethod && PropertyUtil.isSimplePropertyGetter((PsiMethod)qualifier)) {
return MyResult.qualifiedWithGetter;
}
}
return MyResult.normal;
}
if (myCompletionType == CompletionType.BASIC) {
if (object instanceof PsiKeyword && PsiKeyword.CLASS.equals(item.getLookupString())) {
return MyResult.classLiteral;
}
if (object instanceof PsiAnnotationMethod && ((PsiAnnotationMethod)object).getContainingClass().isAnnotationType()) {
return MyResult.annoMethod;
}
if (object instanceof PsiClass) {
return MyResult.className;
}
if (object instanceof PsiField && myNonInitializedFields.contains(object)) {
return MyResult.nonInitialized;
}
}
return MyResult.normal;
}
private static boolean isLastStatement(PsiStatement statement) {
if (statement == null || !(statement.getParent() instanceof PsiCodeBlock)) {
return true;
}
PsiStatement[] siblings = ((PsiCodeBlock)statement.getParent()).getStatements();
return statement == siblings[siblings.length - 1];
}
}
/*
* 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.codeInsight.completion;
import com.intellij.codeInsight.completion.scope.JavaCompletionProcessor;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementWeigher;
import com.intellij.psi.*;
import com.intellij.psi.filters.getters.MembersGetter;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Set;
/**
* @author peter
*/
public class PreferLocalVariablesLiteralsAndAnnoMethodsWeigher extends LookupElementWeigher {
private final CompletionType myCompletionType;
private final PsiElement myPosition;
private final Set<PsiField> myNonInitializedFields;
public PreferLocalVariablesLiteralsAndAnnoMethodsWeigher(CompletionType completionType, PsiElement position) {
super("local");
myCompletionType = completionType;
myPosition = position;
myNonInitializedFields = JavaCompletionProcessor.getNonInitializedFields(position);
}
enum MyResult {
annoMethod,
probableKeyword,
localOrParameter,
qualifiedWithField,
qualifiedWithGetter,
superMethodParameters,
normal,
collectionFactory,
expectedTypeMember,
nonInitialized,
classLiteral,
classNameOrGlobalStatic,
}
@NotNull
@Override
public MyResult weigh(@NotNull LookupElement item) {
final Object object = item.getObject();
if (object instanceof PsiKeyword) {
String keyword = ((PsiKeyword)object).getText();
if (PsiKeyword.RETURN.equals(keyword) && isLastStatement(PsiTreeUtil.getParentOfType(myPosition, PsiStatement.class))) {
return MyResult.probableKeyword;
}
if (PsiKeyword.ELSE.equals(keyword) || PsiKeyword.FINALLY.equals(keyword)) {
return MyResult.probableKeyword;
}
}
if (object instanceof PsiLocalVariable || object instanceof PsiParameter || object instanceof PsiThisExpression) {
return MyResult.localOrParameter;
}
if (object instanceof String && item.getUserData(JavaCompletionUtil.SUPER_METHOD_PARAMETERS) == Boolean.TRUE) {
return MyResult.superMethodParameters;
}
if (myCompletionType == CompletionType.SMART) {
if (item.getUserData(CollectionsUtilityMethodsProvider.COLLECTION_FACTORY) != null) {
return MyResult.collectionFactory;
}
if (Boolean.TRUE.equals(item.getUserData(MembersGetter.EXPECTED_TYPE_INHERITOR_MEMBER))) {
return MyResult.expectedTypeMember;
}
final JavaChainLookupElement chain = item.as(JavaChainLookupElement.CLASS_CONDITION_KEY);
if (chain != null) {
Object qualifier = chain.getQualifier().getObject();
if (qualifier instanceof PsiLocalVariable || qualifier instanceof PsiParameter) {
return MyResult.localOrParameter;
}
if (qualifier instanceof PsiField) {
return MyResult.qualifiedWithField;
}
if (qualifier instanceof PsiMethod && PropertyUtil.isSimplePropertyGetter((PsiMethod)qualifier)) {
return MyResult.qualifiedWithGetter;
}
}
return MyResult.normal;
}
if (myCompletionType == CompletionType.BASIC) {
StaticallyImportable callElement = item.as(StaticallyImportable.CLASS_CONDITION_KEY);
if (callElement != null && callElement.canBeImported() && !callElement.willBeImported()) {
return MyResult.classNameOrGlobalStatic;
}
if (object instanceof PsiKeyword && PsiKeyword.CLASS.equals(item.getLookupString())) {
return MyResult.classLiteral;
}
if (object instanceof PsiAnnotationMethod && ((PsiAnnotationMethod)object).getContainingClass().isAnnotationType()) {
return MyResult.annoMethod;
}
if (object instanceof PsiClass) {
return MyResult.classNameOrGlobalStatic;
}
if (object instanceof PsiField && myNonInitializedFields.contains(object)) {
return MyResult.nonInitialized;
}
}
return MyResult.normal;
}
private static boolean isLastStatement(PsiStatement statement) {
if (statement == null || !(statement.getParent() instanceof PsiCodeBlock)) {
return true;
}
PsiStatement[] siblings = ((PsiCodeBlock)statement.getParent()).getStatements();
return statement == siblings[siblings.length - 1];
}
}
@@ -1,159 +1,151 @@
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.daemon.impl.quickfix.StaticImportMethodFix;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.util.Consumer;
import com.intellij.util.PairConsumer;
import com.intellij.util.containers.CollectionFactory;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.intellij.util.containers.CollectionFactory.hashSet;
import static com.intellij.util.containers.ContainerUtil.addIfNotNull;
/**
* @author peter
*/
public abstract class StaticMemberProcessor {
private final Set<PsiClass> myStaticImportedClasses = hashSet();
private final PsiElement myPosition;
private final Project myProject;
private final PsiResolveHelper myResolveHelper;
private boolean myHintShown = false;
private final boolean myPackagedContext;
public StaticMemberProcessor(final PsiElement position) {
myPosition = position;
myProject = myPosition.getProject();
myResolveHelper = JavaPsiFacade.getInstance(myProject).getResolveHelper();
myPackagedContext = JavaCompletionUtil.inSomePackage(position);
}
public void importMembersOf(@Nullable PsiClass psiClass) {
addIfNotNull(myStaticImportedClasses, psiClass);
}
public void processStaticMethodsGlobally(final CompletionResultSet resultSet) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.GLOBAL_MEMBER_NAME);
final Consumer<LookupElement> consumer = new Consumer<LookupElement>() {
@Override
public void consume(LookupElement element) {
resultSet.addElement(element);
}
};
final PrefixMatcher matcher = resultSet.getPrefixMatcher();
final GlobalSearchScope scope = myPosition.getResolveScope();
final PsiShortNamesCache namesCache = PsiShortNamesCache.getInstance(myProject);
for (final String methodName : namesCache.getAllMethodNames()) {
if (matcher.prefixMatches(methodName)) {
Set<PsiClass> classes = new THashSet<PsiClass>();
for (final PsiMethod method : namesCache.getMethodsByName(methodName, scope)) {
if (isStaticallyImportable(method)) {
final PsiClass containingClass = method.getContainingClass();
assert containingClass != null : method.getName() + "; " + method + "; " + method.getClass();
if (classes.add(containingClass) && JavaCompletionUtil.isSourceLevelAccessible(myPosition, containingClass, myPackagedContext)) {
final boolean shouldImport = myStaticImportedClasses.contains(containingClass);
showHint(shouldImport);
final PsiMethod[] allMethods = containingClass.getAllMethods();
final List<PsiMethod> overloads = ContainerUtil.findAll(allMethods, new Condition<PsiMethod>() {
@Override
public boolean value(PsiMethod psiMethod) {
return methodName.equals(psiMethod.getName()) && isStaticallyImportable(psiMethod);
}
});
assert !overloads.isEmpty();
if (overloads.size() == 1) {
assert method == overloads.get(0);
consumer.consume(createLookupElement(method, containingClass, shouldImport));
} else {
if (overloads.get(0).getParameterList().getParametersCount() == 0) {
overloads.add(0, overloads.remove(1));
}
consumer.consume(createLookupElement(overloads, containingClass, shouldImport));
}
}
}
}
}
}
for (final String fieldName : namesCache.getAllFieldNames()) {
if (matcher.prefixMatches(fieldName)) {
for (final PsiField field : namesCache.getFieldsByName(fieldName, scope)) {
if (isStaticallyImportable(field)) {
final PsiClass containingClass = field.getContainingClass();
assert containingClass != null : field.getName() + "; " + field + "; " + field.getClass();
if (JavaCompletionUtil.isSourceLevelAccessible(myPosition, containingClass, myPackagedContext)) {
final boolean shouldImport = myStaticImportedClasses.contains(containingClass);
showHint(shouldImport);
consumer.consume(createLookupElement(field, containingClass, shouldImport));
}
}
}
}
}
}
private void showHint(boolean shouldImport) {
if (!myHintShown && !shouldImport && CompletionService.getCompletionService().getAdvertisementText() == null) {
final String shortcut = CompletionContributor.getActionShortcut(IdeActions.ACTION_SHOW_INTENTION_ACTIONS);
if (shortcut != null) {
CompletionService.getCompletionService().setAdvertisementText("To import a method statically, press " + shortcut);
}
myHintShown = true;
}
}
public List<PsiMember> processMembersOfRegisteredClasses(final PrefixMatcher matcher, PairConsumer<PsiMember, PsiClass> consumer) {
final ArrayList<PsiMember> result = CollectionFactory.arrayList();
for (final PsiClass psiClass : myStaticImportedClasses) {
for (final PsiMethod method : psiClass.getAllMethods()) {
if (matcher.prefixMatches(method.getName())) {
if (isStaticallyImportable(method)) {
consumer.consume(method, psiClass);
}
}
}
for (final PsiField field : psiClass.getAllFields()) {
if (matcher.prefixMatches(field. getName())) {
if (isStaticallyImportable(field)) {
consumer.consume(field, psiClass);
}
}
}
}
return result;
}
private boolean isStaticallyImportable(final PsiMember member) {
return member.hasModifierProperty(PsiModifier.STATIC) && isAccessible(member) && !StaticImportMethodFix.isExcluded(member);
}
protected boolean isAccessible(PsiMember member) {
return myResolveHelper.isAccessible(member, myPosition, null);
}
@NotNull
protected abstract LookupElement createLookupElement(@NotNull PsiMember member, @NotNull PsiClass containingClass, boolean shouldImport);
protected abstract LookupElement createLookupElement(@NotNull List<PsiMethod> overloads, @NotNull PsiClass containingClass, boolean shouldImport);
}
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.daemon.impl.quickfix.StaticImportMethodFix;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.util.Consumer;
import com.intellij.util.PairConsumer;
import com.intellij.util.containers.CollectionFactory;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.intellij.util.containers.CollectionFactory.hashSet;
import static com.intellij.util.containers.ContainerUtil.addIfNotNull;
/**
* @author peter
*/
public abstract class StaticMemberProcessor {
private final Set<PsiClass> myStaticImportedClasses = hashSet();
private final PsiElement myPosition;
private final Project myProject;
private final PsiResolveHelper myResolveHelper;
private boolean myHintShown = false;
private final boolean myPackagedContext;
public StaticMemberProcessor(final PsiElement position) {
myPosition = position;
myProject = myPosition.getProject();
myResolveHelper = JavaPsiFacade.getInstance(myProject).getResolveHelper();
myPackagedContext = JavaCompletionUtil.inSomePackage(position);
}
public void importMembersOf(@Nullable PsiClass psiClass) {
addIfNotNull(myStaticImportedClasses, psiClass);
}
public void processStaticMethodsGlobally(PrefixMatcher matcher, Consumer<LookupElement> consumer) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.GLOBAL_MEMBER_NAME);
final GlobalSearchScope scope = myPosition.getResolveScope();
final PsiShortNamesCache namesCache = PsiShortNamesCache.getInstance(myProject);
for (final String methodName : namesCache.getAllMethodNames()) {
if (matcher.prefixMatches(methodName)) {
Set<PsiClass> classes = new THashSet<PsiClass>();
for (final PsiMethod method : namesCache.getMethodsByName(methodName, scope)) {
if (isStaticallyImportable(method)) {
final PsiClass containingClass = method.getContainingClass();
assert containingClass != null : method.getName() + "; " + method + "; " + method.getClass();
if (classes.add(containingClass) && JavaCompletionUtil.isSourceLevelAccessible(myPosition, containingClass, myPackagedContext)) {
final boolean shouldImport = myStaticImportedClasses.contains(containingClass);
showHint(shouldImport);
final PsiMethod[] allMethods = containingClass.getAllMethods();
final List<PsiMethod> overloads = ContainerUtil.findAll(allMethods, new Condition<PsiMethod>() {
@Override
public boolean value(PsiMethod psiMethod) {
return methodName.equals(psiMethod.getName()) && isStaticallyImportable(psiMethod);
}
});
assert !overloads.isEmpty();
if (overloads.size() == 1) {
assert method == overloads.get(0);
consumer.consume(createLookupElement(method, containingClass, shouldImport));
} else {
if (overloads.get(0).getParameterList().getParametersCount() == 0) {
overloads.add(0, overloads.remove(1));
}
consumer.consume(createLookupElement(overloads, containingClass, shouldImport));
}
}
}
}
}
}
for (final String fieldName : namesCache.getAllFieldNames()) {
if (matcher.prefixMatches(fieldName)) {
for (final PsiField field : namesCache.getFieldsByName(fieldName, scope)) {
if (isStaticallyImportable(field)) {
final PsiClass containingClass = field.getContainingClass();
assert containingClass != null : field.getName() + "; " + field + "; " + field.getClass();
if (JavaCompletionUtil.isSourceLevelAccessible(myPosition, containingClass, myPackagedContext)) {
final boolean shouldImport = myStaticImportedClasses.contains(containingClass);
showHint(shouldImport);
consumer.consume(createLookupElement(field, containingClass, shouldImport));
}
}
}
}
}
}
private void showHint(boolean shouldImport) {
if (!myHintShown && !shouldImport && CompletionService.getCompletionService().getAdvertisementText() == null) {
final String shortcut = CompletionContributor.getActionShortcut(IdeActions.ACTION_SHOW_INTENTION_ACTIONS);
if (shortcut != null) {
CompletionService.getCompletionService().setAdvertisementText("To import a method statically, press " + shortcut);
}
myHintShown = true;
}
}
public List<PsiMember> processMembersOfRegisteredClasses(final PrefixMatcher matcher, PairConsumer<PsiMember, PsiClass> consumer) {
final ArrayList<PsiMember> result = CollectionFactory.arrayList();
for (final PsiClass psiClass : myStaticImportedClasses) {
for (final PsiMethod method : psiClass.getAllMethods()) {
if (matcher.prefixMatches(method.getName())) {
if (isStaticallyImportable(method)) {
consumer.consume(method, psiClass);
}
}
}
for (final PsiField field : psiClass.getAllFields()) {
if (matcher.prefixMatches(field. getName())) {
if (isStaticallyImportable(field)) {
consumer.consume(field, psiClass);
}
}
}
}
return result;
}
private boolean isStaticallyImportable(final PsiMember member) {
return member.hasModifierProperty(PsiModifier.STATIC) && isAccessible(member) && !StaticImportMethodFix.isExcluded(member);
}
protected boolean isAccessible(PsiMember member) {
return myResolveHelper.isAccessible(member, myPosition, null);
}
@NotNull
protected abstract LookupElement createLookupElement(@NotNull PsiMember member, @NotNull PsiClass containingClass, boolean shouldImport);
protected abstract LookupElement createLookupElement(@NotNull List<PsiMethod> overloads, @NotNull PsiClass containingClass, boolean shouldImport);
}
@@ -1,45 +1,59 @@
/*
* 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.codeInsight.completion;
import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.lang.StdLanguages;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
/**
* @author peter
*/
public class XmlBasicToClassNameDelegator extends AbstractBasicToClassNameDelegator {
@Override
protected boolean isClassNameCompletionSupported(CompletionResultSet result, PsiFile file, PsiElement position) {
if (!JavaCompletionContributor.mayStartClassName(result)) return false;
return file.getLanguage().isKindOf(StdLanguages.XML);
}
@Override
protected void updateProperties(LookupElement lookupElement) {
JavaPsiClassReferenceElement classElement = lookupElement.as(JavaPsiClassReferenceElement.CLASS_CONDITION_KEY);
if (classElement != null) {
classElement.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
}
lookupElement.putUserData(XmlCompletionContributor.WORD_COMPLETION_COMPATIBLE, Boolean.TRUE); //todo think of a less dirty interaction
}
}
/*
* 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.codeInsight.completion;
import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.lang.StdLanguages;
import com.intellij.psi.PsiElement;
import com.intellij.util.Consumer;
/**
* @author peter
*/
public class XmlBasicToClassNameDelegator extends CompletionContributor {
@Override
public void fillCompletionVariants(CompletionParameters parameters, final CompletionResultSet result) {
PsiElement position = parameters.getPosition();
if (parameters.getCompletionType() != CompletionType.BASIC ||
!JavaCompletionContributor.mayStartClassName(result) ||
!position.getContainingFile().getLanguage().isKindOf(StdLanguages.XML)) {
return;
}
final boolean empty = result.runRemainingContributors(parameters, true).isEmpty();
if (!empty && parameters.getInvocationCount() == 0) {
result.restartCompletionWhenNothingMatches();
}
if (empty || parameters.isExtendedCompletion()) {
CompletionService.getCompletionService().getVariantsFromContributors(parameters.delegateToClassName(), null, new Consumer<CompletionResult>() {
public void consume(final CompletionResult completionResult) {
LookupElement lookupElement = completionResult.getLookupElement();
JavaPsiClassReferenceElement classElement = lookupElement.as(JavaPsiClassReferenceElement.CLASS_CONDITION_KEY);
if (classElement != null) {
classElement.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
}
lookupElement.putUserData(XmlCompletionContributor.WORD_COMPLETION_COMPATIBLE, Boolean.TRUE); //todo think of a less dirty interaction
result.passResult(completionResult);
}
});
}
}
}
@@ -1,73 +1,129 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.daemon.QuickFixActionRegistrar;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightMethodUtil;
import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
public class DefaultQuickFixProvider extends UnresolvedReferenceQuickFixProvider<PsiJavaCodeReferenceElement> {
@Override
public void registerFixes(PsiJavaCodeReferenceElement ref, QuickFixActionRegistrar registrar) {
registrar.register(new ImportClassFix(ref));
registrar.register(SetupJDKFix.getInstance());
OrderEntryFix.registerFixes(registrar, ref);
MoveClassToModuleFix.registerFixes(registrar, ref);
if (ref instanceof PsiReferenceExpression) {
TextRange fixRange = HighlightMethodUtil.getFixRange(ref);
PsiReferenceExpression refExpr = (PsiReferenceExpression)ref;
registrar.register(fixRange, new CreateEnumConstantFromUsageFix(refExpr), null);
registrar.register(fixRange, new CreateConstantFieldFromUsageFix(refExpr), null);
registrar.register(fixRange, new CreateFieldFromUsageFix(refExpr), null);
registrar.register(new RenameWrongRefFix(refExpr));
if (!ref.isQualified()) {
registrar.register(fixRange, new BringVariableIntoScopeFix(refExpr), null);
registrar.register(fixRange, new CreateLocalFromUsageFix(refExpr), null);
registrar.register(fixRange, new CreateParameterFromUsageFix(refExpr), null);
}
}
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.INTERFACE));
if (PsiUtil.isLanguageLevel5OrHigher(ref)) {
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.ENUM));
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.ANNOTATION));
}
PsiElement parent = PsiTreeUtil.getParentOfType(ref, PsiNewExpression.class, PsiMethod.class);
final PsiExpressionList expressionList = PsiTreeUtil.getParentOfType(ref, PsiExpressionList.class);
if (parent instanceof PsiNewExpression && !(ref.getParent() instanceof PsiTypeElement) && (expressionList == null || !PsiTreeUtil.isAncestor(parent, expressionList, false))) {
registrar.register(new CreateClassFromNewFix((PsiNewExpression)parent));
registrar.register(new CreateInnerClassFromNewFix((PsiNewExpression)parent));
}
else {
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.CLASS));
registrar.register(new CreateInnerClassFromUsageFix(ref, CreateClassKind.CLASS));
}
}
@Override
@NotNull
public Class<PsiJavaCodeReferenceElement> getReferenceClass() {
return PsiJavaCodeReferenceElement.class;
}
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.daemon.QuickFixActionRegistrar;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightMethodUtil;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.impl.PriorityIntentionActionWrapper;
import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class DefaultQuickFixProvider extends UnresolvedReferenceQuickFixProvider<PsiJavaCodeReferenceElement> {
@Override
public void registerFixes(PsiJavaCodeReferenceElement ref, QuickFixActionRegistrar registrar) {
registrar.register(new ImportClassFix(ref));
registrar.register(SetupJDKFix.getInstance());
OrderEntryFix.registerFixes(registrar, ref);
MoveClassToModuleFix.registerFixes(registrar, ref);
if (ref instanceof PsiReferenceExpression) {
TextRange fixRange = HighlightMethodUtil.getFixRange(ref);
PsiReferenceExpression refExpr = (PsiReferenceExpression)ref;
registrar.register(fixRange, new CreateEnumConstantFromUsageFix(refExpr), null);
registrar.register(new RenameWrongRefFix(refExpr));
if (!ref.isQualified()) {
registrar.register(fixRange, new BringVariableIntoScopeFix(refExpr), null);
}
registerPriorityActions(registrar,fixRange,refExpr);
}
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.INTERFACE));
if (PsiUtil.isLanguageLevel5OrHigher(ref)) {
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.ENUM));
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.ANNOTATION));
}
PsiElement parent = PsiTreeUtil.getParentOfType(ref, PsiNewExpression.class, PsiMethod.class);
final PsiExpressionList expressionList = PsiTreeUtil.getParentOfType(ref, PsiExpressionList.class);
if (parent instanceof PsiNewExpression && !(ref.getParent() instanceof PsiTypeElement) && (expressionList == null || !PsiTreeUtil.isAncestor(parent, expressionList, false))) {
registrar.register(new CreateClassFromNewFix((PsiNewExpression)parent));
registrar.register(new CreateInnerClassFromNewFix((PsiNewExpression)parent));
}
else {
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.CLASS));
registrar.register(new CreateInnerClassFromUsageFix(ref, CreateClassKind.CLASS));
}
}
private static void registerPriorityActions(@NotNull final QuickFixActionRegistrar registrar,
@NotNull final TextRange fixRange,
@NotNull final PsiReferenceExpression refExpr) {
final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(refExpr.getProject());
final Map<VariableKind, IntentionAction> map = new HashMap<VariableKind, IntentionAction>() {
{
put(VariableKind.FIELD, new CreateFieldFromUsageFix(refExpr));
put(VariableKind.STATIC_FINAL_FIELD, new CreateConstantFieldFromUsageFix(refExpr));
if (!refExpr.isQualified()) {
put(VariableKind.LOCAL_VARIABLE, new CreateLocalFromUsageFix(refExpr));
put(VariableKind.PARAMETER, new CreateParameterFromUsageFix(refExpr));
}
}
};
final VariableKind kind = getKind(styleManager, refExpr);
if (map.containsKey(kind)){
map.put(kind, PriorityIntentionActionWrapper.highPriority(map.get(kind)));
}
for (IntentionAction action : map.values()){
registrar.register(fixRange, action, null);
}
}
@NotNull
private static VariableKind getKind(@NotNull JavaCodeStyleManager styleManager,
@NotNull PsiReferenceExpression refExpr) {
final String reference = refExpr.getText();
if (reference.toUpperCase().equals(reference)){
return VariableKind.STATIC_FINAL_FIELD;
}
for (VariableKind kind : VariableKind.values()) {
final String prefix = styleManager.getPrefixByVariableKind(kind);
final String suffix = styleManager.getSuffixByVariableKind(kind);
if (prefix.isEmpty() && suffix.isEmpty()) {
continue;
}
if (reference.startsWith(prefix) && reference.endsWith(suffix)) {
return kind;
}
}
return VariableKind.LOCAL_VARIABLE;
}
@Override
@NotNull
public Class<PsiJavaCodeReferenceElement> getReferenceClass() {
return PsiJavaCodeReferenceElement.class;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,109 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.intention.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
/**
* @author Danila Ponomarenko
*/
public class BreakStringOnLineBreaksIntentionAction extends PsiElementBaseIntentionAction {
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
if (!(element instanceof PsiJavaToken)) {
return false;
}
final PsiJavaToken token = (PsiJavaToken)element;
if (token.getTokenType() != JavaTokenType.STRING_LITERAL) {
return false;
}
final String text = token.getText();
if (text == null) {
return false;
}
final int indexOfSlashN = text.indexOf("\\n");
if (indexOfSlashN == -1 || Comparing.equal(text.substring(indexOfSlashN, text.length()), "\\n\"")){
return false;
}
final int indexOfSlashNSlashR = text.indexOf("\\n\\r");
if (indexOfSlashNSlashR != -1 && Comparing.equal(text.substring(indexOfSlashNSlashR, text.length()), "\\n\\r\"")){
return false;
}
return true;
}
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
if (!(element instanceof PsiJavaToken)) {
return;
}
final PsiJavaToken token = (PsiJavaToken)element;
if (token.getTokenType() != JavaTokenType.STRING_LITERAL) {
return;
}
final String text = token.getText();
if (text == null) {
return;
}
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
token.replace(factory.createExpressionFromText(breakOnLineBreaks(text), element));
}
@NotNull
private static String breakOnLineBreaks(@NotNull String string) {
final String result = StringUtil.replace(
string,
new String[]{"\\n\\r", "\\n"},
new String[]{"\\n\\r\" + \n\"", "\\n\" + \n\""}
);
final String redundantSuffix = " + \n\"\"";
return result.endsWith(redundantSuffix) ? result.substring(0, result.length() - redundantSuffix.length()) : result;
}
@NotNull
@Override
public String getText() {
return CodeInsightBundle.message("intention.break.string.on.line.breaks.text");
}
@NotNull
@Override
public String getFamilyName() {
return getText();
}
}
@@ -1,67 +1,67 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInspection.internal;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.psi.*;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
public class FileEqualsUsageInspection extends InternalInspection {
@Nls
@NotNull
@Override
public String getDisplayName() {
return "File.equals()/hashCode()/compareTo() Usage";
}
@NotNull
@Override
public String getShortName() {
return "FileEqualsUsage";
}
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
if (!ApplicationManagerEx.getApplicationEx().isInternal()) {
return new JavaElementVisitor() {
};
}
return new JavaElementVisitor() {
@Override
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
PsiReferenceExpression methodExpression = expression.getMethodExpression();
PsiElement resolved = methodExpression.resolve();
if (!(resolved instanceof PsiMethod)) return;
PsiMethod method = (PsiMethod)resolved;
PsiClass clazz = method.getContainingClass();
if (clazz == null) return;
String methodName = method.getName();
if ("java.io.File".equals(clazz.getQualifiedName())
&& ("equals".equals(methodName) || "compareTo".equals(methodName) || "hashCode".equals(methodName))) {
holder.registerProblem(methodExpression,
"Do not use File.equals/hashCode/compareTo as they don't honor case-sensitivity on MacOS. Use FileUtil.filesEquals/fileHashCode/compareFiles instead",
ProblemHighlightType.LIKE_DEPRECATED);
}
}
};
}
}
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInspection.internal;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.psi.*;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
public class FileEqualsUsageInspection extends InternalInspection {
@Nls
@NotNull
@Override
public String getDisplayName() {
return "File.equals()/hashCode()/compareTo() Usage";
}
@NotNull
@Override
public String getShortName() {
return "FileEqualsUsage";
}
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
if (!ApplicationManagerEx.getApplicationEx().isInternal()) {
return new JavaElementVisitor() {
};
}
return new JavaElementVisitor() {
@Override
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
PsiReferenceExpression methodExpression = expression.getMethodExpression();
PsiElement resolved = methodExpression.resolve();
if (!(resolved instanceof PsiMethod)) return;
PsiMethod method = (PsiMethod)resolved;
PsiClass clazz = method.getContainingClass();
if (clazz == null) return;
String methodName = method.getName();
if (CommonClassNames.JAVA_IO_FILE.equals(clazz.getQualifiedName())
&& ("equals".equals(methodName) || "compareTo".equals(methodName) || "hashCode".equals(methodName))) {
holder.registerProblem(methodExpression,
"Do not use File.equals/hashCode/compareTo as they don't honor case-sensitivity on MacOS. Use FileUtil.filesEquals/fileHashCode/compareFiles instead",
ProblemHighlightType.LIKE_DEPRECATED);
}
}
};
}
}
@@ -1,161 +1,161 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.filters.getters;
import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.TailTypeDecorator;
import com.intellij.codeInsight.lookup.VariableLookupItem;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashSet;
import java.util.Set;
/**
* @author peter
*/
public class JavaMembersGetter extends MembersGetter {
private final PsiType myExpectedType;
private final PsiElement myPlace;
public JavaMembersGetter(@NotNull PsiType expectedType, PsiElement place) {
myPlace = place;
myExpectedType = JavaCompletionUtil.originalize(expectedType);
}
public void addMembers(CompletionParameters parameters, boolean searchInheritors, final Consumer<LookupElement> results) {
final StaticMemberProcessor processor = JavaGlobalMemberNameCompletionContributor.completeStaticMembers(parameters);
final PsiElement position = parameters.getPosition();
if (myExpectedType instanceof PsiPrimitiveType && PsiType.DOUBLE.isAssignableFrom(myExpectedType)) {
addConstantsFromTargetClass(position, results, searchInheritors, processor);
addConstantsFromReferencedClassesInSwitch(position, results, processor);
}
if (position.getParent().getParent() instanceof PsiSwitchLabelStatement) {
return; //non-enum values are processed above, enum values will be suggested by reference completion
}
final PsiClass psiClass = PsiUtil.resolveClassInType(myExpectedType);
processMembers(position, results, psiClass, PsiTreeUtil.getParentOfType(position, PsiAnnotation.class) != null, searchInheritors, processor);
}
private void addConstantsFromReferencedClassesInSwitch(PsiElement position, final Consumer<LookupElement> results, final StaticMemberProcessor processor) {
final Set<PsiField> fields = ReferenceExpressionCompletionContributor.findConstantsUsedInSwitch(position);
final Set<PsiClass> classes = new HashSet<PsiClass>();
for (PsiField field : fields) {
ContainerUtil.addIfNotNull(classes, field.getContainingClass());
}
for (PsiClass aClass : classes) {
processMembers(position, new Consumer<LookupElement>() {
@Override
public void consume(LookupElement element) {
//noinspection SuspiciousMethodCalls
if (!fields.contains(element.getObject())) {
results.consume(TailTypeDecorator.withTail(element, TailType.CASE_COLON));
}
}
}, aClass, false, false, processor);
}
}
private void addConstantsFromTargetClass(PsiElement position,
Consumer<LookupElement> results,
boolean searchInheritors, final StaticMemberProcessor processor) {
PsiElement parent = position.getParent();
if (!(parent instanceof PsiReferenceExpression)) {
return;
}
PsiElement prev = parent;
parent = parent.getParent();
while (parent instanceof PsiBinaryExpression) {
final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)parent;
final IElementType op = binaryExpression.getOperationTokenType();
if (JavaTokenType.EQEQ == op || JavaTokenType.NE == op) {
if (prev == binaryExpression.getROperand()) {
processMembers(position, results, getCalledClass(binaryExpression.getLOperand()), false, searchInheritors,
processor);
}
return;
}
prev = parent;
parent = parent.getParent();
}
if (parent instanceof PsiExpressionList) {
processMembers(position, results, getCalledClass(parent.getParent()), false, searchInheritors, processor);
}
}
@Nullable
private static PsiClass getCalledClass(@Nullable PsiElement call) {
if (call instanceof PsiMethodCallExpression) {
for (final JavaResolveResult result : ((PsiMethodCallExpression)call).getMethodExpression().multiResolve(true)) {
final PsiElement element = result.getElement();
if (element instanceof PsiMethod) {
final PsiClass aClass = ((PsiMethod)element).getContainingClass();
if (aClass != null) {
return aClass;
}
}
}
}
if (call instanceof PsiNewExpression) {
final PsiJavaCodeReferenceElement reference = ((PsiNewExpression)call).getClassReference();
if (reference != null) {
for (final JavaResolveResult result : reference.multiResolve(true)) {
final PsiElement element = result.getElement();
if (element instanceof PsiClass) {
return (PsiClass)element;
}
}
}
}
return null;
}
@Override
@Nullable
protected LookupElement createFieldElement(PsiField field) {
if (!myExpectedType.isAssignableFrom(field.getType())) {
return null;
}
return new VariableLookupItem(field, false);
}
@Override
@Nullable
protected LookupElement createMethodElement(PsiMethod method) {
PsiSubstitutor substitutor = SmartCompletionDecorator.calculateMethodReturnTypeSubstitutor(method, myExpectedType);
PsiType type = substitutor.substitute(method.getReturnType());
if (type == null || !myExpectedType.isAssignableFrom(type)) {
return null;
}
JavaMethodCallElement item = new JavaMethodCallElement(method, false, false);
item.setInferenceSubstitutor(substitutor, myPlace);
return item;
}
}
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.filters.getters;
import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.TailTypeDecorator;
import com.intellij.codeInsight.lookup.VariableLookupItem;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashSet;
import java.util.Set;
/**
* @author peter
*/
public class JavaMembersGetter extends MembersGetter {
private final PsiType myExpectedType;
private final PsiElement myPlace;
public JavaMembersGetter(@NotNull PsiType expectedType, PsiElement place) {
myPlace = place;
myExpectedType = JavaCompletionUtil.originalize(expectedType);
}
public void addMembers(CompletionParameters parameters, boolean searchInheritors, final Consumer<LookupElement> results) {
final StaticMemberProcessor processor = new JavaStaticMemberProcessor(parameters);
final PsiElement position = parameters.getPosition();
if (myExpectedType instanceof PsiPrimitiveType && PsiType.DOUBLE.isAssignableFrom(myExpectedType)) {
addConstantsFromTargetClass(position, results, searchInheritors, processor);
addConstantsFromReferencedClassesInSwitch(position, results, processor);
}
if (position.getParent().getParent() instanceof PsiSwitchLabelStatement) {
return; //non-enum values are processed above, enum values will be suggested by reference completion
}
final PsiClass psiClass = PsiUtil.resolveClassInType(myExpectedType);
processMembers(position, results, psiClass, PsiTreeUtil.getParentOfType(position, PsiAnnotation.class) != null, searchInheritors, processor);
}
private void addConstantsFromReferencedClassesInSwitch(PsiElement position, final Consumer<LookupElement> results, final StaticMemberProcessor processor) {
final Set<PsiField> fields = ReferenceExpressionCompletionContributor.findConstantsUsedInSwitch(position);
final Set<PsiClass> classes = new HashSet<PsiClass>();
for (PsiField field : fields) {
ContainerUtil.addIfNotNull(classes, field.getContainingClass());
}
for (PsiClass aClass : classes) {
processMembers(position, new Consumer<LookupElement>() {
@Override
public void consume(LookupElement element) {
//noinspection SuspiciousMethodCalls
if (!fields.contains(element.getObject())) {
results.consume(TailTypeDecorator.withTail(element, TailType.CASE_COLON));
}
}
}, aClass, false, false, processor);
}
}
private void addConstantsFromTargetClass(PsiElement position,
Consumer<LookupElement> results,
boolean searchInheritors, final StaticMemberProcessor processor) {
PsiElement parent = position.getParent();
if (!(parent instanceof PsiReferenceExpression)) {
return;
}
PsiElement prev = parent;
parent = parent.getParent();
while (parent instanceof PsiBinaryExpression) {
final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)parent;
final IElementType op = binaryExpression.getOperationTokenType();
if (JavaTokenType.EQEQ == op || JavaTokenType.NE == op) {
if (prev == binaryExpression.getROperand()) {
processMembers(position, results, getCalledClass(binaryExpression.getLOperand()), false, searchInheritors,
processor);
}
return;
}
prev = parent;
parent = parent.getParent();
}
if (parent instanceof PsiExpressionList) {
processMembers(position, results, getCalledClass(parent.getParent()), false, searchInheritors, processor);
}
}
@Nullable
private static PsiClass getCalledClass(@Nullable PsiElement call) {
if (call instanceof PsiMethodCallExpression) {
for (final JavaResolveResult result : ((PsiMethodCallExpression)call).getMethodExpression().multiResolve(true)) {
final PsiElement element = result.getElement();
if (element instanceof PsiMethod) {
final PsiClass aClass = ((PsiMethod)element).getContainingClass();
if (aClass != null) {
return aClass;
}
}
}
}
if (call instanceof PsiNewExpression) {
final PsiJavaCodeReferenceElement reference = ((PsiNewExpression)call).getClassReference();
if (reference != null) {
for (final JavaResolveResult result : reference.multiResolve(true)) {
final PsiElement element = result.getElement();
if (element instanceof PsiClass) {
return (PsiClass)element;
}
}
}
}
return null;
}
@Override
@Nullable
protected LookupElement createFieldElement(PsiField field) {
if (!myExpectedType.isAssignableFrom(field.getType())) {
return null;
}
return new VariableLookupItem(field, false);
}
@Override
@Nullable
protected LookupElement createMethodElement(PsiMethod method) {
PsiSubstitutor substitutor = SmartCompletionDecorator.calculateMethodReturnTypeSubstitutor(method, myExpectedType);
PsiType type = substitutor.substitute(method.getReturnType());
if (type == null || !myExpectedType.isAssignableFrom(type)) {
return null;
}
JavaMethodCallElement item = new JavaMethodCallElement(method, false, false);
item.setInferenceSubstitutor(substitutor, myPlace);
return item;
}
}
File diff suppressed because it is too large Load Diff
@@ -1,110 +1,111 @@
/*
* 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.formatter.java;
import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.impl.source.codeStyle.ShiftIndentInsideHelper;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class LeafBlock implements ASTBlock{
private int myStartOffset = -1;
private final ASTNode myNode;
private final Wrap myWrap;
private final Alignment myAlignment;
private static final ArrayList<Block> EMPTY_SUB_BLOCKS = new ArrayList<Block>();
private final Indent myIndent;
public LeafBlock(final ASTNode node,
final Wrap wrap,
final Alignment alignment,
Indent indent) {
myNode = node;
myWrap = wrap;
myAlignment = alignment;
myIndent = indent;
}
@Override
public ASTNode getNode() {
return myNode;
}
@Override
@NotNull
public TextRange getTextRange() {
if (myStartOffset != -1) {
return new TextRange(myStartOffset, myStartOffset + myNode.getTextLength());
}
return myNode.getTextRange();
}
@Override
@NotNull
public List<Block> getSubBlocks() {
return EMPTY_SUB_BLOCKS;
}
@Override
public Wrap getWrap() {
return myWrap;
}
@Override
public Indent getIndent() {
return myIndent;
}
@Override
public Alignment getAlignment() {
return myAlignment;
}
@Override
public Spacing getSpacing(Block child1, Block child2) {
return null;
}
public ASTNode getTreeNode() {
return myNode;
}
@Override
@NotNull
public ChildAttributes getChildAttributes(final int newChildIndex) {
return new ChildAttributes(getIndent(), null);
}
@Override
public boolean isIncomplete() {
return false;
}
@Override
public boolean isLeaf() {
return ShiftIndentInsideHelper.mayShiftIndentInside(myNode);
}
public void setStartOffset(final int startOffset) {
myStartOffset = startOffset;
// if (startOffset != -1) assert startOffset == myNode.getTextRange().getStartOffset();
}
}
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.formatter.java;
import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.impl.source.codeStyle.ShiftIndentInsideHelper;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class LeafBlock implements ASTBlock{
private int myStartOffset = -1;
private final ASTNode myNode;
private final Wrap myWrap;
private final Alignment myAlignment;
private static final ArrayList<Block> EMPTY_SUB_BLOCKS = new ArrayList<Block>();
private final Indent myIndent;
public LeafBlock(final ASTNode node,
final Wrap wrap,
final Alignment alignment,
Indent indent)
{
myNode = node;
myWrap = wrap;
myAlignment = alignment;
myIndent = indent;
}
@Override
public ASTNode getNode() {
return myNode;
}
@Override
@NotNull
public TextRange getTextRange() {
if (myStartOffset != -1) {
return new TextRange(myStartOffset, myStartOffset + myNode.getTextLength());
}
return myNode.getTextRange();
}
@Override
@NotNull
public List<Block> getSubBlocks() {
return EMPTY_SUB_BLOCKS;
}
@Override
public Wrap getWrap() {
return myWrap;
}
@Override
public Indent getIndent() {
return myIndent;
}
@Override
public Alignment getAlignment() {
return myAlignment;
}
@Override
public Spacing getSpacing(Block child1, Block child2) {
return null;
}
public ASTNode getTreeNode() {
return myNode;
}
@Override
@NotNull
public ChildAttributes getChildAttributes(final int newChildIndex) {
return new ChildAttributes(getIndent(), null);
}
@Override
public boolean isIncomplete() {
return false;
}
@Override
public boolean isLeaf() {
return ShiftIndentInsideHelper.mayShiftIndentInside(myNode);
}
public void setStartOffset(final int startOffset) {
myStartOffset = startOffset;
// if (startOffset != -1) assert startOffset == myNode.getTextRange().getStartOffset();
}
}
@@ -1,133 +1,134 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.formatter.java;
import com.intellij.formatting.*;
import com.intellij.formatting.alignment.AlignmentStrategy;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.formatter.FormatterUtil;
import com.intellij.psi.impl.source.tree.JavaDocElementType;
import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.impl.source.tree.StdTokenSets;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SimpleJavaBlock extends AbstractJavaBlock {
private int myStartOffset = -1;
private final Map<IElementType, Wrap> myReservedWrap = new HashMap<IElementType, Wrap>();
public SimpleJavaBlock(final ASTNode node, final Wrap wrap, final AlignmentStrategy alignment, final Indent indent, CommonCodeStyleSettings settings) {
super(node, wrap, alignment, indent,settings);
}
@Override
protected List<Block> buildChildren() {
ASTNode child = myNode.getFirstChildNode();
int offset = myStartOffset != -1 ? myStartOffset : child != null ? child.getTextRange().getStartOffset():0;
final ArrayList<Block> result = new ArrayList<Block>();
Indent indent = null;
while (child != null) {
if (StdTokenSets.COMMENT_BIT_SET.contains(child.getElementType()) || child.getElementType() == JavaDocElementType.DOC_COMMENT) {
result.add(createJavaBlock(child, mySettings, Indent.getNoneIndent(), null, AlignmentStrategy.getNullStrategy()));
indent = Indent.getNoneIndent();
}
else if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
break;
}
offset += child.getTextLength();
child = child.getTreeNext();
}
myReservedAlignment = createChildAlignment();
myReservedAlignment2 = createChildAlignment2(myReservedAlignment);
Wrap childWrap = createChildWrap();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0){
final ASTNode astNode = child;
AlignmentStrategy alignmentStrategyToUse = ALIGN_IN_COLUMNS_ELEMENT_TYPES.contains(myNode.getElementType()) ? myAlignmentStrategy
: AlignmentStrategy.wrap(chooseAlignment(myReservedAlignment, myReservedAlignment2, child));
child = processChild(result, astNode, alignmentStrategyToUse, childWrap, indent, offset);
if (astNode != child && child != null) {
offset = child.getTextRange().getStartOffset();
}
if (indent != null
&& !(myNode.getPsi() instanceof PsiFile) && child != null && child.getElementType() != JavaElementType.MODIFIER_LIST)
{
indent = Indent.getContinuationIndent(myIndentSettings.USE_RELATIVE_INDENTS);
}
}
if (child != null) {
offset += child.getTextLength();
child = child.getTreeNext();
}
}
return result;
}
@Override
@NotNull
public TextRange getTextRange() {
if (myStartOffset != -1) {
return new TextRange(myStartOffset, myStartOffset + myNode.getTextLength());
}
return super.getTextRange();
}
@Override
@NotNull
public ChildAttributes getChildAttributes(final int newChildIndex) {
if (myNode.getElementType() == JavaElementType.CONDITIONAL_EXPRESSION && mySettings.ALIGN_MULTILINE_TERNARY_OPERATION) {
final Alignment usedAlignment = getUsedAlignment(newChildIndex);
if (usedAlignment != null) {
return new ChildAttributes(null, usedAlignment);
} else {
return super.getChildAttributes(newChildIndex);
}
}
else if (myNode.getElementType() == JavaElementType.SWITCH_LABEL_STATEMENT) {
return new ChildAttributes(Indent.getNormalIndent(), null);
}
else {
return super.getChildAttributes(newChildIndex);
}
}
@Override
public Wrap getReservedWrap(final IElementType elementType) {
return myReservedWrap.get(elementType);
}
@Override
protected void setReservedWrap(final Wrap reservedWrap, final IElementType operationType) {
myReservedWrap.put(operationType, reservedWrap);
}
public void setStartOffset(final int startOffset) {
myStartOffset = startOffset;
}
}
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.formatter.java;
import com.intellij.formatting.*;
import com.intellij.formatting.alignment.AlignmentStrategy;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.formatter.FormatterUtil;
import com.intellij.psi.impl.source.tree.JavaDocElementType;
import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.impl.source.tree.StdTokenSets;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SimpleJavaBlock extends AbstractJavaBlock {
private int myStartOffset = -1;
private final Map<IElementType, Wrap> myReservedWrap = new HashMap<IElementType, Wrap>();
public SimpleJavaBlock(final ASTNode node, final Wrap wrap, final AlignmentStrategy alignment, final Indent indent, CommonCodeStyleSettings settings) {
super(node, wrap, alignment, indent,settings);
}
@Override
protected List<Block> buildChildren() {
ASTNode child = myNode.getFirstChildNode();
int offset = myStartOffset != -1 ? myStartOffset : child != null ? child.getTextRange().getStartOffset():0;
final ArrayList<Block> result = new ArrayList<Block>();
Indent indent = null;
while (child != null) {
if (StdTokenSets.COMMENT_BIT_SET.contains(child.getElementType()) || child.getElementType() == JavaDocElementType.DOC_COMMENT) {
result.add(createJavaBlock(child, mySettings, Indent.getNoneIndent(), null, AlignmentStrategy.getNullStrategy()));
indent = Indent.getNoneIndent();
}
else if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
break;
}
offset += child.getTextLength();
child = child.getTreeNext();
}
myReservedAlignment = createChildAlignment();
myReservedAlignment2 = createChildAlignment2(myReservedAlignment);
Wrap childWrap = createChildWrap();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0){
final ASTNode astNode = child;
AlignmentStrategy alignmentStrategyToUse = ALIGN_IN_COLUMNS_ELEMENT_TYPES.contains(myNode.getElementType())
? myAlignmentStrategy
: AlignmentStrategy.wrap(chooseAlignment(myReservedAlignment, myReservedAlignment2, child));
child = processChild(result, astNode, alignmentStrategyToUse, childWrap, indent, offset);
if (astNode != child && child != null) {
offset = child.getTextRange().getStartOffset();
}
if (indent != null
&& !(myNode.getPsi() instanceof PsiFile) && child != null && child.getElementType() != JavaElementType.MODIFIER_LIST)
{
indent = Indent.getContinuationIndent(myIndentSettings.USE_RELATIVE_INDENTS);
}
}
if (child != null) {
offset += child.getTextLength();
child = child.getTreeNext();
}
}
return result;
}
@Override
@NotNull
public TextRange getTextRange() {
if (myStartOffset != -1) {
return new TextRange(myStartOffset, myStartOffset + myNode.getTextLength());
}
return super.getTextRange();
}
@Override
@NotNull
public ChildAttributes getChildAttributes(final int newChildIndex) {
if (myNode.getElementType() == JavaElementType.CONDITIONAL_EXPRESSION && mySettings.ALIGN_MULTILINE_TERNARY_OPERATION) {
final Alignment usedAlignment = getUsedAlignment(newChildIndex);
if (usedAlignment != null) {
return new ChildAttributes(null, usedAlignment);
} else {
return super.getChildAttributes(newChildIndex);
}
}
else if (myNode.getElementType() == JavaElementType.SWITCH_LABEL_STATEMENT) {
return new ChildAttributes(Indent.getNormalIndent(), null);
}
else {
return super.getChildAttributes(newChildIndex);
}
}
@Override
public Wrap getReservedWrap(final IElementType elementType) {
return myReservedWrap.get(elementType);
}
@Override
protected void setReservedWrap(final Wrap reservedWrap, final IElementType operationType) {
myReservedWrap.put(operationType, reservedWrap);
}
public void setStartOffset(final int startOffset) {
myStartOffset = startOffset;
}
}
@@ -1,65 +1,65 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ModuleRootManager;
import org.intellij.lang.regexp.RegExpLanguageHost;
import org.intellij.lang.regexp.psi.RegExpGroup;
/**
* @author yole
*/
public class JavaRegExpHost implements RegExpLanguageHost {
@Override
public boolean characterNeedsEscaping(char c) {
return c == ']' || c == '}';
}
@Override
public boolean supportsPerl5EmbeddedComments() {
return false;
}
@Override
public boolean supportsPossessiveQuantifiers() {
return false;
}
@Override
public boolean supportsPythonConditionalRefs() {
return false;
}
@Override
public boolean supportsNamedGroupSyntax(RegExpGroup group) {
if (group.isRubyNamedGroup()) {
final Module module = ModuleUtil.findModuleForPsiElement(group);
if (module != null) {
final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
if (sdk != null && sdk.getSdkType() instanceof JavaSdk) {
final JavaSdkVersion version = JavaSdk.getInstance().getVersion(sdk);
return version != null && version.isAtLeast(JavaSdkVersion.JDK_1_7);
}
}
}
return false;
}
}
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ModuleRootManager;
import org.intellij.lang.regexp.RegExpLanguageHost;
import org.intellij.lang.regexp.psi.RegExpGroup;
/**
* @author yole
*/
public class JavaRegExpHost implements RegExpLanguageHost {
@Override
public boolean characterNeedsEscaping(char c) {
return c == ']' || c == '}';
}
@Override
public boolean supportsPerl5EmbeddedComments() {
return false;
}
@Override
public boolean supportsPossessiveQuantifiers() {
return true;
}
@Override
public boolean supportsPythonConditionalRefs() {
return false;
}
@Override
public boolean supportsNamedGroupSyntax(RegExpGroup group) {
if (group.isRubyNamedGroup()) {
final Module module = ModuleUtil.findModuleForPsiElement(group);
if (module != null) {
final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
if (sdk != null && sdk.getSdkType() instanceof JavaSdk) {
final JavaSdkVersion version = JavaSdk.getInstance().getVersion(sdk);
return version != null && version.isAtLeast(JavaSdkVersion.JDK_1_7);
}
}
}
return false;
}
}
@@ -1,95 +1,95 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.changeSignature;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiParameter;
import com.intellij.psi.PsiTypeElement;
import com.intellij.util.VisibilityUtil;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class JavaMethodDescriptor implements MethodDescriptor<ParameterInfoImpl> {
private final PsiMethod myMethod;
public JavaMethodDescriptor(PsiMethod method) {
myMethod = method;
}
@Override
public String getName() {
return myMethod.getName();
}
@Override
public List<ParameterInfoImpl> getParameters() {
final ArrayList<ParameterInfoImpl> result = new ArrayList<ParameterInfoImpl>();
final PsiParameter[] parameters = myMethod.getParameterList().getParameters();
for (int i = 0; i < parameters.length; i++) {
PsiParameter parameter = parameters[i];
ParameterInfoImpl info = new ParameterInfoImpl(i, parameter.getName(), parameter.getType());
info.defaultValue = "";
result.add(info);
}
return result;
}
@Override
public String getVisibility() {
return VisibilityUtil.getVisibilityModifier(myMethod.getModifierList());
}
@Override
public PsiMethod getMethod() {
return myMethod;
}
@Override
public int getParametersCount() {
return myMethod.getParameterList().getParametersCount();
}
@Nullable
public String getReturnTypeText() {
final PsiTypeElement typeElement = myMethod.getReturnTypeElement();
return typeElement != null ? typeElement.getText() : null;
}
@Override
public boolean canChangeVisibility() {
PsiClass containingClass = myMethod.getContainingClass();
return containingClass != null && !containingClass.isInterface();
}
@Override
public boolean canChangeParameters() {
return true;
}
@Override
public ReadWriteOption canChangeReturnType() {
return myMethod.isConstructor() ? ReadWriteOption.None : ReadWriteOption.ReadWrite;
}
@Override
public boolean canChangeName() {
return !myMethod.isConstructor();
}
}
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.changeSignature;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiParameter;
import com.intellij.psi.PsiTypeElement;
import com.intellij.util.VisibilityUtil;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class JavaMethodDescriptor implements MethodDescriptor<ParameterInfoImpl, String> {
private final PsiMethod myMethod;
public JavaMethodDescriptor(PsiMethod method) {
myMethod = method;
}
@Override
public String getName() {
return myMethod.getName();
}
@Override
public List<ParameterInfoImpl> getParameters() {
final ArrayList<ParameterInfoImpl> result = new ArrayList<ParameterInfoImpl>();
final PsiParameter[] parameters = myMethod.getParameterList().getParameters();
for (int i = 0; i < parameters.length; i++) {
PsiParameter parameter = parameters[i];
ParameterInfoImpl info = new ParameterInfoImpl(i, parameter.getName(), parameter.getType());
info.defaultValue = "";
result.add(info);
}
return result;
}
@Override
public String getVisibility() {
return VisibilityUtil.getVisibilityModifier(myMethod.getModifierList());
}
@Override
public PsiMethod getMethod() {
return myMethod;
}
@Override
public int getParametersCount() {
return myMethod.getParameterList().getParametersCount();
}
@Nullable
public String getReturnTypeText() {
final PsiTypeElement typeElement = myMethod.getReturnTypeElement();
return typeElement != null ? typeElement.getText() : null;
}
@Override
public boolean canChangeVisibility() {
PsiClass containingClass = myMethod.getContainingClass();
return containingClass != null && !containingClass.isInterface();
}
@Override
public boolean canChangeParameters() {
return true;
}
@Override
public ReadWriteOption canChangeReturnType() {
return myMethod.isConstructor() ? ReadWriteOption.None : ReadWriteOption.ReadWrite;
}
@Override
public boolean canChangeName() {
return !myMethod.isConstructor();
}
}
File diff suppressed because it is too large Load Diff
@@ -1,38 +1,38 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.ui;
import com.intellij.psi.PsiModifier;
import static com.intellij.util.VisibilityUtil.toPresentableText;
/**
* @author Konstantin Bulenkov
*/
public class JavaComboBoxVisibilityPanel extends ComboBoxVisibilityPanel implements PsiModifier {
private static final String[] MODIFIERS = {PRIVATE, PACKAGE_LOCAL, PROTECTED, PUBLIC};
private static final String[] PRESENTABLE_NAMES = {
toPresentableText(PRIVATE),
toPresentableText(PACKAGE_LOCAL),
toPresentableText(PROTECTED),
toPresentableText(PUBLIC)
};
public JavaComboBoxVisibilityPanel() {
super(MODIFIERS, PRESENTABLE_NAMES);
}
}
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.ui;
import com.intellij.psi.PsiModifier;
import static com.intellij.util.VisibilityUtil.toPresentableText;
/**
* @author Konstantin Bulenkov
*/
public class JavaComboBoxVisibilityPanel extends ComboBoxVisibilityPanel<String> implements PsiModifier {
private static final String[] MODIFIERS = {PRIVATE, PACKAGE_LOCAL, PROTECTED, PUBLIC};
private static final String[] PRESENTABLE_NAMES = {
toPresentableText(PRIVATE),
toPresentableText(PACKAGE_LOCAL),
toPresentableText(PROTECTED),
toPresentableText(PUBLIC)
};
public JavaComboBoxVisibilityPanel() {
super(MODIFIERS, PRESENTABLE_NAMES);
}
}
@@ -1,165 +1,165 @@
/*
* 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.
*/
/*
* Created by IntelliJ IDEA.
* User: dsl
* Date: 07.06.2002
* Time: 18:16:19
* To change template for new class use
* Code Style | Class Templates options (Tools | IDE Options).
*/
package com.intellij.refactoring.ui;
import com.intellij.psi.PsiModifier;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.util.VisibilityUtil;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class JavaVisibilityPanel extends VisibilityPanelBase {
private JRadioButton myRbAsIs;
private JRadioButton myRbEscalate;
private final JRadioButton myRbPrivate;
private final JRadioButton myRbProtected;
private final JRadioButton myRbPackageLocal;
private final JRadioButton myRbPublic;
public JavaVisibilityPanel(boolean hasAsIs, final boolean hasEscalate) {
setBorder(IdeBorderFactory.createTitledBorder(RefactoringBundle.message("visibility.border.title"), true,
new Insets(IdeBorderFactory.TITLED_BORDER_TOP_INSET,
UIUtil.DEFAULT_HGAP,
IdeBorderFactory.TITLED_BORDER_BOTTOM_INSET,
IdeBorderFactory.TITLED_BORDER_RIGHT_INSET)));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
ButtonGroup bg = new ButtonGroup();
ItemListener listener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
myEventDispatcher.getMulticaster().stateChanged(new ChangeEvent(this));
}
}
};
if (hasEscalate) {
myRbEscalate = new JRadioButton();
myRbEscalate.setText(RefactoringBundle.getEscalateVisibility());
myRbEscalate.addItemListener(listener);
add(myRbEscalate);
bg.add(myRbEscalate);
}
if (hasAsIs) {
myRbAsIs = new JRadioButton();
myRbAsIs.setText(RefactoringBundle.getVisibilityAsIs());
myRbAsIs.addItemListener(listener);
add(myRbAsIs);
bg.add(myRbAsIs);
}
myRbPrivate = new JRadioButton();
myRbPrivate.setText(RefactoringBundle.getVisibilityPrivate());
myRbPrivate.addItemListener(listener);
myRbPrivate.setFocusable(false);
add(myRbPrivate);
bg.add(myRbPrivate);
myRbPackageLocal = new JRadioButton();
myRbPackageLocal.setText(RefactoringBundle.getVisibilityPackageLocal());
myRbPackageLocal.addItemListener(listener);
myRbPackageLocal.setFocusable(false);
add(myRbPackageLocal);
bg.add(myRbPackageLocal);
myRbProtected = new JRadioButton();
myRbProtected.setText(RefactoringBundle.getVisibilityProtected());
myRbProtected.addItemListener(listener);
myRbProtected.setFocusable(false);
add(myRbProtected);
bg.add(myRbProtected);
myRbPublic = new JRadioButton();
myRbPublic.setText(RefactoringBundle.getVisibilityPublic());
myRbPublic.addItemListener(listener);
myRbPublic.setFocusable(false);
add(myRbPublic);
bg.add(myRbPublic);
}
public String getVisibility() {
if (myRbPublic.isSelected()) {
return PsiModifier.PUBLIC;
}
if (myRbPackageLocal.isSelected()) {
return PsiModifier.PACKAGE_LOCAL;
}
if (myRbProtected.isSelected()) {
return PsiModifier.PROTECTED;
}
if (myRbPrivate.isSelected()) {
return PsiModifier.PRIVATE;
}
if (myRbEscalate != null && myRbEscalate.isSelected()) {
return VisibilityUtil.ESCALATE_VISIBILITY;
}
return null;
}
public void setVisibility(String visibility) {
if (PsiModifier.PUBLIC.equals(visibility)) {
myRbPublic.setSelected(true);
}
else if (PsiModifier.PROTECTED.equals(visibility)) {
myRbProtected.setSelected(true);
}
else if (PsiModifier.PACKAGE_LOCAL.equals(visibility)) {
myRbPackageLocal.setSelected(true);
}
else if (PsiModifier.PRIVATE.equals(visibility)) {
myRbPrivate.setSelected(true);
}
else if (myRbEscalate != null) {
myRbEscalate.setSelected(true);
}
else if (myRbAsIs != null) {
myRbAsIs.setSelected(true);
}
}
public void disableAllButPublic() {
myRbPrivate.setEnabled(false);
myRbProtected.setEnabled(false);
myRbPackageLocal.setEnabled(false);
if (myRbEscalate != null) {
myRbEscalate.setEnabled(false);
}
if (myRbAsIs != null) {
myRbAsIs.setEnabled(false);
}
myRbPublic.setEnabled(true);
myRbPublic.setSelected(true);
}
}
/*
* 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.
*/
/*
* Created by IntelliJ IDEA.
* User: dsl
* Date: 07.06.2002
* Time: 18:16:19
* To change template for new class use
* Code Style | Class Templates options (Tools | IDE Options).
*/
package com.intellij.refactoring.ui;
import com.intellij.psi.PsiModifier;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.util.VisibilityUtil;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class JavaVisibilityPanel extends VisibilityPanelBase<String> {
private JRadioButton myRbAsIs;
private JRadioButton myRbEscalate;
private final JRadioButton myRbPrivate;
private final JRadioButton myRbProtected;
private final JRadioButton myRbPackageLocal;
private final JRadioButton myRbPublic;
public JavaVisibilityPanel(boolean hasAsIs, final boolean hasEscalate) {
setBorder(IdeBorderFactory.createTitledBorder(RefactoringBundle.message("visibility.border.title"), true,
new Insets(IdeBorderFactory.TITLED_BORDER_TOP_INSET,
UIUtil.DEFAULT_HGAP,
IdeBorderFactory.TITLED_BORDER_BOTTOM_INSET,
IdeBorderFactory.TITLED_BORDER_RIGHT_INSET)));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
ButtonGroup bg = new ButtonGroup();
ItemListener listener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
myEventDispatcher.getMulticaster().stateChanged(new ChangeEvent(this));
}
}
};
if (hasEscalate) {
myRbEscalate = new JRadioButton();
myRbEscalate.setText(RefactoringBundle.getEscalateVisibility());
myRbEscalate.addItemListener(listener);
add(myRbEscalate);
bg.add(myRbEscalate);
}
if (hasAsIs) {
myRbAsIs = new JRadioButton();
myRbAsIs.setText(RefactoringBundle.getVisibilityAsIs());
myRbAsIs.addItemListener(listener);
add(myRbAsIs);
bg.add(myRbAsIs);
}
myRbPrivate = new JRadioButton();
myRbPrivate.setText(RefactoringBundle.getVisibilityPrivate());
myRbPrivate.addItemListener(listener);
myRbPrivate.setFocusable(false);
add(myRbPrivate);
bg.add(myRbPrivate);
myRbPackageLocal = new JRadioButton();
myRbPackageLocal.setText(RefactoringBundle.getVisibilityPackageLocal());
myRbPackageLocal.addItemListener(listener);
myRbPackageLocal.setFocusable(false);
add(myRbPackageLocal);
bg.add(myRbPackageLocal);
myRbProtected = new JRadioButton();
myRbProtected.setText(RefactoringBundle.getVisibilityProtected());
myRbProtected.addItemListener(listener);
myRbProtected.setFocusable(false);
add(myRbProtected);
bg.add(myRbProtected);
myRbPublic = new JRadioButton();
myRbPublic.setText(RefactoringBundle.getVisibilityPublic());
myRbPublic.addItemListener(listener);
myRbPublic.setFocusable(false);
add(myRbPublic);
bg.add(myRbPublic);
}
public String getVisibility() {
if (myRbPublic.isSelected()) {
return PsiModifier.PUBLIC;
}
if (myRbPackageLocal.isSelected()) {
return PsiModifier.PACKAGE_LOCAL;
}
if (myRbProtected.isSelected()) {
return PsiModifier.PROTECTED;
}
if (myRbPrivate.isSelected()) {
return PsiModifier.PRIVATE;
}
if (myRbEscalate != null && myRbEscalate.isSelected()) {
return VisibilityUtil.ESCALATE_VISIBILITY;
}
return null;
}
public void setVisibility(String visibility) {
if (PsiModifier.PUBLIC.equals(visibility)) {
myRbPublic.setSelected(true);
}
else if (PsiModifier.PROTECTED.equals(visibility)) {
myRbProtected.setSelected(true);
}
else if (PsiModifier.PACKAGE_LOCAL.equals(visibility)) {
myRbPackageLocal.setSelected(true);
}
else if (PsiModifier.PRIVATE.equals(visibility)) {
myRbPrivate.setSelected(true);
}
else if (myRbEscalate != null) {
myRbEscalate.setSelected(true);
}
else if (myRbAsIs != null) {
myRbAsIs.setSelected(true);
}
}
public void disableAllButPublic() {
myRbPrivate.setEnabled(false);
myRbProtected.setEnabled(false);
myRbPackageLocal.setEnabled(false);
if (myRbEscalate != null) {
myRbEscalate.setEnabled(false);
}
if (myRbAsIs != null) {
myRbAsIs.setEnabled(false);
}
myRbPublic.setEnabled(true);
myRbPublic.setSelected(true);
}
}