From 87b19db227121a13e91397b71ba605d7f77c41fa Mon Sep 17 00:00:00 2001 From: Maxim Medvedev Date: Mon, 1 Feb 2010 18:37:00 +0300 Subject: [PATCH 01/93] simple groovy smart completion --- plugins/groovy/src/META-INF/plugin.xml | 5 + .../GroovyExpectedTypesProvider.java | 203 ++++++++++++++++++ .../GroovySmartCompletionContributor.java | 145 +++++++++++++ .../CompleteReferenceExpression.java | 2 + .../plugins/groovy/GroovyCompletionTest.java | 5 +- ...artCompletionInAssignmentExpression.groovy | 4 + ...pletionInAssignmentExpression_after.groovy | 4 + 7 files changed, 367 insertions(+), 1 deletion(-) create mode 100644 plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyExpectedTypesProvider.java create mode 100644 plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java create mode 100644 plugins/groovy/testdata/groovy/completion/SmartCompletionInAssignmentExpression.groovy create mode 100644 plugins/groovy/testdata/groovy/completion/SmartCompletionInAssignmentExpression_after.groovy diff --git a/plugins/groovy/src/META-INF/plugin.xml b/plugins/groovy/src/META-INF/plugin.xml index db8b74f44d60..4e5e4a10e475 100644 --- a/plugins/groovy/src/META-INF/plugin.xml +++ b/plugins/groovy/src/META-INF/plugin.xml @@ -136,6 +136,7 @@ + @@ -210,6 +211,10 @@ + + + diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyExpectedTypesProvider.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyExpectedTypesProvider.java new file mode 100644 index 000000000000..b85727b7fb4e --- /dev/null +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyExpectedTypesProvider.java @@ -0,0 +1,203 @@ +/* + * 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 org.jetbrains.plugins.groovy.codeInsight; + +import com.intellij.codeInsight.ExpectedTypeInfo; +import com.intellij.codeInsight.ExpectedTypeInfoImpl; +import com.intellij.codeInsight.ExpectedTypesProvider; +import com.intellij.codeInsight.TailType; +import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.project.Project; +import com.intellij.psi.*; +import com.intellij.psi.codeStyle.JavaCodeStyleManager; +import com.intellij.psi.codeStyle.VariableKind; +import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.psi.search.PsiShortNamesCache; +import com.intellij.util.ArrayUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor; +import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrForStatement; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForClause; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrParenthesizedExpression; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; + +/** + * @author Maxim.Medvedev + */ +public class GroovyExpectedTypesProvider { + private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.codeInsight.GroovyExpectedTypesProvider"); + + private static final ExpectedTypesProvider.ExpectedClassProvider OUR_GLOBAL_SCOPE_CLASS_PROVIDER = new ExpectedTypesProvider.ExpectedClassProvider() { + public PsiField[] findDeclaredFields(final PsiManager manager, String name) { + final PsiShortNamesCache cache = JavaPsiFacade.getInstance(manager.getProject()).getShortNamesCache(); + GlobalSearchScope scope = GlobalSearchScope.allScope(manager.getProject()); + return cache.getFieldsByName(name, scope); + } + + public PsiMethod[] findDeclaredMethods(final PsiManager manager, String name) { + final PsiShortNamesCache cache = JavaPsiFacade.getInstance(manager.getProject()).getShortNamesCache(); + GlobalSearchScope scope = GlobalSearchScope.allScope(manager.getProject()); + return cache.getMethodsByName(name, scope); + } + }; + + public GroovyExpectedTypesProvider() { + } + + public static GroovyExpectedTypesProvider getInstance(Project project) { + return ServiceManager.getService(project, GroovyExpectedTypesProvider.class); + } + + private static ExpectedTypeInfoImpl createInfoImpl(@NotNull PsiType type, int kind, PsiType defaultType, TailType tailType) { + int dims = 0; + while (type instanceof PsiArrayType) { + type = ((PsiArrayType)type).getComponentType(); + LOG.assertTrue(defaultType instanceof PsiArrayType); + defaultType = ((PsiArrayType)defaultType).getComponentType(); + dims++; + } + return new ExpectedTypeInfoImpl(type, kind, dims, defaultType, tailType); + } + + + @Nullable + public ExpectedTypeInfo[] getExpectedTypes(GrExpression expr, + boolean forCompletion, + final boolean voidable) { + return getExpectedTypes(expr, forCompletion, OUR_GLOBAL_SCOPE_CLASS_PROVIDER, voidable); + } + + @Nullable + public ExpectedTypeInfo[] getExpectedTypes(GrExpression expr, + boolean forCompletion, + ExpectedTypesProvider.ExpectedClassProvider classProvider, + final boolean voidable) { + if (expr == null) return null; + PsiElement parent = expr.getParent(); + while (parent instanceof GrParenthesizedExpression) { + expr = (GrExpression)parent; + parent = parent.getParent(); + } + MyParentVisitor visitor = new MyParentVisitor(expr, forCompletion, classProvider, voidable); + ((GroovyPsiElement)parent).accept(visitor); + return visitor.getResult(); + } + + + private static class MyParentVisitor extends GroovyElementVisitor { + private ExpectedTypeInfo[] myResult = ExpectedTypeInfo.EMPTY_ARRAY; + + private GrExpression myExpr; + private final boolean myForCompletion; + private final ExpectedTypesProvider.ExpectedClassProvider myClassProvider; + private final boolean myVoidable; + + private MyParentVisitor(GrExpression expr, + boolean forCompletion, + ExpectedTypesProvider.ExpectedClassProvider classProvider, + boolean voidable) { + myExpr = expr; + myForCompletion = forCompletion; + myClassProvider = classProvider; + myVoidable = voidable; + } + + public ExpectedTypeInfo[] getResult() { + return myResult; + } + + @Override + public void visitAssignmentExpression(GrAssignmentExpression assignment) { + if (myExpr == assignment.getRValue()) { + GrExpression lExpr = assignment.getLValue(); + PsiType type = lExpr.getType(); + if (type != null) { + TailType tailType = getAssignmentRValueTailType(assignment); + ExpectedTypeInfoImpl info = createInfoImpl(type, ExpectedTypeInfo.TYPE_OR_SUBTYPE, type, tailType); + if (lExpr instanceof GrReferenceExpression) { + PsiElement refElement = ((GrReferenceExpression)lExpr).resolve(); + if (refElement instanceof GrVariable) { + info.expectedName = getPropertyName((GrVariable)refElement); + } + } + myResult = new ExpectedTypeInfo[]{info}; + } + else { + myResult = ExpectedTypeInfo.EMPTY_ARRAY; + } + + } + else { + if (myForCompletion) { + myExpr = (GrExpression)myExpr.getParent(); + ((GroovyPsiElement)assignment.getParent()).accept(this); + return; + } + + GrExpression rExpr = assignment.getRValue(); + if (rExpr != null) { + PsiType type = rExpr.getType(); + if (type != null) { + if (type instanceof PsiClassType) { + final PsiClass resolved = ((PsiClassType)type).resolve(); + if (resolved instanceof PsiAnonymousClass) { + type = ((PsiAnonymousClass)resolved).getBaseClassType(); + } + } + ExpectedTypeInfoImpl info = createInfoImpl(type, ExpectedTypeInfo.TYPE_OR_SUPERTYPE, type, + TailType.NONE); + myResult = new ExpectedTypeInfo[]{info}; + return; + } + } + myResult = ExpectedTypeInfo.EMPTY_ARRAY; + } + } + + private static TailType getAssignmentRValueTailType(GrAssignmentExpression assignment) { + if (assignment.getParent() instanceof GrExpression) { + if (!(assignment.getParent().getParent() instanceof GrForStatement)) { + return TailType.SEMICOLON; + } + + GrForStatement forStatement = (GrForStatement)assignment.getParent().getParent(); + final GrForClause forClause = forStatement.getClause(); + if (forClause instanceof GrTraditionalForClause) { + if (ArrayUtil.find(((GrTraditionalForClause)forClause).getUpdate(), assignment.getParent()) != -1) { + return TailType.SEMICOLON; + } + } + } + return TailType.NONE; + } + + @Nullable + private static String getPropertyName(GrVariable variable) { + final String name = variable.getName(); + if (name == null) return null; + JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(variable.getProject()); + VariableKind variableKind = codeStyleManager.getVariableKind(variable); + return codeStyleManager.variableNameToPropertyName(name, variableKind); + } + } +} diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java new file mode 100644 index 000000000000..0f0c906bf653 --- /dev/null +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java @@ -0,0 +1,145 @@ +/* + * 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 org.jetbrains.plugins.groovy.lang.completion; + +import com.intellij.codeInsight.ExpectedTypeInfo; +import com.intellij.codeInsight.completion.*; +import com.intellij.codeInsight.lookup.LookupElement; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.util.Computable; +import com.intellij.patterns.ElementPattern; +import com.intellij.psi.*; +import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.util.ProcessingContext; +import gnu.trove.THashSet; +import gnu.trove.TObjectHashingStrategy; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.groovy.codeInsight.GroovyExpectedTypesProvider; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral; +import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; + +import java.util.Arrays; +import java.util.Set; + +import static com.intellij.patterns.PlatformPatterns.psiElement; + +/** + * @author Maxim.Medvedev + */ +public class GroovySmartCompletionContributor extends CompletionContributor { + private static final ElementPattern INSIDE_EXPRESSION = psiElement().withParent(GrExpression.class); + private static final TObjectHashingStrategy EXPECTED_TYPE_INFO_STRATEGY = + new TObjectHashingStrategy() { + public int computeHashCode(final ExpectedTypeInfo object) { + return object.getType().hashCode(); + } + + public boolean equals(final ExpectedTypeInfo o1, final ExpectedTypeInfo o2) { + return o1.getType().equals(o2.getType()); + } + }; + + public GroovySmartCompletionContributor() { + extend(CompletionType.SMART, INSIDE_EXPRESSION, new CompletionProvider() { + @Override + protected void addCompletions(@NotNull final CompletionParameters params, + ProcessingContext context, + @NotNull final CompletionResultSet result) { + final PsiElement position = params.getPosition(); + if (position.getParent() instanceof GrLiteral) return; + + final THashSet _infos = new THashSet(); + ApplicationManager.getApplication().runReadAction(new Runnable() { + public void run() { + _infos.addAll(Arrays.asList(getExpectedTypes(params))); + } + }); + final Set infos = ApplicationManager.getApplication().runReadAction(new Computable>() { + public Set compute() { + return new THashSet(_infos, EXPECTED_TYPE_INFO_STRATEGY); + } + }); + + + final PsiReference reference = position.getContainingFile().findReferenceAt(params.getOffset()); + if (reference == null) return; + final Object[] variants = reference.getVariants(); + for (Object variant : variants) { + PsiType type = null; + if (variant instanceof PsiElement) { + type = getTypeByElement((PsiElement)variant, position); + + } + else if (variant instanceof String) { + if ("true".equals(variant) || "false".equals(variant)) { + type = PsiType.BOOLEAN; + } + } + + for (ExpectedTypeInfo info : infos) { + if (TypesUtil.isAssignable(info.getType(), type, position.getManager(), GlobalSearchScope.allScope(position.getProject()))) { + final LookupElement lookupElement = CompletionData.objectToLookupItem(variant); + result.addElement(lookupElement); + break; + } + } + } + } + }); + } + + @Nullable + public static ExpectedTypeInfo[] getExpectedTypes(CompletionParameters params) { + final PsiElement position = params.getPosition(); + final GrExpression expression = PsiTreeUtil.getParentOfType(position, GrExpression.class); + if (expression != null) { + return GroovyExpectedTypesProvider.getInstance(position.getProject()) + .getExpectedTypes(expression, true, params.getCompletionType() == CompletionType.SMART); + } + return null; + } + + @Nullable + public static PsiType getTypeByElement(PsiElement element, PsiElement context) { + //if(!element.isValid()) return null; + if (element instanceof PsiType) { + return (PsiType)element; + } + if (element instanceof PsiClass) { + return PsiType.getJavaLangClass(context.getManager(), GlobalSearchScope.allScope(context.getProject())); + } + if (element instanceof PsiMethod) { + return ((PsiMethod)element).getReturnType(); + } + if (element instanceof GrVariable) { + return ((GrVariable)element).getTypeGroovy(); + } +/* if(element instanceof PsiKeyword){ + return getKeywordItemType(context, element.getText()); + }*/ + if (element instanceof GrExpression) { + return ((GrExpression)element).getType(); + } + + return null; + } + + +} diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java index ffbe24d8458b..422dcbda7408 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java @@ -159,6 +159,7 @@ public class CompleteReferenceExpression { if (GroovyPropertyUtils.isSimplePropertyAccessor(method)) { String prop = GroovyPropertyUtils.getPropertyName(method); accessedPropertyNames.add(prop); + assert prop != null; props.add(LookupElementBuilder.create(prop).setIcon(GroovyIcons.PROPERTY)); } else if (eventListener != null) { @@ -270,6 +271,7 @@ public class CompleteReferenceExpression { if (!PsiUtil.isValidReferenceName(propName)) { propName = "'" + propName + "'"; } + assert propName != null; result.add(LookupElementBuilder.create(propName).setIcon(GroovyIcons.PROPERTY)); } } diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java index 347a8a03c5be..f6c9d96bb450 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java @@ -79,7 +79,7 @@ public class GroovyCompletionTest extends LightCodeInsightFixtureTestCase { myFixture.testCompletion(getTestName(false) + ".groovy", getTestName(false) + "_after.groovy"); } - public void testEachMethodForMapWithKeyValue() throws Throwable { +public void testEachMethodForMapWithKeyValue() throws Throwable { doBasicTest(); } @@ -267,4 +267,7 @@ public class GroovyCompletionTest extends LightCodeInsightFixtureTestCase { myFixture.testCompletionVariants(getTestName(false)+".groovy", "geteMail", "getePost"); } + public void testSmartCompletionInAssignmentExpression() throws Throwable { + doSmartTest(); + } } diff --git a/plugins/groovy/testdata/groovy/completion/SmartCompletionInAssignmentExpression.groovy b/plugins/groovy/testdata/groovy/completion/SmartCompletionInAssignmentExpression.groovy new file mode 100644 index 000000000000..1be7b678d457 --- /dev/null +++ b/plugins/groovy/testdata/groovy/completion/SmartCompletionInAssignmentExpression.groovy @@ -0,0 +1,4 @@ +def foo = new Date() + +Date date +date = f \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/completion/SmartCompletionInAssignmentExpression_after.groovy b/plugins/groovy/testdata/groovy/completion/SmartCompletionInAssignmentExpression_after.groovy new file mode 100644 index 000000000000..9144559c6ccf --- /dev/null +++ b/plugins/groovy/testdata/groovy/completion/SmartCompletionInAssignmentExpression_after.groovy @@ -0,0 +1,4 @@ +def foo = new Date() + +Date date +date = foo \ No newline at end of file From c61ee07c656bfe28a348345349f9886b7dde6b9a Mon Sep 17 00:00:00 2001 From: Maxim Medvedev Date: Tue, 2 Feb 2010 15:54:10 +0300 Subject: [PATCH 02/93] use processVariants() instead of getVariants() for completion of Groovy references --- .../GroovyCompletionContributor.java | 50 +++++++++- .../groovy/lang/psi/GrReferenceElement.java | 3 + .../CompleteReferenceExpression.java | 56 ++++++----- .../GrReferenceExpressionImpl.java | 7 +- .../types/GrCodeReferenceElementImpl.java | 98 +++++++++---------- .../groovy/oldCompletion/keyword/imp4.test | 6 +- .../groovy/oldCompletion/keyword/var3.test | 5 + 7 files changed, 142 insertions(+), 83 deletions(-) diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java index 82e13abd4ce8..b06dedd1fa93 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java @@ -16,9 +16,7 @@ package org.jetbrains.plugins.groovy.lang.completion; import com.intellij.codeInsight.completion.*; -import com.intellij.codeInsight.lookup.LookupElementBuilder; -import com.intellij.codeInsight.lookup.LookupItem; -import com.intellij.codeInsight.lookup.LookupItemUtil; +import com.intellij.codeInsight.lookup.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.highlighter.HighlighterIterator; @@ -39,6 +37,7 @@ import org.jetbrains.plugins.groovy.lang.completion.getters.ClassesGetter; import org.jetbrains.plugins.groovy.lang.completion.handlers.AfterNewClassInsertHandler; import org.jetbrains.plugins.groovy.lang.completion.handlers.ArrayInsertHandler; import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; +import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement; @@ -46,9 +45,11 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter; import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList; +import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement; import java.util.ArrayList; import java.util.List; @@ -76,7 +77,50 @@ public class GroovyCompletionContributor extends CompletionContributor { private static final String[] THIS_SUPER = {"this", "super"}; + private static boolean isReferenceInNewExpression(PsiReference reference) { + if (!(reference instanceof GrCodeReferenceElement)) return false; + + PsiElement parent = ((GrCodeReferenceElement)reference).getParent(); + while (parent instanceof GrCodeReferenceElement) parent = parent.getParent(); + return parent instanceof GrNewExpression; + } + public GroovyCompletionContributor() { + extend(CompletionType.BASIC, psiElement(PsiElement.class), new CompletionProvider() { + @Override + protected void addCompletions(@NotNull CompletionParameters parameters, + ProcessingContext context, + @NotNull final CompletionResultSet result) { + final PsiElement position = parameters.getPosition(); + final int offset = parameters.getOffset(); + final PsiReference reference = position.getContainingFile().findReferenceAt(offset); + if (reference == null) return; + if (isReferenceInNewExpression(reference)) { + //reference in new Expression + ((GrCodeReferenceElement)reference).processVariants(new Consumer() { + public void consume(Object element) { + if (element instanceof PsiClass) { + final PsiClass clazz = (PsiClass)element; + final MutableLookupElement lookupElement = LookupElementFactory.getInstance().createLookupElement(clazz); + result.addElement(GroovyCompletionUtil.setTailTypeForConstructor(clazz, lookupElement)); + } + else { + result.addElement(LookupItemUtil.objectToLookupItem(element)); + } + } + }); + + } + else if (reference instanceof GrReferenceElement) { + ((GrReferenceElement)reference).processVariants(new Consumer() { + public void consume(Object element) { + result.addElement(LookupItemUtil.objectToLookupItem(element)); + } + }); + } + } + }); + extend(CompletionType.SMART, AFTER_NEW, new CompletionProvider(false) { public void addCompletions(@NotNull final CompletionParameters parameters, final ProcessingContext matchingContext, diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/GrReferenceElement.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/GrReferenceElement.java index 2e94600bcbc4..42fa9555251a 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/GrReferenceElement.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/GrReferenceElement.java @@ -19,6 +19,7 @@ import com.intellij.psi.PsiElement; import com.intellij.psi.PsiPolyVariantReference; import com.intellij.psi.PsiQualifiedReference; import com.intellij.psi.PsiType; +import com.intellij.util.Consumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; @@ -46,4 +47,6 @@ public interface GrReferenceElement extends GroovyPsiElement, PsiPolyVariantRefe @Nullable GrTypeArgumentList getTypeArgumentList(); + + void processVariants(Consumer consumer); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java index 422dcbda7408..ac9f2a1f0059 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java @@ -26,6 +26,7 @@ import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.util.ArrayUtil; +import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashSet; import org.jetbrains.plugins.groovy.GroovyIcons; @@ -53,7 +54,10 @@ import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; import org.jetbrains.plugins.groovy.lang.resolve.processors.CompletionProcessor; import org.jetbrains.plugins.groovy.lang.resolve.processors.ResolverProcessor; -import java.util.*; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; /** * @author ven @@ -62,9 +66,9 @@ public class CompleteReferenceExpression { private CompleteReferenceExpression() { } - public static Object[] getVariants(GrReferenceExpressionImpl refExpr) { + public static void processVariants(Consumer consumer, GrReferenceExpressionImpl refExpr) { PsiElement refParent = refExpr.getParent(); - List namedArgsVariants = getNamedArgsVariants(refParent); + processArgsVariants(consumer, refParent); final GrExpression qualifier = refExpr.getQualifierExpression(); Object[] propertyVariants = getVariantsImpl(refExpr, CompletionProcessor.createPropertyCompletionProcessor(refExpr)); @@ -85,34 +89,31 @@ public class CompleteReferenceExpression { if (type instanceof PsiClassType) { PsiClass clazz = ((PsiClassType)type).resolve(); if (clazz != null) { - Set accessedPropertyNames = new THashSet(); - List variantList = new ArrayList(getPropertyVariants(refExpr, clazz, accessedPropertyNames)); + Set accessedPropertyNames = processPropertyVariants(consumer, refExpr, clazz); for (Object variant : propertyVariants) { - if (variant instanceof PsiField && accessedPropertyNames.contains(((PsiField) variant).getName())) { + if (variant instanceof PsiField && accessedPropertyNames.contains(((PsiField)variant).getName())) { continue; } - variantList.add(variant); + consumer.consume(variant); } - - propertyVariants = variantList.toArray(new Object[variantList.size()]); } } - - propertyVariants = - ArrayUtil.mergeArrays(propertyVariants, namedArgsVariants.toArray(new Object[namedArgsVariants.size()]), Object.class); + else { + for (Object variant : propertyVariants) { + consumer.consume(variant); + } + } if (refExpr.getKind() == GrReferenceExpressionImpl.Kind.TYPE_OR_PROPERTY) { ResolverProcessor classVariantsCollector = CompletionProcessor.createClassCompletionProcessor(refExpr); final Object[] classVariants = getVariantsImpl(refExpr, classVariantsCollector); - return ArrayUtil.mergeArrays(propertyVariants, classVariants, Object.class); - } - else { - return propertyVariants; + for (Object variant : classVariants) { + consumer.consume(variant); + } } } - private static List getNamedArgsVariants(PsiElement refParent) { - List namedArgsVariants = new LinkedList(); + private static void processArgsVariants(Consumer consumer, PsiElement refParent) { if (refParent instanceof GrArgumentList) { PsiElement refPParent = refParent.getParent(); if (refPParent instanceof GrCall) { @@ -141,17 +142,18 @@ public class CompleteReferenceExpression { if (element instanceof GrMethod) { Set[] parametersArray = ((GrMethod)element).getNamedParametersArray(); for (Set namedParameters : parametersArray) { - namedArgsVariants.addAll(namedParameters); + for (String parameter : namedParameters) { + consumer.consume(parameter); + } } } } } } - return namedArgsVariants; } - private static List getPropertyVariants(GrReferenceExpression refExpr, PsiClass clazz, Set accessedPropertyNames) { - List props = new ArrayList(); + private static Set processPropertyVariants(Consumer consumer, GrReferenceExpression refExpr, PsiClass clazz) { + Set accessedPropertyNames=new THashSet(); final PsiClass eventListener = JavaPsiFacade.getInstance(refExpr.getProject()).findClass("java.util.EventListener", refExpr.getResolveScope()); for (PsiMethod method : clazz.getAllMethods()) { @@ -160,17 +162,17 @@ public class CompleteReferenceExpression { String prop = GroovyPropertyUtils.getPropertyName(method); accessedPropertyNames.add(prop); assert prop != null; - props.add(LookupElementBuilder.create(prop).setIcon(GroovyIcons.PROPERTY)); + consumer.consume(LookupElementBuilder.create(prop).setIcon(GroovyIcons.PROPERTY)); } else if (eventListener != null) { - addListenerProperties(method, eventListener, props); + consumeListenerProperties(consumer, method, eventListener); } } } - return props; + return accessedPropertyNames; } - private static void addListenerProperties(PsiMethod method, PsiClass eventListenerClass, List result) { + private static void consumeListenerProperties(Consumer consumer, PsiMethod method, PsiClass eventListenerClass) { if (method.getName().startsWith("add") && method.getParameterList().getParametersCount() == 1) { final PsiParameter parameter = method.getParameterList().getParameters()[0]; final PsiType type = parameter.getType(); @@ -181,7 +183,7 @@ public class CompleteReferenceExpression { final PsiMethod[] listenerMethods = listenerClass.getMethods(); if (InheritanceUtil.isInheritorOrSelf(listenerClass, eventListenerClass, true)) { for (PsiMethod listenerMethod : listenerMethods) { - result.add(LookupElementBuilder.create(listenerMethod.getName()).setIcon(GroovyIcons.PROPERTY)); + consumer.consume(LookupElementBuilder.create(listenerMethod.getName()).setIcon(GroovyIcons.PROPERTY)); } } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java index 20f4c6918d9d..67c37505ba77 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java @@ -31,6 +31,7 @@ import com.intellij.psi.util.PropertyUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.util.ArrayUtil; +import com.intellij.util.Consumer; import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NonNls; @@ -599,7 +600,7 @@ public class GrReferenceExpressionImpl extends GrReferenceElementImpl implements @NotNull public Object[] getVariants() { - return CompleteReferenceExpression.getVariants(this); + return ArrayUtil.EMPTY_OBJECT_ARRAY; } @@ -645,6 +646,10 @@ public class GrReferenceExpressionImpl extends GrReferenceElementImpl implements return (GroovyResolveResult[]) getManager().getResolveCache().resolveWithCaching(this, RESOLVER, false, incomplete); } + public void processVariants(Consumer consumer) { + CompleteReferenceExpression.processVariants(consumer, this); + } + @NotNull public GroovyResolveResult[] getSameNameVariants() { return RESOLVER.resolve(this, true); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java index c89295c286b0..6b0016536bcb 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java @@ -16,15 +16,13 @@ package org.jetbrains.plugins.groovy.lang.psi.impl.types; -import com.intellij.codeInsight.lookup.LookupElement; -import com.intellij.codeInsight.lookup.LookupElementFactory; -import com.intellij.codeInsight.lookup.MutableLookupElement; import com.intellij.lang.ASTNode; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.ResolveCache; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayUtil; +import com.intellij.util.Consumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.completion.GroovyCompletionUtil; @@ -122,6 +120,10 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement } private ReferenceKind getKind(boolean forCompletion) { + if (isClassReferenceForNew()) { + return CLASS_OR_PACKAGE; + } + PsiElement parent = getParent(); if (parent instanceof GrCodeReferenceElement) { ReferenceKind parentKind = ((GrCodeReferenceElementImpl) parent).getKind(forCompletion); @@ -197,11 +199,7 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement @NotNull public Object[] getVariants() { - if (isClassReferenceForNew()) { - return getVariantsForNewExpression(); - } - - return getVariantsImpl(getKind(true)); + return ArrayUtil.EMPTY_OBJECT_ARRAY; } private boolean isClassReferenceForNew() { @@ -210,30 +208,7 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement return parent instanceof GrNewExpression; } - private Object[] getVariantsForNewExpression() { - final Object[] classVariants = getVariantsImpl(CLASS_OR_PACKAGE); - List result = new ArrayList(); - for (Object variant : classVariants) { - if (variant instanceof PsiClass) { - final PsiClass clazz = (PsiClass) variant; - final MutableLookupElement lookupElement = LookupElementFactory.getInstance().createLookupElement(clazz); - result.add(GroovyCompletionUtil.setTailTypeForConstructor(clazz, lookupElement)); - } else if (variant instanceof LookupElement) { - final LookupElement lookupElement = (LookupElement) variant; - final Object obj = lookupElement.getObject(); - if (obj instanceof PsiClass) { - result.add(GroovyCompletionUtil.setTailTypeForConstructor((PsiClass) obj, lookupElement)); - } else { - result.add(lookupElement); - } - } else { - result.add(variant); - } - } - return result.toArray(new Object[result.size()]); - } - - private Object[] getVariantsImpl(ReferenceKind kind) { + private void processVariantsImpl(ReferenceKind kind, Consumer consumer) { switch (kind) { case STATIC_MEMBER_FQ: { final GrCodeReferenceElement qualifier = getQualifier(); @@ -241,21 +216,19 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement final PsiElement resolve = qualifier.resolve(); if (resolve instanceof PsiClass) { final PsiClass clazz = (PsiClass) resolve; - List result = new ArrayList(); for (PsiField field : clazz.getFields()) { if (field.hasModifierProperty(PsiModifier.STATIC)) { - result.add(field); + consumer.consume(field); } } for (PsiMethod method : clazz.getMethods()) { if (method.hasModifierProperty(PsiModifier.STATIC)) { - result.add(method); + consumer.consume(method); } } - - return result.toArray(new PsiElement[result.size()]); + return; } } } @@ -271,17 +244,26 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement if (parentPackage != null) { final GlobalSearchScope scope = getResolveScope(); if (kind == PACKAGE_FQ) { - return parentPackage.getSubPackages(scope); + for (PsiPackage aPackage : parentPackage.getSubPackages(scope)) { + consumer.consume(aPackage); + } + return; } else { if (kind == CLASS_FQ) { - return parentPackage.getClasses(scope); + for (PsiClass aClass : parentPackage.getClasses(scope)) { + consumer.consume(aClass); + } + return; } else { final PsiPackage[] subpackages = parentPackage.getSubPackages(scope); final PsiClass[] classes = parentPackage.getClasses(scope); - PsiElement[] result = new PsiElement[subpackages.length + classes.length]; - System.arraycopy(subpackages, 0, result, 0, subpackages.length); - System.arraycopy(classes, 0, result, subpackages.length, classes.length); - return result; + for (PsiPackage aPackage : subpackages) { + consumer.consume(aPackage); + } + for (PsiClass aClass : classes) { + consumer.consume(aClass); + } + return; } } } @@ -296,21 +278,31 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement if (qualifierResolved instanceof PsiPackage) { PsiPackage aPackage = (PsiPackage) qualifierResolved; PsiClass[] classes = aPackage.getClasses(getResolveScope()); - if (kind == CLASS) return classes; + + for (PsiClass aClass : classes) { + consumer.consume(aClass); + } + if (kind == CLASS) return; + PsiPackage[] subpackages = aPackage.getSubPackages(); - return ArrayUtil.mergeArrays(classes, subpackages, Object.class); + for (PsiPackage subpackage : subpackages) { + consumer.consume(subpackage); + } } else if (qualifierResolved instanceof PsiClass) { - return ((PsiClass) qualifierResolved).getInnerClasses(); + for (PsiClass aClass : ((PsiClass)qualifierResolved).getInnerClasses()) { + consumer.consume(aClass); + } } } else { - ResolverProcessor processor = CompletionProcessor.createClassCompletionProcessor(this); - ResolveUtil.treeWalkUp(this, processor, false); - return GroovyCompletionUtil.getCompletionVariants(processor.getCandidates()); + ResolverProcessor classProcessor = CompletionProcessor.createClassCompletionProcessor(this); + ResolveUtil.treeWalkUp(this, classProcessor, false); + + for (Object o : GroovyCompletionUtil.getCompletionVariants(classProcessor.getCandidates())) { + consumer.consume(o); + } } } } - - return ArrayUtil.EMPTY_OBJECT_ARRAY; } public boolean isSoft() { @@ -489,4 +481,8 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement return (GroovyResolveResult[])results; } + + public void processVariants(Consumer consumer) { + processVariantsImpl(getKind(true), consumer); + } } diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/imp4.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/imp4.test index 425faa279629..7f2476687da7 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/imp4.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/imp4.test @@ -1,2 +1,6 @@ import static a.b ------ \ No newline at end of file +----- +META-INF +com +java +javax \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var3.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var3.test index c26b3e8a7eb4..61b0056f6e56 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var3.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var3.test @@ -10,4 +10,9 @@ class A { } } ----- +A +META-INF +com +java +javax static \ No newline at end of file From 389973240bbf3f4059bb135ac2659e7717812a10 Mon Sep 17 00:00:00 2001 From: Maxim Medvedev Date: Wed, 3 Feb 2010 13:43:15 +0300 Subject: [PATCH 03/93] simple smart completion for method arguments --- .../GroovyExpectedTypesProvider.java | 74 +++++++++++++++++-- .../GroovyCompletionContributor.java | 7 +- .../GroovySmartCompletionContributor.java | 49 +++++++----- .../expressions/GrNewExpression.java | 10 +-- .../plugins/groovy/GroovyCompletionTest.java | 16 ++++ .../lang/completion/CompletionTestBase.java | 12 +++ .../completion/SimpleMethodParameter.groovy | 9 +++ .../groovy/oldCompletion/keyword/file12.test | 2 + .../groovy/oldCompletion/keyword/grvy945.test | 1 - .../groovy/oldCompletion/keyword/mod11.test | 3 +- .../groovy/oldCompletion/keyword/var1.test | 1 + .../groovy/oldCompletion/keyword/var10.test | 1 + .../groovy/oldCompletion/keyword/var2.test | 1 + .../groovy/oldCompletion/keyword/var3.test | 1 - 14 files changed, 143 insertions(+), 44 deletions(-) create mode 100644 plugins/groovy/testdata/groovy/completion/SimpleMethodParameter.groovy diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyExpectedTypesProvider.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyExpectedTypesProvider.java index b85727b7fb4e..0d41ab0ed3d1 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyExpectedTypesProvider.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyExpectedTypesProvider.java @@ -15,10 +15,7 @@ */ package org.jetbrains.plugins.groovy.codeInsight; -import com.intellij.codeInsight.ExpectedTypeInfo; -import com.intellij.codeInsight.ExpectedTypeInfoImpl; -import com.intellij.codeInsight.ExpectedTypesProvider; -import com.intellij.codeInsight.TailType; +import com.intellij.codeInsight.*; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; @@ -28,18 +25,21 @@ import com.intellij.psi.codeStyle.VariableKind; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiShortNamesCache; import com.intellij.util.ArrayUtil; +import com.intellij.util.containers.hash.HashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; +import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrForStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForClause; import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrParenthesizedExpression; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression; + +import java.util.Set; /** * @author Maxim.Medvedev @@ -174,6 +174,46 @@ public class GroovyExpectedTypesProvider { } } + @Override + public void visitArgumentList(GrArgumentList list) { + final PsiElement parent = list.getParent(); + + GroovyResolveResult[] results = null; + if (parent instanceof GrMethodCallExpression) { + final GrExpression expression = ((GrMethodCallExpression)parent).getInvokedExpression(); + if (expression instanceof GrReferenceExpression) { + results = ((GrReferenceExpression)expression).multiResolve(false); + } + } + else if (parent instanceof GrApplicationStatement) { + final GrExpression expression = ((GrApplicationStatement)parent).getFunExpression(); + if (expression instanceof GrReferenceExpression) { + results = ((GrReferenceExpression)expression).multiResolve(false); + } + } + else if (parent instanceof GrConstructorCall) { + results = ((GrConstructorCall)parent).multiResolveConstructor(); + } + + if (results == null || results.length == 0) return; + + final int argumentIndex = list.getExpressionArgumentIndex(myExpr); + assert argumentIndex != -1; + + Set infos = new HashSet(); + for (GroovyResolveResult result : results) { + final PsiElement element = result.getElement(); + if (!(element instanceof PsiMethod)) continue; + final PsiParameter[] parameters = ((PsiMethod)element).getParameterList().getParameters(); + if (parameters.length < argumentIndex) continue; + final PsiParameter parameter = parameters[argumentIndex]; + final PsiType type = parameter.getType(); + final TailType tailType = getMethodArgumentTailType(myExpr, argumentIndex, (PsiMethod)element, result.getSubstitutor(), parameters); + infos.add(createInfoImpl(type, ExpectedTypeInfo.TYPE_OR_SUBTYPE, type, tailType)); + } + myResult = infos.toArray(new ExpectedTypeInfo[infos.size()]); + } + private static TailType getAssignmentRValueTailType(GrAssignmentExpression assignment) { if (assignment.getParent() instanceof GrExpression) { if (!(assignment.getParent().getParent() instanceof GrForStatement)) { @@ -199,5 +239,23 @@ public class GroovyExpectedTypesProvider { VariableKind variableKind = codeStyleManager.getVariableKind(variable); return codeStyleManager.variableNameToPropertyName(name, variableKind); } + + private TailType getMethodArgumentTailType(final GrExpression argument, final int index, final PsiMethod method, final PsiSubstitutor substitutor, + final PsiParameter[] parms) { + if (index >= parms.length) { + return TailType.NONE; + } + if (index == parms.length - 1) { + //myTailType = CompletionUtil.NONE_TAIL; + final PsiElement call = argument.getParent().getParent(); + + PsiType returnType = method.getReturnType(); + if (returnType != null) returnType = substitutor.substitute(returnType); + return (PsiType.VOID.equals(returnType) || returnType == null) && call.getParent() instanceof PsiStatement + ? TailTypes.CALL_RPARENTH_SEMICOLON + : TailTypes.CALL_RPARENTH; + } + return TailType.COMMA; + } } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java index b06dedd1fa93..3c413437c04e 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java @@ -77,10 +77,10 @@ public class GroovyCompletionContributor extends CompletionContributor { private static final String[] THIS_SUPER = {"this", "super"}; - private static boolean isReferenceInNewExpression(PsiReference reference) { + private static boolean isReferenceInNewExpression(PsiElement reference) { if (!(reference instanceof GrCodeReferenceElement)) return false; - PsiElement parent = ((GrCodeReferenceElement)reference).getParent(); + PsiElement parent = reference.getParent(); while (parent instanceof GrCodeReferenceElement) parent = parent.getParent(); return parent instanceof GrNewExpression; } @@ -92,8 +92,7 @@ public class GroovyCompletionContributor extends CompletionContributor { ProcessingContext context, @NotNull final CompletionResultSet result) { final PsiElement position = parameters.getPosition(); - final int offset = parameters.getOffset(); - final PsiReference reference = position.getContainingFile().findReferenceAt(offset); + final PsiElement reference = position.getParent(); if (reference == null) return; if (isReferenceInNewExpression(reference)) { //reference in new Expression diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java index 0f0c906bf653..c52e4b5bb0ee 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java @@ -18,18 +18,24 @@ package org.jetbrains.plugins.groovy.lang.completion; import com.intellij.codeInsight.ExpectedTypeInfo; import com.intellij.codeInsight.completion.*; import com.intellij.codeInsight.lookup.LookupElement; +import com.intellij.codeInsight.lookup.LookupItemUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.Computable; import com.intellij.patterns.ElementPattern; -import com.intellij.psi.*; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiType; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.util.Consumer; import com.intellij.util.ProcessingContext; import gnu.trove.THashSet; import gnu.trove.TObjectHashingStrategy; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.codeInsight.GroovyExpectedTypesProvider; +import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral; @@ -78,28 +84,31 @@ public class GroovySmartCompletionContributor extends CompletionContributor { }); - final PsiReference reference = position.getContainingFile().findReferenceAt(params.getOffset()); + final PsiElement reference = position.getParent(); if (reference == null) return; - final Object[] variants = reference.getVariants(); - for (Object variant : variants) { - PsiType type = null; - if (variant instanceof PsiElement) { - type = getTypeByElement((PsiElement)variant, position); + if (reference instanceof GrReferenceElement) { + ((GrReferenceElement)reference).processVariants(new Consumer() { + public void consume(Object variant) { + PsiType type = null; + if (variant instanceof PsiElement) { + type = getTypeByElement((PsiElement)variant, position); + } + else if (variant instanceof String) { + if ("true".equals(variant) || "false".equals(variant)) { + type = PsiType.BOOLEAN; + } + } + if (type == null) return; + for (ExpectedTypeInfo info : infos) { + if (TypesUtil.isAssignableByMethodCallConversion(info.getType(), type, position.getManager(), GlobalSearchScope.allScope(position.getProject()))) { + final LookupElement lookupElement = LookupItemUtil.objectToLookupItem(variant); + result.addElement(lookupElement); + break; + } + } - } - else if (variant instanceof String) { - if ("true".equals(variant) || "false".equals(variant)) { - type = PsiType.BOOLEAN; } - } - - for (ExpectedTypeInfo info : infos) { - if (TypesUtil.isAssignable(info.getType(), type, position.getManager(), GlobalSearchScope.allScope(position.getProject()))) { - final LookupElement lookupElement = CompletionData.objectToLookupItem(variant); - result.addElement(lookupElement); - break; - } - } + }); } } }); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/expressions/GrNewExpression.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/expressions/GrNewExpression.java index 83d8fe963f5d..15af4670f96a 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/expressions/GrNewExpression.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/expressions/GrNewExpression.java @@ -16,9 +16,7 @@ package org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions; -import com.intellij.psi.PsiMethod; import org.jetbrains.annotations.Nullable; -import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement; @@ -26,18 +24,12 @@ import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement; /** * @author ilyas */ -public interface GrNewExpression extends GrCallExpression { +public interface GrNewExpression extends GrCallExpression, GrConstructorCall { @Nullable GrExpression getQualifier(); GrCodeReferenceElement getReferenceElement(); - GroovyResolveResult[] multiResolveConstructor(); - - PsiMethod resolveConstructor(); - - GroovyResolveResult resolveConstructorGenerics(); - int getArrayCount(); @Nullable diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java index f6c9d96bb450..c36ee4213ac4 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java @@ -17,9 +17,12 @@ package org.jetbrains.plugins.groovy; import com.intellij.codeInsight.completion.CompletionType; +import com.intellij.testFramework.UsefulTestCase; import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; import org.jetbrains.plugins.groovy.util.TestUtils; +import java.util.List; + /** * @author Maxim.Medvedev */ @@ -270,4 +273,17 @@ public void testEachMethodForMapWithKeyValue() throws Throwable { public void testSmartCompletionInAssignmentExpression() throws Throwable { doSmartTest(); } + + public void doSmartCompletion(String... variants) throws Exception { + myFixture.configureByFile(getTestName(false) + ".groovy"); + myFixture.complete(CompletionType.SMART); + final List list = myFixture.getLookupElementStrings(); + assertNotNull(list); + UsefulTestCase.assertSameElements(list, variants); + } + + public void testSimpleMethodParameter() throws Throwable { + doSmartCompletion("d1", "d2"); + } + } diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/CompletionTestBase.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/CompletionTestBase.java index 436038ca7739..96b8da3defba 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/CompletionTestBase.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/CompletionTestBase.java @@ -5,9 +5,13 @@ import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.lookup.impl.LookupImpl; import com.intellij.openapi.fileTypes.FileType; +import com.intellij.openapi.util.Condition; +import com.intellij.psi.PsiMember; import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.plugins.groovy.CompositeCompletionData; import org.jetbrains.plugins.groovy.GroovyFileType; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; import org.jetbrains.plugins.groovy.util.TestUtils; import java.util.Collections; @@ -43,6 +47,14 @@ public abstract class CompletionTestBase extends JavaCodeInsightFixtureTestCase final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myFixture.getEditor()); if (lookup != null) { List items = lookup.getItems(); + if (!addReferenceVariants()) { + items = ContainerUtil.findAll(items, new Condition() { + public boolean value(LookupElement lookupElement) { + final Object o = lookupElement.getObject(); + return !(o instanceof PsiMember) && !(o instanceof GrVariable); + } + }); + } Collections.sort(items, new Comparator() { public int compare(LookupElement o1, LookupElement o2) { return o1.getLookupString().compareTo(o2.getLookupString()); diff --git a/plugins/groovy/testdata/groovy/completion/SimpleMethodParameter.groovy b/plugins/groovy/testdata/groovy/completion/SimpleMethodParameter.groovy new file mode 100644 index 000000000000..74a5c2daa8f7 --- /dev/null +++ b/plugins/groovy/testdata/groovy/completion/SimpleMethodParameter.groovy @@ -0,0 +1,9 @@ +def method(Date date, String x, Date d) { + +} + +Date d1=new Date() +def d2=new Date() +String x="ds" + +method(d1, x, ) \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/file12.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/file12.test index 9f61ae66c168..4ee2e0e4f740 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/file12.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/file12.test @@ -15,12 +15,14 @@ assert boolean byte char +class double false final float for int +k long new null diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/grvy945.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/grvy945.test index 4a6fdc84a144..c4bdfd1176dd 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/grvy945.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/grvy945.test @@ -4,4 +4,3 @@ class Category { } } ----- -Category \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/mod11.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/mod11.test index ef32b89a780b..2309d8cdd4c6 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/mod11.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/mod11.test @@ -1,4 +1,5 @@ def foo = { p ppp } ------ \ No newline at end of file +----- +ppp \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var1.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var1.test index 53a404842098..1ab4dd69a70d 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var1.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var1.test @@ -25,6 +25,7 @@ for import int interface +k long native new diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var10.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var10.test index 34814a2c3c52..f1bcfebccd65 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var10.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var10.test @@ -14,6 +14,7 @@ class A { boolean byte char +class double false float diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var2.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var2.test index f9c25dc3a419..9a92104184d8 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var2.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var2.test @@ -25,6 +25,7 @@ for import int interface +k long native new diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var3.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var3.test index 61b0056f6e56..24fcb08c1220 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var3.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var3.test @@ -10,7 +10,6 @@ class A { } } ----- -A META-INF com java From 6100596b75809ac52dc83e730ac7817ec3e5aa51 Mon Sep 17 00:00:00 2001 From: Maxim Medvedev Date: Thu, 4 Feb 2010 19:13:08 +0300 Subject: [PATCH 04/93] use old GroovyExpectedTypesUtil for smart completion --- plugins/groovy/src/META-INF/plugin.xml | 5 - .../intentions/CreateFieldFromUsageFix.java | 4 +- .../CreateLocalVariableFromUsageFix.java | 4 +- .../intentions/CreateMethodFromUsageFix.java | 4 +- .../dynamic/ui/DynamicMethodDialog.java | 4 +- .../dynamic/ui/DynamicPropertyDialog.java | 4 +- .../GroovyExpectedTypesProvider.java | 261 ------------------ .../GroovySmartCompletionContributor.java | 32 +-- ....java => GroovyExpectedTypesProvider.java} | 90 +++--- .../psi/expectedTypes/SubtypeConstraint.java | 12 +- .../expectedTypes/SupertypeConstraint.java | 12 +- .../psi/expectedTypes/TypeConstraint.java | 4 +- .../lang/psi/expectedTypes/TypeEquals.java | 9 +- .../statements/expressions/TypesUtil.java | 2 - .../plugins/groovy/GroovyCompletionTest.java | 7 +- .../groovy/completion/ReturnStatement.groovy | 6 + 16 files changed, 99 insertions(+), 361 deletions(-) delete mode 100644 plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyExpectedTypesProvider.java rename plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/{GroovyExpectedTypesUtil.java => GroovyExpectedTypesProvider.java} (68%) create mode 100644 plugins/groovy/testdata/groovy/completion/ReturnStatement.groovy diff --git a/plugins/groovy/src/META-INF/plugin.xml b/plugins/groovy/src/META-INF/plugin.xml index 4e5e4a10e475..9a02673f9b70 100644 --- a/plugins/groovy/src/META-INF/plugin.xml +++ b/plugins/groovy/src/META-INF/plugin.xml @@ -70,7 +70,6 @@ - @@ -211,10 +210,6 @@ - - - diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateFieldFromUsageFix.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateFieldFromUsageFix.java index 5c06006dbaab..808c25838b2d 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateFieldFromUsageFix.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateFieldFromUsageFix.java @@ -25,7 +25,7 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.GroovyBundle; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrMemberOwner; -import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesUtil; +import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider; import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint; import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil; @@ -62,7 +62,7 @@ public class CreateFieldFromUsageFix extends CreateFieldFix { } protected TypeConstraint[] calculateTypeConstrains() { - return GroovyExpectedTypesUtil.calculateTypeConstraints(myRefExpression); + return GroovyExpectedTypesProvider.calculateTypeConstraints(myRefExpression); } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateLocalVariableFromUsageFix.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateLocalVariableFromUsageFix.java index c54b2b8ca5db..1e5255a701e8 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateLocalVariableFromUsageFix.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateLocalVariableFromUsageFix.java @@ -39,7 +39,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaratio import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement; import org.jetbrains.plugins.groovy.lang.psi.api.util.GrVariableDeclarationOwner; -import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesUtil; +import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider; import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint; /** @@ -85,7 +85,7 @@ public class CreateLocalVariableFromUsageFix implements IntentionAction { int offset = myRefExpression.getTextRange().getStartOffset(); GrStatement anchor = findAnchor(file, offset); - TypeConstraint[] constraints = GroovyExpectedTypesUtil.calculateTypeConstraints(myRefExpression); + TypeConstraint[] constraints = GroovyExpectedTypesProvider.calculateTypeConstraints(myRefExpression); if (anchor.equals(myRefExpression)) { decl = myRefExpression.replaceWithStatement(decl); } else { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateMethodFromUsageFix.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateMethodFromUsageFix.java index 41f44fb1ba79..c14efd35f9e5 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateMethodFromUsageFix.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateMethodFromUsageFix.java @@ -33,7 +33,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrRefere import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrMemberOwner; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; -import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesUtil; +import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider; import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.SupertypeConstraint; import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; @@ -83,7 +83,7 @@ public class CreateMethodFromUsageFix implements IntentionAction { methodBuffer.append(") {\n}"); GrMethod method = GroovyPsiElementFactory.getInstance(project).createMethodFromText(methodBuffer.toString()); GrMemberOwner owner = myTargetClass; - TypeConstraint[] constraints = GroovyExpectedTypesUtil.calculateTypeConstraints((GrExpression) myRefExpression.getParent()); + TypeConstraint[] constraints = GroovyExpectedTypesProvider.calculateTypeConstraints((GrExpression) myRefExpression.getParent()); PsiElement parent = myTargetClass instanceof GrTypeDefinition ? ((GrTypeDefinition)myTargetClass).getBody() : ((GroovyScriptClass) myTargetClass).getContainingFile(); if (PsiTreeUtil.isAncestor(parent, myRefExpression, false)) { PsiElement prevParent = PsiTreeUtil.findPrevParent(parent, myRefExpression); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicMethodDialog.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicMethodDialog.java index 1275eda5cd64..0054c8f3f08c 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicMethodDialog.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicMethodDialog.java @@ -26,7 +26,7 @@ import org.jetbrains.plugins.groovy.annotator.intentions.dynamic.MyPair; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; -import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesUtil; +import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider; import javax.swing.*; import javax.swing.event.CellEditorListener; @@ -46,7 +46,7 @@ public class DynamicMethodDialog extends DynamicDialog { private final GrReferenceExpression myReferenceExpression; public DynamicMethodDialog(GrReferenceExpression referenceExpression) { - super(referenceExpression, QuickfixUtil.createSettings(referenceExpression), GroovyExpectedTypesUtil.calculateTypeConstraints((GrExpression)referenceExpression.getParent())); + super(referenceExpression, QuickfixUtil.createSettings(referenceExpression), GroovyExpectedTypesProvider.calculateTypeConstraints((GrExpression)referenceExpression.getParent())); myReferenceExpression = referenceExpression; assert getSettings().isMethod(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicPropertyDialog.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicPropertyDialog.java index 3bd0191d323d..98c3dd49e7de 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicPropertyDialog.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicPropertyDialog.java @@ -20,7 +20,7 @@ import org.jetbrains.plugins.groovy.GroovyBundle; import org.jetbrains.plugins.groovy.annotator.intentions.QuickfixUtil; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; -import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesUtil; +import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider; import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.SupertypeConstraint; /** @@ -32,7 +32,7 @@ public class DynamicPropertyDialog extends DynamicDialog { private final GrArgumentLabel myLabel; public DynamicPropertyDialog(GrReferenceExpression referenceExpression) { - super(referenceExpression, QuickfixUtil.createSettings(referenceExpression), GroovyExpectedTypesUtil.calculateTypeConstraints(referenceExpression)); + super(referenceExpression, QuickfixUtil.createSettings(referenceExpression), GroovyExpectedTypesProvider.calculateTypeConstraints(referenceExpression)); myReferenceExpression = referenceExpression; myLabel = null; setTitle(GroovyBundle.message("add.dynamic.property", referenceExpression.getReferenceName())); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyExpectedTypesProvider.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyExpectedTypesProvider.java deleted file mode 100644 index 0d41ab0ed3d1..000000000000 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyExpectedTypesProvider.java +++ /dev/null @@ -1,261 +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 org.jetbrains.plugins.groovy.codeInsight; - -import com.intellij.codeInsight.*; -import com.intellij.openapi.components.ServiceManager; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.project.Project; -import com.intellij.psi.*; -import com.intellij.psi.codeStyle.JavaCodeStyleManager; -import com.intellij.psi.codeStyle.VariableKind; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.search.PsiShortNamesCache; -import com.intellij.util.ArrayUtil; -import com.intellij.util.containers.hash.HashSet; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor; -import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; -import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrForStatement; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForClause; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression; - -import java.util.Set; - -/** - * @author Maxim.Medvedev - */ -public class GroovyExpectedTypesProvider { - private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.codeInsight.GroovyExpectedTypesProvider"); - - private static final ExpectedTypesProvider.ExpectedClassProvider OUR_GLOBAL_SCOPE_CLASS_PROVIDER = new ExpectedTypesProvider.ExpectedClassProvider() { - public PsiField[] findDeclaredFields(final PsiManager manager, String name) { - final PsiShortNamesCache cache = JavaPsiFacade.getInstance(manager.getProject()).getShortNamesCache(); - GlobalSearchScope scope = GlobalSearchScope.allScope(manager.getProject()); - return cache.getFieldsByName(name, scope); - } - - public PsiMethod[] findDeclaredMethods(final PsiManager manager, String name) { - final PsiShortNamesCache cache = JavaPsiFacade.getInstance(manager.getProject()).getShortNamesCache(); - GlobalSearchScope scope = GlobalSearchScope.allScope(manager.getProject()); - return cache.getMethodsByName(name, scope); - } - }; - - public GroovyExpectedTypesProvider() { - } - - public static GroovyExpectedTypesProvider getInstance(Project project) { - return ServiceManager.getService(project, GroovyExpectedTypesProvider.class); - } - - private static ExpectedTypeInfoImpl createInfoImpl(@NotNull PsiType type, int kind, PsiType defaultType, TailType tailType) { - int dims = 0; - while (type instanceof PsiArrayType) { - type = ((PsiArrayType)type).getComponentType(); - LOG.assertTrue(defaultType instanceof PsiArrayType); - defaultType = ((PsiArrayType)defaultType).getComponentType(); - dims++; - } - return new ExpectedTypeInfoImpl(type, kind, dims, defaultType, tailType); - } - - - @Nullable - public ExpectedTypeInfo[] getExpectedTypes(GrExpression expr, - boolean forCompletion, - final boolean voidable) { - return getExpectedTypes(expr, forCompletion, OUR_GLOBAL_SCOPE_CLASS_PROVIDER, voidable); - } - - @Nullable - public ExpectedTypeInfo[] getExpectedTypes(GrExpression expr, - boolean forCompletion, - ExpectedTypesProvider.ExpectedClassProvider classProvider, - final boolean voidable) { - if (expr == null) return null; - PsiElement parent = expr.getParent(); - while (parent instanceof GrParenthesizedExpression) { - expr = (GrExpression)parent; - parent = parent.getParent(); - } - MyParentVisitor visitor = new MyParentVisitor(expr, forCompletion, classProvider, voidable); - ((GroovyPsiElement)parent).accept(visitor); - return visitor.getResult(); - } - - - private static class MyParentVisitor extends GroovyElementVisitor { - private ExpectedTypeInfo[] myResult = ExpectedTypeInfo.EMPTY_ARRAY; - - private GrExpression myExpr; - private final boolean myForCompletion; - private final ExpectedTypesProvider.ExpectedClassProvider myClassProvider; - private final boolean myVoidable; - - private MyParentVisitor(GrExpression expr, - boolean forCompletion, - ExpectedTypesProvider.ExpectedClassProvider classProvider, - boolean voidable) { - myExpr = expr; - myForCompletion = forCompletion; - myClassProvider = classProvider; - myVoidable = voidable; - } - - public ExpectedTypeInfo[] getResult() { - return myResult; - } - - @Override - public void visitAssignmentExpression(GrAssignmentExpression assignment) { - if (myExpr == assignment.getRValue()) { - GrExpression lExpr = assignment.getLValue(); - PsiType type = lExpr.getType(); - if (type != null) { - TailType tailType = getAssignmentRValueTailType(assignment); - ExpectedTypeInfoImpl info = createInfoImpl(type, ExpectedTypeInfo.TYPE_OR_SUBTYPE, type, tailType); - if (lExpr instanceof GrReferenceExpression) { - PsiElement refElement = ((GrReferenceExpression)lExpr).resolve(); - if (refElement instanceof GrVariable) { - info.expectedName = getPropertyName((GrVariable)refElement); - } - } - myResult = new ExpectedTypeInfo[]{info}; - } - else { - myResult = ExpectedTypeInfo.EMPTY_ARRAY; - } - - } - else { - if (myForCompletion) { - myExpr = (GrExpression)myExpr.getParent(); - ((GroovyPsiElement)assignment.getParent()).accept(this); - return; - } - - GrExpression rExpr = assignment.getRValue(); - if (rExpr != null) { - PsiType type = rExpr.getType(); - if (type != null) { - if (type instanceof PsiClassType) { - final PsiClass resolved = ((PsiClassType)type).resolve(); - if (resolved instanceof PsiAnonymousClass) { - type = ((PsiAnonymousClass)resolved).getBaseClassType(); - } - } - ExpectedTypeInfoImpl info = createInfoImpl(type, ExpectedTypeInfo.TYPE_OR_SUPERTYPE, type, - TailType.NONE); - myResult = new ExpectedTypeInfo[]{info}; - return; - } - } - myResult = ExpectedTypeInfo.EMPTY_ARRAY; - } - } - - @Override - public void visitArgumentList(GrArgumentList list) { - final PsiElement parent = list.getParent(); - - GroovyResolveResult[] results = null; - if (parent instanceof GrMethodCallExpression) { - final GrExpression expression = ((GrMethodCallExpression)parent).getInvokedExpression(); - if (expression instanceof GrReferenceExpression) { - results = ((GrReferenceExpression)expression).multiResolve(false); - } - } - else if (parent instanceof GrApplicationStatement) { - final GrExpression expression = ((GrApplicationStatement)parent).getFunExpression(); - if (expression instanceof GrReferenceExpression) { - results = ((GrReferenceExpression)expression).multiResolve(false); - } - } - else if (parent instanceof GrConstructorCall) { - results = ((GrConstructorCall)parent).multiResolveConstructor(); - } - - if (results == null || results.length == 0) return; - - final int argumentIndex = list.getExpressionArgumentIndex(myExpr); - assert argumentIndex != -1; - - Set infos = new HashSet(); - for (GroovyResolveResult result : results) { - final PsiElement element = result.getElement(); - if (!(element instanceof PsiMethod)) continue; - final PsiParameter[] parameters = ((PsiMethod)element).getParameterList().getParameters(); - if (parameters.length < argumentIndex) continue; - final PsiParameter parameter = parameters[argumentIndex]; - final PsiType type = parameter.getType(); - final TailType tailType = getMethodArgumentTailType(myExpr, argumentIndex, (PsiMethod)element, result.getSubstitutor(), parameters); - infos.add(createInfoImpl(type, ExpectedTypeInfo.TYPE_OR_SUBTYPE, type, tailType)); - } - myResult = infos.toArray(new ExpectedTypeInfo[infos.size()]); - } - - private static TailType getAssignmentRValueTailType(GrAssignmentExpression assignment) { - if (assignment.getParent() instanceof GrExpression) { - if (!(assignment.getParent().getParent() instanceof GrForStatement)) { - return TailType.SEMICOLON; - } - - GrForStatement forStatement = (GrForStatement)assignment.getParent().getParent(); - final GrForClause forClause = forStatement.getClause(); - if (forClause instanceof GrTraditionalForClause) { - if (ArrayUtil.find(((GrTraditionalForClause)forClause).getUpdate(), assignment.getParent()) != -1) { - return TailType.SEMICOLON; - } - } - } - return TailType.NONE; - } - - @Nullable - private static String getPropertyName(GrVariable variable) { - final String name = variable.getName(); - if (name == null) return null; - JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(variable.getProject()); - VariableKind variableKind = codeStyleManager.getVariableKind(variable); - return codeStyleManager.variableNameToPropertyName(name, variableKind); - } - - private TailType getMethodArgumentTailType(final GrExpression argument, final int index, final PsiMethod method, final PsiSubstitutor substitutor, - final PsiParameter[] parms) { - if (index >= parms.length) { - return TailType.NONE; - } - if (index == parms.length - 1) { - //myTailType = CompletionUtil.NONE_TAIL; - final PsiElement call = argument.getParent().getParent(); - - PsiType returnType = method.getReturnType(); - if (returnType != null) returnType = substitutor.substitute(returnType); - return (PsiType.VOID.equals(returnType) || returnType == null) && call.getParent() instanceof PsiStatement - ? TailTypes.CALL_RPARENTH_SEMICOLON - : TailTypes.CALL_RPARENTH; - } - return TailType.COMMA; - } - } -} diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java index c52e4b5bb0ee..cd1871292fdb 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java @@ -15,7 +15,6 @@ */ package org.jetbrains.plugins.groovy.lang.completion; -import com.intellij.codeInsight.ExpectedTypeInfo; import com.intellij.codeInsight.completion.*; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupItemUtil; @@ -34,12 +33,12 @@ import gnu.trove.THashSet; import gnu.trove.TObjectHashingStrategy; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.plugins.groovy.codeInsight.GroovyExpectedTypesProvider; import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral; -import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; +import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider; +import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint; import java.util.Arrays; import java.util.Set; @@ -51,14 +50,14 @@ import static com.intellij.patterns.PlatformPatterns.psiElement; */ public class GroovySmartCompletionContributor extends CompletionContributor { private static final ElementPattern INSIDE_EXPRESSION = psiElement().withParent(GrExpression.class); - private static final TObjectHashingStrategy EXPECTED_TYPE_INFO_STRATEGY = - new TObjectHashingStrategy() { - public int computeHashCode(final ExpectedTypeInfo object) { + private static final TObjectHashingStrategy EXPECTED_TYPE_INFO_STRATEGY = + new TObjectHashingStrategy() { + public int computeHashCode(final TypeConstraint object) { return object.getType().hashCode(); } - public boolean equals(final ExpectedTypeInfo o1, final ExpectedTypeInfo o2) { - return o1.getType().equals(o2.getType()); + public boolean equals(final TypeConstraint o1, final TypeConstraint o2) { + return o1.getClass().equals(o2.getClass()) && o1.getType().equals(o2.getType()); } }; @@ -71,15 +70,15 @@ public class GroovySmartCompletionContributor extends CompletionContributor { final PsiElement position = params.getPosition(); if (position.getParent() instanceof GrLiteral) return; - final THashSet _infos = new THashSet(); + final THashSet _infos = new THashSet(); ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { _infos.addAll(Arrays.asList(getExpectedTypes(params))); } }); - final Set infos = ApplicationManager.getApplication().runReadAction(new Computable>() { - public Set compute() { - return new THashSet(_infos, EXPECTED_TYPE_INFO_STRATEGY); + final Set infos = ApplicationManager.getApplication().runReadAction(new Computable>() { + public Set compute() { + return new THashSet(_infos, EXPECTED_TYPE_INFO_STRATEGY); } }); @@ -99,8 +98,8 @@ public class GroovySmartCompletionContributor extends CompletionContributor { } } if (type == null) return; - for (ExpectedTypeInfo info : infos) { - if (TypesUtil.isAssignableByMethodCallConversion(info.getType(), type, position.getManager(), GlobalSearchScope.allScope(position.getProject()))) { + for (TypeConstraint info : infos) { + if (info.satisfied(type, position.getManager(), GlobalSearchScope.allScope(position.getProject()))) { final LookupElement lookupElement = LookupItemUtil.objectToLookupItem(variant); result.addElement(lookupElement); break; @@ -115,12 +114,11 @@ public class GroovySmartCompletionContributor extends CompletionContributor { } @Nullable - public static ExpectedTypeInfo[] getExpectedTypes(CompletionParameters params) { + public static TypeConstraint[] getExpectedTypes(CompletionParameters params) { final PsiElement position = params.getPosition(); final GrExpression expression = PsiTreeUtil.getParentOfType(position, GrExpression.class); if (expression != null) { - return GroovyExpectedTypesProvider.getInstance(position.getProject()) - .getExpectedTypes(expression, true, params.getCompletionType() == CompletionType.SMART); + return GroovyExpectedTypesProvider.calculateTypeConstraints(expression); } return null; } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java similarity index 68% rename from plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesUtil.java rename to plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java index 923a3fff3c41..c590e65b1ea6 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java @@ -15,25 +15,24 @@ */ package org.jetbrains.plugins.groovy.lang.psi.expectedTypes; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiType; +import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrIfStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrParametersOwner; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrWhileStatement; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrIfStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrThrowStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; @@ -44,10 +43,13 @@ import java.util.List; /** * @author ven */ -public class GroovyExpectedTypesUtil { +public class GroovyExpectedTypesProvider { + private GroovyExpectedTypesProvider() { + } + public static TypeConstraint[] calculateTypeConstraints(GrExpression expression) { MyCalculator calculator = new MyCalculator(expression); - ((GroovyPsiElement) expression.getParent()).accept(calculator); + ((GroovyPsiElement)expression.getParent()).accept(calculator); return calculator.getResult(); } @@ -58,117 +60,101 @@ public class GroovyExpectedTypesUtil { public MyCalculator(GrExpression expression) { myExpression = expression; - } - - public void visitElement(GroovyPsiElement element) { - makeDefault(); + myResult = new TypeConstraint[]{SubtypeConstraint.create("java.lang.Object", myExpression)}; } public void visitReturnStatement(GrReturnStatement returnStatement) { GrParametersOwner parent = PsiTreeUtil.getParentOfType(returnStatement, GrMethod.class, GrClosableBlock.class); if (parent instanceof GrMethod) { - GrTypeElement typeElement = ((GrMethod) parent).getReturnTypeElementGroovy(); + GrTypeElement typeElement = ((GrMethod)parent).getReturnTypeElementGroovy(); if (typeElement != null) { PsiType type = typeElement.getType(); - myResult = new TypeConstraint[] {SubtypeConstraint.create(type)}; - return; + myResult = new TypeConstraint[]{SubtypeConstraint.create(type)}; } } - makeDefault(); } public void visitVariable(GrVariable variable) { if (myExpression.equals(variable.getInitializerGroovy())) { PsiType type = variable.getDeclaredType(); if (type != null) { - myResult = new TypeConstraint[] {new SubtypeConstraint(type, type)}; - return; + myResult = new TypeConstraint[]{new SubtypeConstraint(type, type)}; } } - makeDefault(); } public void visitMethodCallExpression(GrMethodCallExpression methodCall) { if (myExpression.equals(methodCall.getInvokedExpression())) { myResult = new TypeConstraint[]{SubtypeConstraint.create("groovy.lang.Closure", methodCall)}; - } else { - makeDefault(); } } public void visitIfStatement(GrIfStatement ifStatement) { if (myExpression.equals(ifStatement.getCondition())) { - myResult = new TypeConstraint[] {new SubtypeConstraint(TypesUtil.getJavaLangObject(ifStatement), PsiType.BOOLEAN)}; - } else makeDefault(); + myResult = new TypeConstraint[]{new SubtypeConstraint(TypesUtil.getJavaLangObject(ifStatement), PsiType.BOOLEAN)}; + } } public void visitWhileStatement(GrWhileStatement whileStatement) { if (myExpression.equals(whileStatement.getCondition())) { - myResult = new TypeConstraint[] {new SubtypeConstraint(TypesUtil.getJavaLangObject(whileStatement), PsiType.BOOLEAN)}; - } else makeDefault(); + myResult = new TypeConstraint[]{new SubtypeConstraint(TypesUtil.getJavaLangObject(whileStatement), PsiType.BOOLEAN)}; + } } public void visitTraditionalForClause(GrTraditionalForClause forClause) { if (myExpression.equals(forClause.getCondition())) { - myResult = new TypeConstraint[] {new SubtypeConstraint(TypesUtil.getJavaLangObject(forClause), PsiType.BOOLEAN)}; - } else makeDefault(); + myResult = new TypeConstraint[]{new SubtypeConstraint(TypesUtil.getJavaLangObject(forClause), PsiType.BOOLEAN)}; + } } public void visitArgumentList(GrArgumentList list) { PsiElement parent = list.getParent(); List constraints = new ArrayList(); if (parent instanceof GrCallExpression) { - GroovyResolveResult[] variants = ((GrCallExpression) parent).getMethodVariants(); - int idx = getIndex(list); + GroovyResolveResult[] variants = ((GrCallExpression)parent).getMethodVariants(); + int idx = list.getExpressionArgumentIndex(myExpression); for (GroovyResolveResult variant : variants) { PsiElement element = variant.getElement(); + PsiParameter[] parameters = null; if (element instanceof GrParametersOwner) { - GrParameter[] parameters = ((GrParametersOwner) element).getParameters(); - if (parameters.length <= idx) continue; - PsiType parameterType = variant.getSubstitutor().substitute(parameters[idx].getType()); - constraints.add(SubtypeConstraint.create(parameterType)); + parameters = ((GrParametersOwner)element).getParameters(); } + else if (element instanceof PsiMethod) { + parameters = ((PsiMethod)element).getParameterList().getParameters(); + } + if (parameters == null || parameters.length <= idx) continue; + PsiType parameterType = variant.getSubstitutor().substitute(parameters[idx].getType()); + constraints.add(SubtypeConstraint.create(parameterType)); } } - if (constraints.isEmpty()) makeDefault(); - else { + if (!constraints.isEmpty()) { myResult = constraints.toArray(new TypeConstraint[constraints.size()]); } } - private int getIndex(GrArgumentList list) { - GrExpression[] arguments = list.getExpressionArguments(); - for (int i = 0; i < arguments.length; i++) { - if (myExpression.equals(arguments[i])) return i; - } - return -1; - } - public void visitAssignmentExpression(GrAssignmentExpression expression) { GrExpression rValue = expression.getRValue(); if (myExpression.equals(rValue)) { PsiType lType = expression.getLValue().getType(); - if (lType == null) makeDefault(); - else { + if (lType != null) { myResult = new TypeConstraint[]{SubtypeConstraint.create(lType)}; } - } else if (myExpression.equals(expression.getLValue())) { - if (rValue == null) makeDefault(); - else { + } + else if (myExpression.equals(expression.getLValue())) { + if (rValue != null) { PsiType rType = rValue.getType(); - if (rType == null) makeDefault(); - else { + if (rType != null) { myResult = new TypeConstraint[]{SupertypeConstraint.create(rType)}; } } } } - private void makeDefault() { - myResult = new TypeConstraint[]{ - SubtypeConstraint.create("java.lang.Object", myExpression) - }; + @Override + public void visitThrowStatement(GrThrowStatement throwStatement) { + final PsiClassType trowable = PsiType.getJavaLangTrowable(myExpression.getManager(), throwStatement.getResolveScope()); + myResult = new TypeConstraint[]{SubtypeConstraint.create(trowable)}; } public TypeConstraint[] getResult() { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SubtypeConstraint.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SubtypeConstraint.java index ae8a10706b31..80821405f521 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SubtypeConstraint.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SubtypeConstraint.java @@ -15,9 +15,13 @@ */ package org.jetbrains.plugins.groovy.lang.psi.expectedTypes; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiType; import com.intellij.psi.PsiClassType; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiManager; +import com.intellij.psi.PsiType; +import com.intellij.psi.search.GlobalSearchScope; +import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; + import static org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType; /** @@ -31,8 +35,8 @@ public class SubtypeConstraint extends TypeConstraint { myDefaultType = defaultType; } - public boolean satisfied(PsiType type){ - return myType.isAssignableFrom(type); + public boolean satisfied(PsiType type, PsiManager manager, GlobalSearchScope scope){ + return TypesUtil.isAssignableByMethodCallConversion(getType(), type, manager, scope); } public PsiType getDefaultType() { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SupertypeConstraint.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SupertypeConstraint.java index dd43b02732a9..f982d7a069a2 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SupertypeConstraint.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SupertypeConstraint.java @@ -15,9 +15,13 @@ */ package org.jetbrains.plugins.groovy.lang.psi.expectedTypes; -import com.intellij.psi.PsiType; -import com.intellij.psi.PsiElement; import com.intellij.psi.PsiClassType; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiManager; +import com.intellij.psi.PsiType; +import com.intellij.psi.search.GlobalSearchScope; +import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; + import static org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType; /** @@ -31,8 +35,8 @@ public class SupertypeConstraint extends TypeConstraint { myDefaultType = defaultType; } - public boolean satisfied(PsiType type){ - return type.isAssignableFrom(myType); + public boolean satisfied(PsiType type, PsiManager manager, GlobalSearchScope scope){ + return TypesUtil.isAssignableByMethodCallConversion(type, getType(), manager, scope); } public PsiType getDefaultType() { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeConstraint.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeConstraint.java index dda1bc58e69c..289041380684 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeConstraint.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeConstraint.java @@ -15,7 +15,9 @@ */ package org.jetbrains.plugins.groovy.lang.psi.expectedTypes; +import com.intellij.psi.PsiManager; import com.intellij.psi.PsiType; +import com.intellij.psi.search.GlobalSearchScope; /** * @author ven @@ -23,7 +25,7 @@ import com.intellij.psi.PsiType; public abstract class TypeConstraint { protected final PsiType myType; - public abstract boolean satisfied(PsiType type); + public abstract boolean satisfied(PsiType type, PsiManager manager, GlobalSearchScope scope); public abstract PsiType getDefaultType(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeEquals.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeEquals.java index f451ccff15ee..2f45163941d3 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeEquals.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeEquals.java @@ -15,9 +15,12 @@ */ package org.jetbrains.plugins.groovy.lang.psi.expectedTypes; -import com.intellij.psi.PsiType; -import com.intellij.psi.PsiElement; import com.intellij.psi.PsiClassType; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiManager; +import com.intellij.psi.PsiType; +import com.intellij.psi.search.GlobalSearchScope; + import static org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType; /** @@ -28,7 +31,7 @@ public class TypeEquals extends TypeConstraint { super(type); } - public boolean satisfied(PsiType type){ + public boolean satisfied(PsiType type, PsiManager manager, GlobalSearchScope scope){ return type.equals(myType); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java index e3049b8a6498..24ab1063a72c 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java @@ -208,8 +208,6 @@ public class TypesUtil { } } - if (lType.equalsToText(JAVA_LANG_STRING)) return true; - rType = boxPrimitiveType(rType, manager, scope); lType = boxPrimitiveType(lType, manager, scope); diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java index c36ee4213ac4..641f162090ca 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java @@ -82,7 +82,7 @@ public class GroovyCompletionTest extends LightCodeInsightFixtureTestCase { myFixture.testCompletion(getTestName(false) + ".groovy", getTestName(false) + "_after.groovy"); } -public void testEachMethodForMapWithKeyValue() throws Throwable { + public void testEachMethodForMapWithKeyValue() throws Throwable { doBasicTest(); } @@ -267,7 +267,7 @@ public void testEachMethodForMapWithKeyValue() throws Throwable { } public void testPropertyWithSecondUpperLetter() throws Exception { - myFixture.testCompletionVariants(getTestName(false)+".groovy", "geteMail", "getePost"); + myFixture.testCompletionVariants(getTestName(false) + ".groovy", "geteMail", "getePost"); } public void testSmartCompletionInAssignmentExpression() throws Throwable { @@ -286,4 +286,7 @@ public void testEachMethodForMapWithKeyValue() throws Throwable { doSmartCompletion("d1", "d2"); } + public void testReturnStatement() throws Exception { + doSmartCompletion("b", "b1", "b2", "foo"); + } } diff --git a/plugins/groovy/testdata/groovy/completion/ReturnStatement.groovy b/plugins/groovy/testdata/groovy/completion/ReturnStatement.groovy new file mode 100644 index 000000000000..fae09e457f8a --- /dev/null +++ b/plugins/groovy/testdata/groovy/completion/ReturnStatement.groovy @@ -0,0 +1,6 @@ +boolean foo(String s, Date d) { + boolean b=true; + Boolean b1= false; + def b2=false; + return +} \ No newline at end of file From 53a2fda7faaaad115842710d43e6438e2ef83d28 Mon Sep 17 00:00:00 2001 From: Maxim Medvedev Date: Fri, 12 Feb 2010 11:58:39 +0300 Subject: [PATCH 05/93] smart completion for unary operations --- .../GroovyExpectedTypesProvider.java | 20 +++++++++++ .../statements/expressions/TypesUtil.java | 36 ++++++++++++++----- .../processors/CompletionProcessor.java | 2 ++ .../processors/MethodResolverProcessor.java | 2 ++ .../processors/PropertyResolverProcessor.java | 2 ++ .../resolve/processors/ResolverProcessor.java | 6 ++-- .../plugins/groovy/GroovyCompletionTest.java | 4 +++ .../completion/IncSmartCompletion.groovy | 15 ++++++++ 8 files changed, 76 insertions(+), 11 deletions(-) create mode 100644 plugins/groovy/testdata/groovy/completion/IncSmartCompletion.groovy diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java index c590e65b1ea6..ed726ad77086 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java @@ -16,6 +16,7 @@ package org.jetbrains.plugins.groovy.lang.psi.expectedTypes; import com.intellij.psi.*; +import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; @@ -31,6 +32,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrThrowStatem import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrUnaryExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; @@ -157,6 +159,24 @@ public class GroovyExpectedTypesProvider { myResult = new TypeConstraint[]{SubtypeConstraint.create(trowable)}; } + @Override + public void visitUnaryExpression(final GrUnaryExpression expression) { + TypeConstraint constraint = new TypeConstraint(PsiType.INT) { + @Override + public boolean satisfied(PsiType type, PsiManager manager, GlobalSearchScope scope) { + return TypesUtil + .getOverloadedOperatorCandidates(TypesUtil.boxPrimitiveType(type, manager, scope), expression.getOperationTokenType(), + expression, PsiType.EMPTY_ARRAY).length > 0; + } + + @Override + public PsiType getDefaultType() { + return PsiType.INT; + } + }; + myResult = new TypeConstraint[]{constraint}; + } + public TypeConstraint[] getResult() { return myResult; } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java index 24ab1063a72c..2255134b45ab 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java @@ -93,6 +93,28 @@ public class TypesUtil { @Nullable public static PsiType getOverloadedOperatorType(PsiType thisType, String operatorName, GroovyPsiElement place, PsiType[] argumentTypes) { + final GroovyResolveResult[] candidates = getOverloadedOperatorCandidates(thisType, operatorName, place, argumentTypes); + if (candidates.length == 1) { + final PsiElement element = candidates[0].getElement(); + if (element instanceof PsiMethod) { + return candidates[0].getSubstitutor().substitute(((PsiMethod)element).getReturnType()); + } + } + return null; + } + + @NotNull + public static GroovyResolveResult[] getOverloadedOperatorCandidates(PsiType thisType, + IElementType tokenType, + GroovyPsiElement place, + PsiType[] argumentTypes) { + return getOverloadedOperatorCandidates(thisType, ourOperationsToOperatorNames.get(tokenType), place, argumentTypes); + } + @NotNull + public static GroovyResolveResult[] getOverloadedOperatorCandidates(PsiType thisType, + String operatorName, + GroovyPsiElement place, + PsiType[] argumentTypes) { if (operatorName != null) { MethodResolverProcessor processor = new MethodResolverProcessor(operatorName, place, false, thisType, argumentTypes, PsiType.EMPTY_ARRAY); @@ -101,21 +123,17 @@ public class TypesUtil { final PsiClassType.ClassResolveResult resolveResult = classtype.resolveGenerics(); final PsiClass lClass = resolveResult.getElement(); if (lClass != null) { - lClass.processDeclarations(processor, ResolveState.initial().put(PsiSubstitutor.KEY, resolveResult.getSubstitutor()), null, place); + lClass + .processDeclarations(processor, ResolveState.initial().put(PsiSubstitutor.KEY, resolveResult.getSubstitutor()), null, place); } } ResolveUtil.processNonCodeMethods(thisType, processor, place.getProject(), place, false); - final GroovyResolveResult[] candidates = processor.getCandidates(); - if (candidates.length == 1) { - final PsiElement element = candidates[0].getElement(); - if (element instanceof PsiMethod) { - return candidates[0].getSubstitutor().substitute(((PsiMethod)element).getReturnType()); - } - } + return processor.getCandidates(); } - return null; + return GroovyResolveResult.EMPTY_ARRAY; } + private static final Map ourPrimitiveTypesToClassNames = new HashMap(); private static final String NULL = "null"; private static final String JAVA_MATH_BIG_DECIMAL = "java.math.BigDecimal"; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/CompletionProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/CompletionProcessor.java index 16209a63aa01..97ad50dbfcbf 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/CompletionProcessor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/CompletionProcessor.java @@ -20,6 +20,7 @@ import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiType; import com.intellij.psi.ResolveState; +import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; @@ -53,6 +54,7 @@ public class CompletionProcessor extends ResolverProcessor { return new CompletionProcessor(place, EnumSet.of(ResolveKind.PACKAGE, ResolveKind.CLASS), null); } + @NotNull public GroovyResolveResult[] getCandidates() { if (myCandidates.size() == 0) return GroovyResolveResult.EMPTY_ARRAY; return ResolveUtil.filterSameSignatureCandidates(myCandidates); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/MethodResolverProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/MethodResolverProcessor.java index d43dcbb5c16f..93ede96f2a4d 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/MethodResolverProcessor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/MethodResolverProcessor.java @@ -22,6 +22,7 @@ import com.intellij.psi.*; import com.intellij.psi.scope.JavaScopeProcessorEvent; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; @@ -207,6 +208,7 @@ public class MethodResolverProcessor extends ResolverProcessor { return rType; } + @NotNull public GroovyResolveResult[] getCandidates() { if (!myCandidates.isEmpty()) { return filterCandidates(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/PropertyResolverProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/PropertyResolverProcessor.java index 8b23c8277b72..2974c45b0f72 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/PropertyResolverProcessor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/PropertyResolverProcessor.java @@ -20,6 +20,7 @@ import com.intellij.openapi.util.Key; import com.intellij.psi.*; import com.intellij.psi.scope.NameHint; import com.intellij.psi.util.PsiTreeUtil; +import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; @@ -97,6 +98,7 @@ public class PropertyResolverProcessor extends ResolverProcessor { return containingClass.findFieldByName(fieldName, false) != null; } + @NotNull public GroovyResolveResult[] getCandidates() { if (myProperty != null) { if (myCandidates.isEmpty()) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/ResolverProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/ResolverProcessor.java index 21c614da63a5..ce2ca46b45e5 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/ResolverProcessor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/ResolverProcessor.java @@ -23,18 +23,19 @@ import com.intellij.psi.scope.NameHint; import com.intellij.psi.scope.PsiScopeProcessor; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; -import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement; import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyResolveResultImpl; -import static org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint.ResolveKind.*; +import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil; import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; +import static org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint.ResolveKind.*; + /** * @author ven */ @@ -110,6 +111,7 @@ public class ResolverProcessor implements PsiScopeProcessor, NameHint, ClassHint return true; } + @NotNull public GroovyResolveResult[] getCandidates() { return myCandidates.toArray(new GroovyResolveResult[myCandidates.size()]); } diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java index 641f162090ca..419fa4733123 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java @@ -289,4 +289,8 @@ public class GroovyCompletionTest extends LightCodeInsightFixtureTestCase { public void testReturnStatement() throws Exception { doSmartCompletion("b", "b1", "b2", "foo"); } + + public void testIncSmartCompletion() throws Exception { + doSmartCompletion("a", "b"); + } } diff --git a/plugins/groovy/testdata/groovy/completion/IncSmartCompletion.groovy b/plugins/groovy/testdata/groovy/completion/IncSmartCompletion.groovy new file mode 100644 index 000000000000..ffd081ad97cc --- /dev/null +++ b/plugins/groovy/testdata/groovy/completion/IncSmartCompletion.groovy @@ -0,0 +1,15 @@ +class A{ + def next() { + return this; + } +} + +class B{ + def next() { + return this; + } +} + +A a=new A() +B b=new B() +++; \ No newline at end of file From 2fbb200fe6c861dba6412d770e3e4ccd5ed7f615 Mon Sep 17 00:00:00 2001 From: Eugene Kudelevsky Date: Tue, 16 Feb 2010 21:18:46 +0300 Subject: [PATCH 06/93] support custom attribute selectors --- .../template/XmlCustomLiveTemplate.java | 261 ++++++++++-------- 1 file changed, 152 insertions(+), 109 deletions(-) diff --git a/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java b/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java index a34969659c98..cd960ff89f4d 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java +++ b/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java @@ -20,15 +20,13 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; +import com.intellij.openapi.util.Pair; import com.intellij.psi.xml.XmlFile; import com.intellij.util.containers.HashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; +import java.util.*; /** * @author Eugene.Kudelevsky @@ -38,9 +36,11 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { private static final String ATTRS = "ATTRS"; - private static final String POSSIBLE_OPERATIONS = ">+*"; - private static final String HTML_SELECTORS = ".#"; + private static final String OPERATIONS = ">+*"; + private static final String SELECTORS = ".#["; private static final char MARKER = '$'; + private static final String ID = "id"; + private static final String CLASS = "class"; private static enum MyState { OPERATION, WORD, AFTER_NUMBER, NUMBER @@ -54,9 +54,11 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { private static class MyTemplateToken extends MyToken { final String myKey; + final Map myAttribute2Value; - MyTemplateToken(String key) { + MyTemplateToken(String key, Map attribute2value) { myKey = key; + myAttribute2Value = attribute2value; } } @@ -77,7 +79,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } private static boolean isTemplateKeyPart(char c) { - return !Character.isWhitespace(c) && POSSIBLE_OPERATIONS.indexOf(c) < 0; + return !Character.isWhitespace(c) && OPERATIONS.indexOf(c) < 0; } private static int parseNonNegativeInt(@NotNull String s) { @@ -92,13 +94,91 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { private static String getPrefix(@NotNull String templateKey) { for (int i = 0, n = templateKey.length(); i < n; i++) { char c = templateKey.charAt(i); - if (HTML_SELECTORS.indexOf(c) >= 0) { + if (SELECTORS.indexOf(c) >= 0) { return templateKey.substring(0, i); } } return templateKey; } + @Nullable + private static Pair parseAttrNameAndValue(@NotNull String text) { + int eqIndex = text.indexOf('='); + if (eqIndex > 0) { + return new Pair(text.substring(0, eqIndex), text.substring(eqIndex + 1)); + } + return null; + } + + @Nullable + private static MyTemplateToken parseSelectors(@NotNull String text) { + String templateKey = null; + Map attribute2value = new HashMap(); + final List classes = new ArrayList(); + StringBuilder builder = new StringBuilder(); + char lastDelim = 0; + text += MARKER; + for (int i = 0, n = text.length(); i < n; i++) { + char c = text.charAt(i); + if (c == '#' || c == '.' || c == '[' || c == ']' || i == n - 1) { + if (c != ']') { + switch (lastDelim) { + case 0: + templateKey = builder.toString(); + break; + case '#': + attribute2value.put(ID, builder.toString()); + break; + case '.': + if (builder.length() > 0) { + classes.add(builder.toString()); + } + else { + return null; + } + break; + case ']': + if (builder.length() > 0) { + return null; + } + break; + default: + return null; + } + } + else if (lastDelim != '[') { + return null; + } + else { + Pair pair = parseAttrNameAndValue(builder.toString()); + if (pair == null || attribute2value.containsKey(pair.first)) { + return null; + } + attribute2value.put(pair.first, pair.second); + } + lastDelim = c; + builder = new StringBuilder(); + } + else { + builder.append(c); + } + } + if (classes.size() > 0) { + if (attribute2value.containsKey(CLASS)) { + return null; + } + StringBuilder classesAttrValue = new StringBuilder(); + for (int i = 0; i < classes.size(); i++) { + classesAttrValue.append(classes.get(i)); + if (i < classes.size() - 1) { + classesAttrValue.append(' '); + } + } + attribute2value.put(CLASS, classesAttrValue.toString()); + } + return new MyTemplateToken(templateKey, attribute2value); + } + @Nullable private static List parse(@NotNull String text, @NotNull CustomTemplateCallback callback) { text += MARKER; @@ -106,7 +186,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { List result = new ArrayList(); for (int i = 0, n = text.length(); i < n; i++) { char c = text.charAt(i); - if (i == n - 1 || POSSIBLE_OPERATIONS.indexOf(c) >= 0) { + if (i == n - 1 || OPERATIONS.indexOf(c) >= 0) { String key = templateKeyBuilder.toString(); templateKeyBuilder = new StringBuilder(); int num = parseNonNegativeInt(key); @@ -121,7 +201,11 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { if (!callback.isLiveTemplateApplicable(prefix) && prefix.indexOf('<') >= 0) { return null; } - result.add(new MyTemplateToken(key)); + MyTemplateToken token = parseSelectors(key); + if (token == null) { + return null; + } + result.add(token); } result.add(i < n - 1 ? new MyOperationToken(c) : new MyMarkerToken()); } @@ -201,61 +285,53 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } @NotNull - private static String buildAttributesString(@Nullable String id, @NotNull List classes) { + private static String buildAttributesString(Map attribute2value) { StringBuilder result = new StringBuilder(); - if (id != null) { - result.append("id=\"").append(id).append('"'); - if (classes.size() > 0) { + Set> entries = attribute2value.entrySet(); + for (Iterator> it = entries.iterator(); it.hasNext();) { + Map.Entry entry = it.next(); + String name = entry.getKey(); + String value = entry.getValue(); + result.append(name).append("=\"").append(value).append('"'); + if (it.hasNext()) { result.append(' '); } } - if (classes.size() > 0) { - result.append("class=\""); - for (int i = 0; i < classes.size(); i++) { - result.append(classes.get(i)); - if (i < classes.size() - 1) { - result.append(' '); - } - } - result.append('"'); - } return result.toString(); } - private static boolean prepareAndInvokeTemplate(String key, - final CustomTemplateCallback callback, - final TemplateInvokationListener listener) { - String templateKey = null; - String id = null; - final List classes = new ArrayList(); - StringBuilder builder = new StringBuilder(); - char lastDelim = 0; - key += MARKER; - for (int i = 0, n = key.length(); i < n; i++) { - char c = key.charAt(i); - if (c == '#' || c == '.' || i == n - 1) { - switch (lastDelim) { - case 0: - templateKey = builder.toString(); - break; - case '#': - id = builder.toString(); - break; - case '.': - if (builder.length() > 0) { - classes.add(builder.toString()); - } - break; + private static boolean invokeTemplate(MyTemplateToken token, + final CustomTemplateCallback callback, + final TemplateInvokationListener listener) { + String attributes = buildAttributesString(token.myAttribute2Value); + attributes = attributes.length() > 0 ? ' ' + attributes : null; + Map predefinedValues = null; + if (attributes != null) { + predefinedValues = new HashMap(); + predefinedValues.put(ATTRS, attributes); + } + if (callback.isLiveTemplateApplicable(token.myKey)) { + if (attributes != null && !callback.templateContainsVars(token.myKey, ATTRS)) { + TemplateImpl newTemplate = generateTemplateWithAttributes(token.myKey, attributes, callback); + if (newTemplate != null) { + return callback.startTemplate(newTemplate, predefinedValues, listener); } - lastDelim = c; - builder = new StringBuilder(); } - else { - builder.append(c); + return callback.startTemplate(token.myKey, predefinedValues, listener); + } + else { + TemplateImpl template = new TemplateImpl("", ""); + template.addTextSegment('<' + token.myKey); + if (attributes != null) { + template.addVariable(ATTRS, "", "", false); + template.addVariableSegment(ATTRS); } + template.addTextSegment(">"); + template.addVariableSegment(TemplateImpl.END); + template.addTextSegment(""); + template.setToReformat(true); + return callback.startTemplate(template, predefinedValues, listener); } - String attributes = buildAttributesString(id, classes); - return startTemplate(templateKey, callback, listener, attributes.length() > 0 ? ' ' + attributes : null); } private static int findPlaceToInsertAttrs(@NotNull TemplateImpl template) { @@ -293,39 +369,6 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { return null; } - private static boolean startTemplate(String key, - CustomTemplateCallback callback, - TemplateInvokationListener listener, - @Nullable String attributes) { - Map predefinedValues = null; - if (attributes != null) { - predefinedValues = new HashMap(); - predefinedValues.put(ATTRS, attributes); - } - if (callback.isLiveTemplateApplicable(key)) { - if (attributes != null && !callback.templateContainsVars(key, ATTRS)) { - TemplateImpl newTemplate = generateTemplateWithAttributes(key, attributes, callback); - if (newTemplate != null) { - return callback.startTemplate(newTemplate, predefinedValues, listener); - } - } - return callback.startTemplate(key, predefinedValues, listener); - } - else { - TemplateImpl template = new TemplateImpl("", ""); - template.addTextSegment('<' + key); - if (attributes != null) { - template.addVariable(ATTRS, "", "", false); - template.addVariableSegment(ATTRS); - } - template.addTextSegment(">"); - template.addVariableSegment(TemplateImpl.END); - template.addTextSegment(""); - template.setToReformat(true); - return callback.startTemplate(template, predefinedValues, listener); - } - } - private static boolean hasClosingTag(CharSequence text, CharSequence tagName, int offset, int rightBound) { if (offset + 1 < text.length() && text.charAt(offset) == '<' && text.charAt(offset + 1) == '/') { CharSequence closingTagName = parseTagName(text, offset + 2, rightBound); @@ -428,14 +471,14 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { public boolean invoke(int startIndex) { final int n = myTokens.size(); - String templateKey = null; + MyTemplateToken templateToken = null; int number = -1; for (int i = startIndex; i < n; i++) { final int finalI = i; MyToken token = myTokens.get(i); switch (myState) { case OPERATION: - if (templateKey != null) { + if (templateToken != null) { if (token instanceof MyMarkerToken || token instanceof MyOperationToken) { final char sign = token instanceof MyOperationToken ? ((MyOperationToken)token).mySign : MARKER; if (sign == MARKER || sign == '+') { @@ -453,16 +496,16 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } } }; - if (!prepareAndInvokeTemplate(templateKey, myCallback, listener)) { + if (!invokeTemplate(templateToken, myCallback, listener)) { return false; } - templateKey = null; + templateToken = null; } else if (sign == '>') { - if (!startTemplateAndGotoChild(templateKey, finalI)) { + if (!startTemplateAndGotoChild(templateToken, finalI)) { return false; } - templateKey = null; + templateToken = null; } else if (sign == '*') { myState = MyState.NUMBER; @@ -475,7 +518,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { break; case WORD: if (token instanceof MyTemplateToken) { - templateKey = ((MyTemplateToken)token).myKey; + templateToken = ((MyTemplateToken)token); myState = MyState.OPERATION; } else { @@ -495,20 +538,20 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { if (token instanceof MyMarkerToken || token instanceof MyOperationToken) { char sign = token instanceof MyOperationToken ? ((MyOperationToken)token).mySign : MARKER; if (sign == MARKER || sign == '+') { - if (!invokeTemplateSeveralTimes(templateKey, number, finalI)) { + if (!invokeTemplateSeveralTimes(templateToken, number, finalI)) { return false; } - templateKey = null; + templateToken = null; } else if (number > 1) { - return invokeTemplateAndProcessTail(templateKey, i + 1, number); + return invokeTemplateAndProcessTail(templateToken, i + 1, number); } else { assert number == 1; - if (!startTemplateAndGotoChild(templateKey, finalI)) { + if (!startTemplateAndGotoChild(templateToken, finalI)) { return false; } - templateKey = null; + templateToken = null; } myState = MyState.WORD; } @@ -522,7 +565,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { return true; } - private boolean startTemplateAndGotoChild(String templateKey, final int index) { + private boolean startTemplateAndGotoChild(MyTemplateToken templateToken, final int index) { final Object key = new Object(); myCallback.fixStartOfTemplate(key); TemplateInvokationListener listener = new TemplateInvokationListener() { @@ -534,13 +577,13 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } } }; - if (!prepareAndInvokeTemplate(templateKey, myCallback, listener)) { + if (!invokeTemplate(templateToken, myCallback, listener)) { return false; } return true; } - private boolean invokeTemplateSeveralTimes(final String templateKey, final int count, final int index) { + private boolean invokeTemplateSeveralTimes(final MyTemplateToken templateToken, final int count, final int index) { final Object key = new Object(); myCallback.fixStartOfTemplate(key); for (int i = 0; i < count; i++) { @@ -553,7 +596,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { if (inSeparateEvent) { int newCount = count - finalI - 1; if (newCount > 0) { - invokeTemplateSeveralTimes(templateKey, newCount, index); + invokeTemplateSeveralTimes(templateToken, newCount, index); } else { invoke(index + 1); @@ -561,14 +604,14 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } } }; - if (!prepareAndInvokeTemplate(templateKey, myCallback, listener)) { + if (!invokeTemplate(templateToken, myCallback, listener)) { return false; } } return true; } - private boolean invokeTemplateAndProcessTail(final String templateKey, final int tailStart, final int count) { + private boolean invokeTemplateAndProcessTail(final MyTemplateToken templateToken, final int tailStart, final int count) { final Object key = new Object(); myCallback.fixStartOfTemplate(key); for (int i = 0; i < count; i++) { @@ -582,13 +625,13 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { fixEndOffset(); myCallback.gotoEndOfTemplate(key); if (inSeparateEvent) { - invokeTemplateAndProcessTail(templateKey, tailStart, count - finalI - 1); + invokeTemplateAndProcessTail(templateToken, tailStart, count - finalI - 1); } } }); if (interpreter.invoke(tailStart)) { if (inSeparateEvent) { - invokeTemplateAndProcessTail(templateKey, tailStart, count - finalI - 1); + invokeTemplateAndProcessTail(templateToken, tailStart, count - finalI - 1); } } else { @@ -596,7 +639,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } } }; - if (!prepareAndInvokeTemplate(templateKey, myCallback, listener) || flag[0]) { + if (!invokeTemplate(templateToken, myCallback, listener) || flag[0]) { return false; } } From 2845c2e9bfd8cc91a48c8bca9dc0f1822d6d9c21 Mon Sep 17 00:00:00 2001 From: Eugene Kudelevsky Date: Tue, 16 Feb 2010 21:59:21 +0300 Subject: [PATCH 07/93] stable order for attributes + tests --- .../template/XmlCustomLiveTemplate.java | 49 +++++++++++-------- 1 file changed, 28 insertions(+), 21 deletions(-) diff --git a/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java b/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java index cd960ff89f4d..08548c64e010 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java +++ b/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java @@ -23,6 +23,7 @@ import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.util.Pair; import com.intellij.psi.xml.XmlFile; import com.intellij.util.containers.HashMap; +import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -54,9 +55,9 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { private static class MyTemplateToken extends MyToken { final String myKey; - final Map myAttribute2Value; + final List> myAttribute2Value; - MyTemplateToken(String key, Map attribute2value) { + MyTemplateToken(String key, List> attribute2value) { myKey = key; myAttribute2Value = attribute2value; } @@ -113,11 +114,13 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { @Nullable private static MyTemplateToken parseSelectors(@NotNull String text) { String templateKey = null; - Map attribute2value = new HashMap(); + List> attributes = new ArrayList>(); + Set definedAttrs = new HashSet(); final List classes = new ArrayList(); StringBuilder builder = new StringBuilder(); char lastDelim = 0; text += MARKER; + int classAttrPosition = -1; for (int i = 0, n = text.length(); i < n; i++) { char c = text.charAt(i); if (c == '#' || c == '.' || c == '[' || c == ']' || i == n - 1) { @@ -127,15 +130,19 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { templateKey = builder.toString(); break; case '#': - attribute2value.put(ID, builder.toString()); - break; - case '.': - if (builder.length() > 0) { - classes.add(builder.toString()); - } - else { + if (!definedAttrs.add(ID)) { return null; } + attributes.add(new Pair(ID, builder.toString())); + break; + case '.': + if (builder.length() <= 0) { + return null; + } + if (classAttrPosition < 0) { + classAttrPosition = attributes.size(); + } + classes.add(builder.toString()); break; case ']': if (builder.length() > 0) { @@ -151,10 +158,10 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } else { Pair pair = parseAttrNameAndValue(builder.toString()); - if (pair == null || attribute2value.containsKey(pair.first)) { + if (pair == null || !definedAttrs.add(pair.first)) { return null; } - attribute2value.put(pair.first, pair.second); + attributes.add(pair); } lastDelim = c; builder = new StringBuilder(); @@ -164,7 +171,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } } if (classes.size() > 0) { - if (attribute2value.containsKey(CLASS)) { + if (definedAttrs.contains(CLASS)) { return null; } StringBuilder classesAttrValue = new StringBuilder(); @@ -174,9 +181,10 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { classesAttrValue.append(' '); } } - attribute2value.put(CLASS, classesAttrValue.toString()); + assert classAttrPosition >= 0; + attributes.add(classAttrPosition, new Pair(CLASS, classesAttrValue.toString())); } - return new MyTemplateToken(templateKey, attribute2value); + return new MyTemplateToken(templateKey, attributes); } @Nullable @@ -285,13 +293,12 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } @NotNull - private static String buildAttributesString(Map attribute2value) { + private static String buildAttributesString(List> attribute2value) { StringBuilder result = new StringBuilder(); - Set> entries = attribute2value.entrySet(); - for (Iterator> it = entries.iterator(); it.hasNext();) { - Map.Entry entry = it.next(); - String name = entry.getKey(); - String value = entry.getValue(); + for (Iterator> it = attribute2value.iterator(); it.hasNext();) { + Pair pair = it.next(); + String name = pair.first; + String value = pair.second; result.append(name).append("=\"").append(value).append('"'); if (it.hasNext()) { result.append(' '); From ad15cc9f9aa93f629a9bbd876e0abf9cdd59ecf7 Mon Sep 17 00:00:00 2001 From: Eugene Kudelevsky Date: Tue, 16 Feb 2010 22:28:57 +0300 Subject: [PATCH 08/93] support E*N$ selector + tests --- .../template/XmlCustomLiveTemplate.java | 47 +++++++++++-------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java b/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java index 08548c64e010..8e6a65acd97d 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java +++ b/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java @@ -42,6 +42,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { private static final char MARKER = '$'; private static final String ID = "id"; private static final String CLASS = "class"; + private static final String NUMBER_IN_ITERATION_PLACE_HOLDER = "$"; private static enum MyState { OPERATION, WORD, AFTER_NUMBER, NUMBER @@ -293,12 +294,12 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } @NotNull - private static String buildAttributesString(List> attribute2value) { + private static String buildAttributesString(List> attribute2value, int numberInIteration) { StringBuilder result = new StringBuilder(); for (Iterator> it = attribute2value.iterator(); it.hasNext();) { Pair pair = it.next(); String name = pair.first; - String value = pair.second; + String value = pair.second.replace(NUMBER_IN_ITERATION_PLACE_HOLDER, Integer.toString(numberInIteration + 1)); result.append(name).append("=\"").append(value).append('"'); if (it.hasNext()) { result.append(' '); @@ -309,8 +310,9 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { private static boolean invokeTemplate(MyTemplateToken token, final CustomTemplateCallback callback, - final TemplateInvokationListener listener) { - String attributes = buildAttributesString(token.myAttribute2Value); + final TemplateInvokationListener listener, + int numberInIteration) { + String attributes = buildAttributesString(token.myAttribute2Value, numberInIteration); attributes = attributes.length() > 0 ? ' ' + attributes : null; Map predefinedValues = null; if (attributes != null) { @@ -503,7 +505,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } } }; - if (!invokeTemplate(templateToken, myCallback, listener)) { + if (!invokeTemplate(templateToken, myCallback, listener, -1)) { return false; } templateToken = null; @@ -545,13 +547,13 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { if (token instanceof MyMarkerToken || token instanceof MyOperationToken) { char sign = token instanceof MyOperationToken ? ((MyOperationToken)token).mySign : MARKER; if (sign == MARKER || sign == '+') { - if (!invokeTemplateSeveralTimes(templateToken, number, finalI)) { + if (!invokeTemplateSeveralTimes(templateToken, 0, number, finalI)) { return false; } templateToken = null; } else if (number > 1) { - return invokeTemplateAndProcessTail(templateToken, i + 1, number); + return invokeTemplateAndProcessTail(templateToken, 0, number, i + 1); } else { assert number == 1; @@ -584,16 +586,19 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } } }; - if (!invokeTemplate(templateToken, myCallback, listener)) { + if (!invokeTemplate(templateToken, myCallback, listener, -1)) { return false; } return true; } - private boolean invokeTemplateSeveralTimes(final MyTemplateToken templateToken, final int count, final int index) { + private boolean invokeTemplateSeveralTimes(final MyTemplateToken templateToken, + final int startIndex, + final int count, + final int globalIndex) { final Object key = new Object(); myCallback.fixStartOfTemplate(key); - for (int i = 0; i < count; i++) { + for (int i = startIndex; i < count; i++) { final int finalI = i; TemplateInvokationListener listener = new TemplateInvokationListener() { public void finished(boolean inSeparateEvent) { @@ -601,27 +606,29 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { fixEndOffset(); myCallback.gotoEndOfTemplate(key); if (inSeparateEvent) { - int newCount = count - finalI - 1; - if (newCount > 0) { - invokeTemplateSeveralTimes(templateToken, newCount, index); + if (finalI + 1 < count) { + invokeTemplateSeveralTimes(templateToken, finalI + 1, count, globalIndex); } else { - invoke(index + 1); + invoke(globalIndex + 1); } } } }; - if (!invokeTemplate(templateToken, myCallback, listener)) { + if (!invokeTemplate(templateToken, myCallback, listener, i)) { return false; } } return true; } - private boolean invokeTemplateAndProcessTail(final MyTemplateToken templateToken, final int tailStart, final int count) { + private boolean invokeTemplateAndProcessTail(final MyTemplateToken templateToken, + final int startIndex, + final int count, + final int tailStart) { final Object key = new Object(); myCallback.fixStartOfTemplate(key); - for (int i = 0; i < count; i++) { + for (int i = startIndex; i < count; i++) { final int finalI = i; final boolean[] flag = new boolean[]{false}; TemplateInvokationListener listener = new TemplateInvokationListener() { @@ -632,13 +639,13 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { fixEndOffset(); myCallback.gotoEndOfTemplate(key); if (inSeparateEvent) { - invokeTemplateAndProcessTail(templateToken, tailStart, count - finalI - 1); + invokeTemplateAndProcessTail(templateToken, finalI + 1, count, tailStart); } } }); if (interpreter.invoke(tailStart)) { if (inSeparateEvent) { - invokeTemplateAndProcessTail(templateToken, tailStart, count - finalI - 1); + invokeTemplateAndProcessTail(templateToken, finalI + 1, count, tailStart); } } else { @@ -646,7 +653,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } } }; - if (!invokeTemplate(templateToken, myCallback, listener) || flag[0]) { + if (!invokeTemplate(templateToken, myCallback, listener, i) || flag[0]) { return false; } } From 9bc3233f15f0d72da561d562b491d1aad651a757 Mon Sep 17 00:00:00 2001 From: Kirill Kalishev Date: Wed, 17 Feb 2010 15:11:03 +0300 Subject: [PATCH 09/93] IDEA-18706 --- .../com/intellij/ide/ToolkitBugsProcessor.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/platform/platform-impl/src/com/intellij/ide/ToolkitBugsProcessor.java b/platform/platform-impl/src/com/intellij/ide/ToolkitBugsProcessor.java index 660ac475114b..b7de602e4ab3 100644 --- a/platform/platform-impl/src/com/intellij/ide/ToolkitBugsProcessor.java +++ b/platform/platform-impl/src/com/intellij/ide/ToolkitBugsProcessor.java @@ -114,6 +114,21 @@ public class ToolkitBugsProcessor { } } + static class Sun_6785663 extends Handler { + Sun_6785663() { + super("Numbus L&F problem -- update style"); + } + + @Override + boolean process(Throwable e, StackTraceElement[] stack) { + if (e instanceof ClassCastException && stack.length > 1) { + return stack[0].getClassName().equals("javax.swing.plaf.synth.SynthButtonUI") + && stack[0].getMethodName().equals("updateStyle"); + } + return false; + } + } + static class Apple_ExceptionOnChangingMonitors extends Handler { @Override From 1147f0d46976a15078952fed64f380ecb8f0f2e8 Mon Sep 17 00:00:00 2001 From: Alexey Pegov Date: Wed, 17 Feb 2010 15:31:45 +0300 Subject: [PATCH 10/93] prefer last selected over toSelect in open project file chooser dialog --- .../src/com/intellij/ide/actions/OpenProjectAction.java | 2 ++ .../openapi/fileChooser/ex/FileChooserDialogImpl.java | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/java/idea-ui/src/com/intellij/ide/actions/OpenProjectAction.java b/java/idea-ui/src/com/intellij/ide/actions/OpenProjectAction.java index 27c8ef04662d..3058583092d1 100644 --- a/java/idea-ui/src/com/intellij/ide/actions/OpenProjectAction.java +++ b/java/idea-ui/src/com/intellij/ide/actions/OpenProjectAction.java @@ -24,6 +24,7 @@ import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; +import com.intellij.openapi.fileChooser.ex.FileChooserDialogImpl; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.SystemInfo; @@ -63,6 +64,7 @@ public class OpenProjectAction extends AnAction implements DumbAware { } } + descriptor.putUserData(FileChooserDialogImpl.PREFER_LAST_OVER_TO_SELECT, Boolean.TRUE); final VirtualFile[] files = FileChooser.chooseFiles(project, descriptor, userHomeDir); if (files.length == 0 || files[0] == null) return; diff --git a/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileChooserDialogImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileChooserDialogImpl.java index 991663561e71..1c216b9ae3ba 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileChooserDialogImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileChooserDialogImpl.java @@ -60,6 +60,8 @@ import java.util.List; import java.util.Map; public class FileChooserDialogImpl extends DialogWrapper implements FileChooserDialog, FileLookup { + public static final DataKey PREFER_LAST_OVER_TO_SELECT = DataKey.create("PREFER_LAST_OVER_TO_SELECT"); + private final FileChooserDescriptor myChooserDescriptor; protected FileSystemTreeImpl myFileSystemTree; @@ -106,7 +108,8 @@ public class FileChooserDialogImpl extends DialogWrapper implements FileChooserD selectFile = project.getBaseDir(); } } else { - selectFile = (toSelect == null) ? ourLastFile : toSelect; + selectFile = (toSelect == null) ? ourLastFile : (ourLastFile == null ? toSelect : myChooserDescriptor.getUserData( + PREFER_LAST_OVER_TO_SELECT.getName()) == null ? toSelect : ourLastFile); } final VirtualFile file = selectFile; From 15207e3c2536c3d7cbf7f3a2f1738cfaec02534a Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Mon, 15 Feb 2010 16:49:59 +0300 Subject: [PATCH 11/93] IDEA-52205 --- .../intellij/psi/impl/JavaPsiFacadeImpl.java | 22 +++++++++++++------ .../impl/file/JavaDirectoryServiceImpl.java | 10 ++++++--- .../psi/impl/file/PsiPackageImpl.java | 5 +++-- .../resolve/ClassCollectingProcessor.java | 2 +- 4 files changed, 26 insertions(+), 13 deletions(-) diff --git a/java/java-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java b/java/java-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java index 3a1c401507ee..3d1cb7f68d1e 100644 --- a/java/java-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java @@ -77,7 +77,6 @@ public class JavaPsiFacadeImpl extends JavaPsiFacadeEx implements Disposable { private final ConcurrentMap myPackageCache = new ConcurrentHashMap(); private final Project myProject; private final JavaFileManager myFileManager; - private final ProgressManager myProgressManager; private final PackagePrefixIndex myPackagePrefixIndex; @@ -114,7 +113,6 @@ public class JavaPsiFacadeImpl extends JavaPsiFacadeEx implements Disposable { } myFileManager = new JavaFileManagerImpl(psiManager, projectRootManagerEx, psiManager.getFileManager(), bus); - myProgressManager = ProgressManager.getInstance(); final PsiModificationTrackerImpl modificationTracker = (PsiModificationTrackerImpl) psiManager.getModificationTracker(); psiManager.addTreeChangePreprocessor(new JavaCodeBlockModificationListener(modificationTracker)); @@ -308,13 +306,15 @@ public class JavaPsiFacadeImpl extends JavaPsiFacadeEx implements Disposable { } public PsiClass[] getClasses(PsiPackageImpl psiPackage, GlobalSearchScope scope) { - List result = new ArrayList(); + List result = null; for (PsiElementFinder finder : myElementFinders) { PsiClass[] classes = finder.getClasses(psiPackage, scope); + if (classes.length == 0) continue; + if (result == null) result = new ArrayList(); result.addAll(Arrays.asList(classes)); } - return result.toArray(new PsiClass[result.size()]); + return result == null ? PsiClass.EMPTY_ARRAY : result.toArray(new PsiClass[result.size()]); } public PsiPackage[] getSubPackages(PsiPackageImpl psiPackage, GlobalSearchScope scope) { @@ -414,13 +414,21 @@ public class JavaPsiFacadeImpl extends JavaPsiFacadeEx implements Disposable { @NotNull public PsiClass[] getClasses(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) { - List list = new ArrayList(); + List list = null; final PsiDirectory[] dirs = psiPackage.getDirectories(scope); + String packageName = psiPackage.getQualifiedName(); for (PsiDirectory dir : dirs) { PsiClass[] classes = JavaDirectoryService.getInstance().getClasses(dir); - list.addAll(Arrays.asList(classes)); + if (classes.length == 0) continue; + if (list == null) list = new ArrayList(); + for (PsiClass aClass : classes) { + // class file can be located in wrong place inside file system + if (Comparing.strEqual(((PsiClassOwner)aClass.getContainingFile()).getPackageName(), packageName)) { + list.add(aClass); + } + } } - return list.toArray(new PsiClass[list.size()]); + return list == null ? PsiClass.EMPTY_ARRAY : list.toArray(new PsiClass[list.size()]); } } diff --git a/java/java-impl/src/com/intellij/psi/impl/file/JavaDirectoryServiceImpl.java b/java/java-impl/src/com/intellij/psi/impl/file/JavaDirectoryServiceImpl.java index 129c20e3be7c..9ad79c328ef7 100644 --- a/java/java-impl/src/com/intellij/psi/impl/file/JavaDirectoryServiceImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/file/JavaDirectoryServiceImpl.java @@ -42,6 +42,7 @@ import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import java.util.Properties; public class JavaDirectoryServiceImpl extends JavaDirectoryService { @@ -58,13 +59,16 @@ public class JavaDirectoryServiceImpl extends JavaDirectoryService { public PsiClass[] getClasses(@NotNull PsiDirectory dir) { LOG.assertTrue(dir.isValid()); - ArrayList classes = new ArrayList(); + List classes = null; for (PsiFile file : dir.getFiles()) { if (file instanceof PsiClassOwner) { - classes.addAll(Arrays.asList(((PsiClassOwner)file).getClasses())); + PsiClass[] psiClasses = ((PsiClassOwner)file).getClasses(); + if (psiClasses.length == 0) continue; + if (classes == null) classes = new ArrayList(); + classes.addAll(Arrays.asList(psiClasses)); } } - return classes.toArray(new PsiClass[classes.size()]); + return classes == null ? PsiClass.EMPTY_ARRAY : classes.toArray(new PsiClass[classes.size()]); } @NotNull diff --git a/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImpl.java b/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImpl.java index 98d9004078d4..a94be32fc589 100644 --- a/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImpl.java @@ -116,14 +116,15 @@ public class PsiPackageImpl extends PsiElementBase implements PsiPackage { @NotNull public PsiDirectory[] getDirectories(@NotNull GlobalSearchScope scope) { - final List result = new ArrayList(); + List result = null; final Collection directories = getAllDirectories(); for (final PsiDirectory directory : directories) { if (scope.contains(directory.getVirtualFile())) { + if (result == null) result = new ArrayList(); result.add(directory); } } - return result.toArray(new PsiDirectory[result.size()]); + return result == null ? PsiDirectory.EMPTY_ARRAY : result.toArray(new PsiDirectory[result.size()]); } public RowIcon getElementIcon(final int elementFlags) { diff --git a/java/java-impl/src/com/intellij/psi/impl/source/resolve/ClassCollectingProcessor.java b/java/java-impl/src/com/intellij/psi/impl/source/resolve/ClassCollectingProcessor.java index 9d0c5428efa0..9ecf483f36fe 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/resolve/ClassCollectingProcessor.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/resolve/ClassCollectingProcessor.java @@ -48,7 +48,7 @@ public class ClassCollectingProcessor extends BaseScopeProcessor implements Elem public boolean execute(PsiElement element, ResolveState state) { if (element instanceof PsiNamedElement) { - PsiNamedElement named = ((PsiNamedElement)element); + PsiNamedElement named = (PsiNamedElement)element; String name = named.getName(); if (name != null) { myResult.add(name, new ResultWithContext(named, myCurrentFileContext)); From a145915abe22b8eda9530934f15d8c8f6119a6a3 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Tue, 16 Feb 2010 10:44:51 +0300 Subject: [PATCH 12/93] cleanup --- .../requests/MethodReturnValueWatcher.java | 3 +- .../ui/breakpoints/BreakpointTree.java | 44 ++++++++++--------- .../LibrariesConfigurationManager.java | 2 +- .../impl/source/resolve/JavaResolveCache.java | 2 +- .../tree/java/PsiBinaryExpressionImpl.java | 26 ++++++++--- .../codeInsight/CodeInsightSettings.java | 9 ++-- .../history/deprecated/DeprecatedLVCS.java | 3 +- .../ide/util/treeView/AbstractTreeUi.java | 2 +- .../fileTypes/MockFileTypeManager.java | 3 +- .../ide/actions/ShowFilePathAction.java | 3 +- .../impl/stores/StateStorageManagerImpl.java | 3 +- .../openapi/vfs/impl/win32/Win32Kernel.java | 4 +- .../openapi/wm/impl/WindowManagerImpl.java | 5 ++- .../src/com/intellij/TestAll.java | 5 ++- .../intellij/mock/MockLocalFileSystem.java | 2 +- .../openapi/util/JDOMExternalizer.java | 3 +- .../netbeans/lib/cvsclient/command/Watch.java | 3 +- .../src/git4idea/changes/GitChangeUtils.java | 3 +- .../org/jetbrains/git4idea/ssh/SSHMain.java | 3 +- .../annotator/intentions/QuickfixUtil.java | 2 +- .../elements/GrEnumConstantElementType.java | 5 ++- .../stubs/elements/GrFieldElementType.java | 3 +- .../extractMethod/ExtractMethodUtil.java | 5 ++- .../inline/GroovyMethodInliner.java | 5 ++- .../execution/EditMavenPropertyDialog.java | 3 +- ...ideImplementsTestNGAnnotationsHandler.java | 3 +- .../properties/IntroListModelProperty.java | 3 +- .../radComponents/LayoutManagerRegistry.java | 2 +- .../source/xml/SchemaPrefixReference.java | 3 +- 29 files changed, 99 insertions(+), 63 deletions(-) diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/requests/MethodReturnValueWatcher.java b/java/debugger/impl/src/com/intellij/debugger/engine/requests/MethodReturnValueWatcher.java index 561ab0c2a240..16fc43ce1639 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/requests/MethodReturnValueWatcher.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/requests/MethodReturnValueWatcher.java @@ -17,6 +17,7 @@ package com.intellij.debugger.engine.requests; import com.intellij.debugger.settings.DebuggerSettings; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.util.ArrayUtil; import com.sun.jdi.Method; import com.sun.jdi.ObjectCollectedException; import com.sun.jdi.Value; @@ -56,7 +57,7 @@ public class MethodReturnValueWatcher { try { if (myReturnValueMethod == null) { //noinspection HardCodedStringLiteral - myReturnValueMethod = MethodExitEvent.class.getDeclaredMethod("returnValue", new Class[0]); + myReturnValueMethod = MethodExitEvent.class.getDeclaredMethod("returnValue", ArrayUtil.EMPTY_CLASS_ARRAY); } myLastMethodReturnValue = (Value)myReturnValueMethod.invoke(event); } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTree.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTree.java index 9de989d1eeb6..afa09b72b124 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTree.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTree.java @@ -18,6 +18,7 @@ import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.DebuggerManagerEx; import com.intellij.openapi.project.Project; import com.intellij.ui.*; +import com.intellij.util.ArrayUtil; import com.intellij.util.Icons; import com.intellij.util.containers.Convertor; import com.intellij.util.ui.tree.TreeUtil; @@ -42,7 +43,7 @@ public class BreakpointTree extends CheckboxTree { private boolean myGroupByClasses = true; private boolean myFlattenPackages = true; - private final NodeAppender[] myAppenders = new NodeAppender[] { + private final NodeAppender[] myAppenders = { new BreakpointToMethodAppender(), new BreakpointToClassAppender(), new BreakpointToPackageAppender(), @@ -186,12 +187,13 @@ public class BreakpointTree extends CheckboxTree { public BreakpointDescriptor(Breakpoint breakpoint) { myBreakpoint = breakpoint; } - public @NotNull Breakpoint getBreakpoint() { + @NotNull + public Breakpoint getBreakpoint() { return myBreakpoint; } protected Icon getDisplayIcon() { - return (myBreakpoint instanceof BreakpointWithHighlighter)? + return myBreakpoint instanceof BreakpointWithHighlighter ? myBreakpoint.ENABLED? ((BreakpointWithHighlighter)myBreakpoint).getSetIcon() : ((BreakpointWithHighlighter)myBreakpoint).getDisabledIcon() : myBreakpoint.getIcon(); } @@ -224,7 +226,7 @@ public class BreakpointTree extends CheckboxTree { private static final class MethodDescriptor extends TreeDescriptor { private final String myClassName; private final String myMethodName; - private final @NotNull String myPackageName; + @NotNull private final String myPackageName; public MethodDescriptor(String methodName, String className, @NotNull String packageName) { myClassName = className; @@ -232,7 +234,8 @@ public class BreakpointTree extends CheckboxTree { myPackageName = packageName; } - public @NotNull String getPackageName() { + @NotNull + public String getPackageName() { return myPackageName; } @@ -267,26 +270,27 @@ public class BreakpointTree extends CheckboxTree { } public int hashCode() { - int result; - result = myClassName.hashCode(); + int result = myClassName.hashCode(); result = 29 * result + myMethodName.hashCode(); return result; } } private static final class ClassDescriptor extends TreeDescriptor { - private final @NotNull String myClassName; - private final @NotNull String myPackageName; + @NotNull private final String myClassName; + @NotNull private final String myPackageName; public ClassDescriptor(@NotNull String className, @NotNull String packageName) { myClassName = className; myPackageName = packageName.length() == 0? DEFAULT_PACKAGE_NAME : packageName; } + @NotNull public String getPackageName() { return myPackageName; } + @NotNull public String getClassName() { return myClassName; } @@ -383,7 +387,7 @@ public class BreakpointTree extends CheckboxTree { myBreakpointManager = DebuggerManagerEx.getInstanceEx(project).getBreakpointManager(); myNodeUpdateListener = new BreakpointManagerListener() { public void breakpointsChanged() { - BreakpointTree.this.repaint(); + repaint(); } }; myBreakpointManager.addBreakpointManagerListener(myNodeUpdateListener); @@ -554,7 +558,8 @@ public class BreakpointTree extends CheckboxTree { } } - private @NotNull CheckedTreeNode createNode(final TreeDescriptor descriptor) { + @NotNull + private CheckedTreeNode createNode(final TreeDescriptor descriptor) { final CheckedTreeNode node = new CheckedTreeNode(descriptor); myDescriptorToNodeMap.put(descriptor, node); return node; @@ -615,7 +620,7 @@ public class BreakpointTree extends CheckboxTree { } } - private static abstract class NodeAppender { + private abstract static class NodeAppender { public abstract CheckedTreeNode append(CheckedTreeNode node); } @@ -676,10 +681,10 @@ public class BreakpointTree extends CheckboxTree { final Breakpoint breakpoint = ((BreakpointDescriptor)descriptor).getBreakpoint(); final String packageName; if (breakpoint instanceof ExceptionBreakpoint) { - packageName = ((ExceptionBreakpoint)breakpoint).getPackageName(); + packageName = breakpoint.getPackageName(); } else if (breakpoint instanceof BreakpointWithHighlighter) { - packageName = ((BreakpointWithHighlighter)breakpoint).getPackageName(); + packageName = breakpoint.getPackageName(); } else { packageName = null; @@ -768,7 +773,6 @@ public class BreakpointTree extends CheckboxTree { private static class TreeStateSnapshot { private final Object[] myExpandedUserObjects; private final Object[] mySelectedUserObjects; - private static final Object[][] EMPTY = new Object[0][]; public TreeStateSnapshot(BreakpointTree tree) { final List expandedPaths = TreeUtil.collectExpandedPaths(tree); @@ -776,9 +780,9 @@ public class BreakpointTree extends CheckboxTree { mySelectedUserObjects =getUserObjects(tree.getSelectionPaths()); } - private Object[] getUserObjects(final TreePath[] treePaths) { + private static Object[] getUserObjects(final TreePath[] treePaths) { if (treePaths == null) { - return EMPTY; + return ArrayUtil.EMPTY_OBJECT_ARRAY; } Object[] userObjects = new Object[treePaths.length]; int index = 0; @@ -790,18 +794,18 @@ public class BreakpointTree extends CheckboxTree { public void restore(BreakpointTree tree) { final List pathsToExpand = getPaths(tree, myExpandedUserObjects); - if (pathsToExpand.size() > 0) { + if (!pathsToExpand.isEmpty()) { TreeUtil.restoreExpandedPaths(tree, pathsToExpand); } final List pathsToSelect = getPaths(tree, mySelectedUserObjects); - if (pathsToSelect.size() > 0) { + if (!pathsToSelect.isEmpty()) { tree.getSelectionModel().clearSelection(); tree.setSelectionPaths(pathsToSelect.toArray(new TreePath[pathsToSelect.size()])); } } - private List getPaths(BreakpointTree tree, final Object[] userObjects) { + private static List getPaths(BreakpointTree tree, final Object[] userObjects) { final List paths = new ArrayList(userObjects.length); for (Object descriptor : userObjects) { final CheckedTreeNode node = tree.myDescriptorToNodeMap.get(descriptor); diff --git a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/versions/LibrariesConfigurationManager.java b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/versions/LibrariesConfigurationManager.java index 633c4201b7d2..babd5cfb94ab 100644 --- a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/versions/LibrariesConfigurationManager.java +++ b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/versions/LibrariesConfigurationManager.java @@ -112,7 +112,7 @@ public class LibrariesConfigurationManager implements Disposable { } private static String[] getSplitted(@Nullable final String s) { - if (StringUtil.isEmptyOrSpaces(s)) return new String[0]; + if (StringUtil.isEmptyOrSpaces(s)) return ArrayUtil.EMPTY_STRING_ARRAY; return ArrayUtil.toStringArray(StringUtil.split(s, STRING_DELIMITER)); } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/resolve/JavaResolveCache.java b/java/java-impl/src/com/intellij/psi/impl/source/resolve/JavaResolveCache.java index 1a1465cdae91..86a110cef96a 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/resolve/JavaResolveCache.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/resolve/JavaResolveCache.java @@ -56,7 +56,7 @@ public class JavaResolveCache { private final Map myVarToConstValueMap2; private static final Object NULL = Key.create("NULL"); - private static final PsiType NULL_TYPE = new PsiEllipsisType(PsiType.NULL){ + public static final PsiType NULL_TYPE = new PsiEllipsisType(PsiType.NULL){ public boolean isValid() { return true; } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiBinaryExpressionImpl.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiBinaryExpressionImpl.java index 47aa5a836ccc..5576c1811d36 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiBinaryExpressionImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiBinaryExpressionImpl.java @@ -61,6 +61,11 @@ public class PsiBinaryExpressionImpl extends ExpressionPsiElement implements Psi PsiExpression lOperand = param.getLOperand(); PsiExpression rOperand = param.getROperand(); if (rOperand == null) return null; + PsiType rType = rOperand.getType(); + IElementType sign = param.getOperationSign().getNode().getElementType(); + // optimization: if we can calculate type based on right type only + PsiType type = calcTypeForBinaryExpression(null, rType, sign, false); + if (type != JavaResolveCache.NULL_TYPE) return type; if (lOperand instanceof PsiBinaryExpressionImpl && !JavaResolveCache.getInstance(param.getProject()).isTypeCached(lOperand)) { // cache all intermediate expression types from bottom up @@ -80,9 +85,8 @@ public class PsiBinaryExpressionImpl extends ExpressionPsiElement implements Psi } }); } - PsiType rType = rOperand.getType(); PsiType lType = lOperand.getType(); - return calcTypeForBinaryExpression(lType, rType, param.getOperationSign().getNode().getElementType()); + return calcTypeForBinaryExpression(lType, rType, sign, true); } private static final Function MY_TYPE_EVALUATOR = new Function() { @@ -144,13 +148,14 @@ public class PsiBinaryExpressionImpl extends ExpressionPsiElement implements Psi } @Nullable - public static PsiType calcTypeForBinaryExpression(PsiType lType, PsiType rType, IElementType sign) { + public static PsiType calcTypeForBinaryExpression(PsiType lType, PsiType rType, IElementType sign, boolean accessLType) { if (sign == JavaTokenType.PLUS) { // evaluate right argument first, since '+-/*%' is left associative and left operand tends to be bigger if (rType == null) return null; if (rType.equalsToText("java.lang.String")) { return rType; } + if (!accessLType) return JavaResolveCache.NULL_TYPE; if (lType == null) return null; if (lType.equalsToText("java.lang.String")) { return lType; @@ -158,10 +163,13 @@ public class PsiBinaryExpressionImpl extends ExpressionPsiElement implements Psi return TypeConversionUtil.unboxAndBalanceTypes(lType, rType); } if (sign == JavaTokenType.MINUS || sign == JavaTokenType.ASTERISK || sign == JavaTokenType.DIV || sign == JavaTokenType.PERC) { - if (lType == null && rType == null) return null; + if (rType == null) return null; + if (!accessLType) return JavaResolveCache.NULL_TYPE; + if (lType == null) return null; return TypeConversionUtil.unboxAndBalanceTypes(lType, rType); } if (sign == JavaTokenType.LTLT || sign == JavaTokenType.GTGT || sign == JavaTokenType.GTGTGT) { + if (!accessLType) return JavaResolveCache.NULL_TYPE; if (PsiType.BYTE.equals(lType) || PsiType.CHAR.equals(lType) || PsiType.SHORT.equals(lType)) { return PsiType.INT; } @@ -178,11 +186,15 @@ public class PsiBinaryExpressionImpl extends ExpressionPsiElement implements Psi return PsiType.BOOLEAN; } if (sign == JavaTokenType.OR || sign == JavaTokenType.XOR || sign == JavaTokenType.AND) { - if (lType instanceof PsiClassType) lType = PsiPrimitiveType.getUnboxedType(lType); if (rType instanceof PsiClassType) rType = PsiPrimitiveType.getUnboxedType(rType); - if (lType == null && rType == null) return null; - if (PsiType.BOOLEAN.equals(lType) || PsiType.BOOLEAN.equals(rType)) return PsiType.BOOLEAN; + if (lType instanceof PsiClassType) lType = PsiPrimitiveType.getUnboxedType(lType); + + if (rType == null) return null; + if (PsiType.BOOLEAN.equals(rType)) return PsiType.BOOLEAN; + if (!accessLType) return JavaResolveCache.NULL_TYPE; + if (lType == null) return null; + if (PsiType.BOOLEAN.equals(lType)) return PsiType.BOOLEAN; if (PsiType.LONG.equals(lType) || PsiType.LONG.equals(rType)) return PsiType.LONG; return PsiType.INT; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/CodeInsightSettings.java b/platform/lang-impl/src/com/intellij/codeInsight/CodeInsightSettings.java index 1debf36b3241..cc8f0c81fab0 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/CodeInsightSettings.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/CodeInsightSettings.java @@ -22,6 +22,7 @@ import com.intellij.openapi.util.DefaultJDOMExternalizer; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.util.ArrayUtil; import com.intellij.util.xmlb.annotations.AbstractCollection; import com.intellij.util.xmlb.annotations.Property; import org.jdom.Element; @@ -127,13 +128,11 @@ public class CodeInsightSettings implements PersistentStateComponent, C public boolean OPTIMIZE_IMPORTS_ON_THE_FLY = false; public boolean ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = false; - @Property(surroundWithTag = false) - @AbstractCollection( + @Property(surroundWithTag = false) @AbstractCollection( surroundWithTag = false, elementTag = "EXCLUDED_PACKAGE", - elementValueAttribute = "NAME" - ) - public String[] EXCLUDED_PACKAGES = new String[0]; + elementValueAttribute = "NAME") + public String[] EXCLUDED_PACKAGES = ArrayUtil.EMPTY_STRING_ARRAY; public void loadState(final Element state) { try { diff --git a/platform/lvcs-impl/src/com/intellij/history/deprecated/DeprecatedLVCS.java b/platform/lvcs-impl/src/com/intellij/history/deprecated/DeprecatedLVCS.java index f92595b2c567..19a2ccbab3ef 100644 --- a/platform/lvcs-impl/src/com/intellij/history/deprecated/DeprecatedLVCS.java +++ b/platform/lvcs-impl/src/com/intellij/history/deprecated/DeprecatedLVCS.java @@ -23,6 +23,7 @@ import com.intellij.history.LocalHistory; import com.intellij.history.LocalHistoryAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -62,7 +63,7 @@ public class DeprecatedLVCS extends LocalVcs implements ProjectComponent { } public String[] getRootPaths() { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } @Nullable diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java index c5fc44a8afd1..928d187f6e1c 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java @@ -3791,7 +3791,7 @@ public class AbstractTreeUi { private Map myChanges = new HashMap(); LoadedChildren(Object[] elements) { - myElements = Arrays.asList(elements != null ? elements : new Object[0]); + myElements = Arrays.asList(elements != null ? elements : ArrayUtil.EMPTY_OBJECT_ARRAY); } void putDescriptor(Object element, NodeDescriptor descriptor, boolean isChanged) { diff --git a/platform/platform-api/src/com/intellij/openapi/fileTypes/MockFileTypeManager.java b/platform/platform-api/src/com/intellij/openapi/fileTypes/MockFileTypeManager.java index 080b51c8fd5e..5605c68d3d0f 100644 --- a/platform/platform-api/src/com/intellij/openapi/fileTypes/MockFileTypeManager.java +++ b/platform/platform-api/src/com/intellij/openapi/fileTypes/MockFileTypeManager.java @@ -20,6 +20,7 @@ package com.intellij.openapi.fileTypes; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -64,7 +65,7 @@ class MockFileTypeManager extends FileTypeManager { @NotNull @Override public String[] getAssociatedExtensions(@NotNull FileType type) { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } @NotNull diff --git a/platform/platform-impl/src/com/intellij/ide/actions/ShowFilePathAction.java b/platform/platform-impl/src/com/intellij/ide/actions/ShowFilePathAction.java index a29a74d0d65f..6f030082eeb8 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/ShowFilePathAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/ShowFilePathAction.java @@ -32,6 +32,7 @@ import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.awt.RelativePoint; +import com.intellij.util.ArrayUtil; import com.intellij.util.ui.EmptyIcon; import org.jetbrains.annotations.NotNull; @@ -174,7 +175,7 @@ public class ShowFilePathAction extends AnAction { try { File parent = ioFile.getParentFile(); if (parent != null) { - Runtime.getRuntime().exec(cmd + " " + path, new String[0], parent); + Runtime.getRuntime().exec(cmd + " " + path, ArrayUtil.EMPTY_STRING_ARRAY, parent); } else { Runtime.getRuntime().exec(cmd + " " + path); } diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java index 30f4261ec00a..cfda7c873e1b 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java @@ -27,6 +27,7 @@ import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.util.ArrayUtil; import com.intellij.util.containers.MultiMap; import com.intellij.util.io.fs.IFile; import org.jdom.Document; @@ -363,7 +364,7 @@ public abstract class StateStorageManagerImpl implements StateStorageManager, Di } public String[] listSubFiles(final String fileSpec) { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } public boolean isEnabled() { diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java index 7b79cd58ffe3..5fce05c6b919 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java @@ -15,6 +15,8 @@ */ package com.intellij.openapi.vfs.impl.win32; +import com.intellij.util.ArrayUtil; + import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashMap; @@ -40,7 +42,7 @@ public class Win32Kernel { FileInfo[] fileInfos = myKernel.listChildren(absolutePath.replace('/', '\\') + "\\*.*"); if (fileInfos == null) { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } ArrayList names = new ArrayList(fileInfos.length); for (int i = 0, fileInfosLength = fileInfos.length; i < fileInfosLength; i++) { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java index c5f0c2ad7402..85acb08387d0 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java @@ -37,6 +37,7 @@ import com.intellij.openapi.wm.WindowManagerListener; import com.intellij.openapi.wm.ex.StatusBarEx; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.util.Alarm; +import com.intellij.util.ArrayUtil; import com.intellij.util.EventDispatcher; import com.intellij.util.ui.UIUtil; import com.sun.jna.examples.WindowUtils; @@ -446,8 +447,8 @@ public final class WindowManagerImpl extends WindowManagerEx implements Applicat frame.setProject(project); } else { - frame = new IdeFrameImpl((ApplicationInfoEx)ApplicationInfo.getInstance(), ActionManager.getInstance(), UISettings.getInstance(), DataManager.getInstance(), - KeymapManager.getInstance(), ApplicationManager.getApplication(), new String[0]); + frame = new IdeFrameImpl((ApplicationInfoEx)ApplicationInfo.getInstance(), ActionManager.getInstance(), UISettings.getInstance(), + DataManager.getInstance(), KeymapManager.getInstance(), ApplicationManager.getApplication(), ArrayUtil.EMPTY_STRING_ARRAY); if (myFrameBounds != null) { frame.setBounds(myFrameBounds); } diff --git a/platform/testFramework/src/com/intellij/TestAll.java b/platform/testFramework/src/com/intellij/TestAll.java index 400b30f5c7e6..9ebb97e8d49f 100644 --- a/platform/testFramework/src/com/intellij/TestAll.java +++ b/platform/testFramework/src/com/intellij/TestAll.java @@ -31,6 +31,7 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl; import com.intellij.testFramework.*; +import com.intellij.util.ArrayUtil; import junit.framework.*; import java.io.File; @@ -296,8 +297,8 @@ public class TestAll implements Test { if ((testCaseClass.getModifiers() & Modifier.PUBLIC) == 0) return null; try { - Method suiteMethod = testCaseClass.getMethod("suite", new Class[0]); - return (Test)suiteMethod.invoke(null, new Class[0]); + Method suiteMethod = testCaseClass.getMethod("suite", ArrayUtil.EMPTY_CLASS_ARRAY); + return (Test)suiteMethod.invoke(null, ArrayUtil.EMPTY_CLASS_ARRAY); } catch (NoSuchMethodException e) { if (TestRunnerUtil.isJUnit4TestClass(testCaseClass)) { diff --git a/platform/testFramework/src/com/intellij/mock/MockLocalFileSystem.java b/platform/testFramework/src/com/intellij/mock/MockLocalFileSystem.java index 2e47322919f8..38917d86fd50 100644 --- a/platform/testFramework/src/com/intellij/mock/MockLocalFileSystem.java +++ b/platform/testFramework/src/com/intellij/mock/MockLocalFileSystem.java @@ -185,7 +185,7 @@ public class MockLocalFileSystem extends LocalFileSystem { } public String[] list(final VirtualFile file) { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } public VirtualFile[] listFiles(final VirtualFile file) { diff --git a/platform/util/src/com/intellij/openapi/util/JDOMExternalizer.java b/platform/util/src/com/intellij/openapi/util/JDOMExternalizer.java index d6ebe99e9253..4b23c3a6f12a 100644 --- a/platform/util/src/com/intellij/openapi/util/JDOMExternalizer.java +++ b/platform/util/src/com/intellij/openapi/util/JDOMExternalizer.java @@ -16,6 +16,7 @@ package com.intellij.openapi.util; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.util.ArrayUtil; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; @@ -73,7 +74,7 @@ public class JDOMExternalizer { else { mapRoot = root; } - final String[] names = map.keySet().toArray(new String[0]); + final String[] names = map.keySet().toArray(ArrayUtil.EMPTY_STRING_ARRAY); Arrays.sort(names); for (String name : names) { @NonNls final Element element = new Element(entryName); diff --git a/plugins/cvs/javacvs-src/org/netbeans/lib/cvsclient/command/Watch.java b/plugins/cvs/javacvs-src/org/netbeans/lib/cvsclient/command/Watch.java index 1a8a9b95a971..7b00d9db35a7 100644 --- a/plugins/cvs/javacvs-src/org/netbeans/lib/cvsclient/command/Watch.java +++ b/plugins/cvs/javacvs-src/org/netbeans/lib/cvsclient/command/Watch.java @@ -12,6 +12,7 @@ */ package org.netbeans.lib.cvsclient.command; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.netbeans.lib.cvsclient.JavaCvsSrcBundle; @@ -39,7 +40,7 @@ public final class Watch { new String[]{"tedit", "tunedit", "tcommit"}); // NOI18N public static final Watch NONE = new Watch(JavaCvsSrcBundle.message("watch.name.none"), "", // NOI18N - new String[0]); + ArrayUtil.EMPTY_STRING_ARRAY); // Static ================================================================= diff --git a/plugins/git4idea/src/git4idea/changes/GitChangeUtils.java b/plugins/git4idea/src/git4idea/changes/GitChangeUtils.java index 58cf81abe202..318c34e7f81d 100644 --- a/plugins/git4idea/src/git4idea/changes/GitChangeUtils.java +++ b/plugins/git4idea/src/git4idea/changes/GitChangeUtils.java @@ -25,6 +25,7 @@ import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList; import com.intellij.openapi.vcs.versionBrowser.CommittedChangeListImpl; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.util.ArrayUtil; import git4idea.GitContentRevision; import git4idea.GitRevisionNumber; import git4idea.GitUtil; @@ -293,7 +294,7 @@ public class GitChangeUtils { final Date commitDate = GitUtil.parseTimestamp(s.line()); final String revisionNumber = s.line(); final String parentsLine = s.line(); - final String[] parents = parentsLine.length() == 0 ? new String[0] : parentsLine.split(" "); + final String[] parents = parentsLine.length() == 0 ? ArrayUtil.EMPTY_STRING_ARRAY : parentsLine.split(" "); String authorName = s.line(); String committerName = s.line(); committerName = GitUtil.adjustAuthorName(authorName, committerName); diff --git a/plugins/git4idea/src/org/jetbrains/git4idea/ssh/SSHMain.java b/plugins/git4idea/src/org/jetbrains/git4idea/ssh/SSHMain.java index e4c948ae2cd1..991226263ce0 100644 --- a/plugins/git4idea/src/org/jetbrains/git4idea/ssh/SSHMain.java +++ b/plugins/git4idea/src/org/jetbrains/git4idea/ssh/SSHMain.java @@ -16,6 +16,7 @@ package org.jetbrains.git4idea.ssh; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.util.ArrayUtil; import com.trilead.ssh2.*; import com.trilead.ssh2.crypto.PEMDecoder; import git4idea.i18n.GitBundle; @@ -501,7 +502,7 @@ public class SSHMain { final String[] prompt, final boolean[] echo) throws Exception { if (numPrompts == 0) { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } myPromptCount++; Vector vPrompts = new Vector(prompt.length); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/QuickfixUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/QuickfixUtil.java index cc819fbe7266..22f927512eaa 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/QuickfixUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/QuickfixUtil.java @@ -156,7 +156,7 @@ public class QuickfixUtil { public static String[] getArgumentsTypes(List listOfPairs) { final List result = new ArrayList(); - if (listOfPairs == null) return new String[0]; + if (listOfPairs == null) return ArrayUtil.EMPTY_STRING_ARRAY; for (MyPair listOfPair : listOfPairs) { String type = PsiTypesUtil.unboxIfPossible(listOfPair.second); result.add(type); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrEnumConstantElementType.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrEnumConstantElementType.java index 105944040d49..3b2de1cb7e9f 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrEnumConstantElementType.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrEnumConstantElementType.java @@ -21,6 +21,7 @@ import com.intellij.psi.stubs.IndexSink; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; +import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.StringRef; @@ -59,7 +60,7 @@ public class GrEnumConstantElementType extends GrStubElementType() { @@ -68,7 +69,7 @@ public class GrEnumConstantElementType extends GrStubElementType final GrModifierList modifiers = psi.getModifierList(); String[] annNames; if (modifiers == null) { - annNames = new String[0]; + annNames = ArrayUtil.EMPTY_STRING_ARRAY; } else { final GrAnnotation[] annotations = modifiers.getAnnotations(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extractMethod/ExtractMethodUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extractMethod/ExtractMethodUtil.java index 84b041283049..57d6423fb6ac 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extractMethod/ExtractMethodUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extractMethod/ExtractMethodUtil.java @@ -101,7 +101,8 @@ public class ExtractMethodUtil { if (helper.isReturnStatement()) { return factory.createStatementFromText("return " + callExpression.getText()); } else if (name != null && mustAddVariableDeclaration(statements, name)) { - return factory.createVariableDeclaration(new String[0], callExpression, type.equalsToText("java.lang.Object") ? null : type, name); + return factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, callExpression, + type.equalsToText("java.lang.Object") ? null : type, name); } else { return factory.createExpressionFromText(name + "= " + callExpression.getText()); } @@ -239,7 +240,7 @@ public class ExtractMethodUtil { if (type != PsiType.VOID && outputName != null && !outputIsParameter && !mustAddVariableDeclaration(helper.getStatements(), outputName) && !containVariableDeclaration(helper.getStatements(), outputName)) { - GrVariableDeclaration decl = factory.createVariableDeclaration(new String[0], null, type, outputName); + GrVariableDeclaration decl = factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, null, type, outputName); buffer.append(decl.getText()).append("\n"); } if (!ExtractMethodUtil.isSingleExpression(helper.getStatements())) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyMethodInliner.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyMethodInliner.java index a7e9f19f5cda..21a3ca5ddc3e 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyMethodInliner.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyMethodInliner.java @@ -34,6 +34,7 @@ import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.usageView.UsageInfo; +import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; @@ -145,7 +146,7 @@ public class GroovyMethodInliner implements InlineHandler.Inliner { while (qualifier instanceof GrParenthesizedExpression) { qualifier = ((GrParenthesizedExpression) qualifier).getOperand(); } - qualifierDeclaration = factory.createVariableDeclaration(new String[0], qualifier, null, qualName); + qualifierDeclaration = factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, qualifier, null, qualName); innerQualifier = ((GrReferenceExpression) factory.createExpressionFromText(qualName)); } else { innerQualifier = ((GrReferenceExpression) qualifier); @@ -212,7 +213,7 @@ public class GroovyMethodInliner implements InlineHandler.Inliner { // Process method return statements if (returnCount > 1 && PsiType.VOID != methodType && !isTailMethodCall) { PsiType type = methodType != null && methodType.equalsToText("java.lang.Object") ? null : methodType; - GrVariableDeclaration resultDecl = factory.createVariableDeclaration(new String[0], null, type, resultName); + GrVariableDeclaration resultDecl = factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, null, type, resultName); GrStatement statement = ((GrStatementOwner) owner).addStatementBefore(resultDecl, anchor); PsiUtil.shortenReferences(statement); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java index e78eebd59fc4..09a96bd0c2a6 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java @@ -18,6 +18,7 @@ package org.jetbrains.idea.maven.execution; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Pair; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; @@ -75,7 +76,7 @@ public class EditMavenPropertyDialog extends DialogWrapper { } private void fillAvailableProperties() { - String[] keys = myAvailableProperties.keySet().toArray(new String[0]); + String[] keys = myAvailableProperties.keySet().toArray(ArrayUtil.EMPTY_STRING_ARRAY); myNameBox.setModel(new DefaultComboBoxModel(keys)); } diff --git a/plugins/testng/src/com/theoryinpractice/testng/intention/OverrideImplementsTestNGAnnotationsHandler.java b/plugins/testng/src/com/theoryinpractice/testng/intention/OverrideImplementsTestNGAnnotationsHandler.java index f8895c2b4de7..1897355ec8b5 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/intention/OverrideImplementsTestNGAnnotationsHandler.java +++ b/plugins/testng/src/com/theoryinpractice/testng/intention/OverrideImplementsTestNGAnnotationsHandler.java @@ -21,6 +21,7 @@ package com.theoryinpractice.testng.intention; import com.intellij.codeInsight.generation.OverrideImplementsAnnotationsHandler; +import com.intellij.util.ArrayUtil; import com.theoryinpractice.testng.util.TestNGUtil; import org.jetbrains.annotations.NotNull; @@ -32,6 +33,6 @@ public class OverrideImplementsTestNGAnnotationsHandler implements OverrideImple @NotNull public String[] annotationsToRemove(@NotNull final String fqName) { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } } \ No newline at end of file diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/IntroListModelProperty.java b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/IntroListModelProperty.java index aba673924fbb..a6b75dd86ae0 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/IntroListModelProperty.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/IntroListModelProperty.java @@ -25,6 +25,7 @@ import com.intellij.uiDesigner.propertyInspector.editors.ListModelEditor; import com.intellij.uiDesigner.propertyInspector.renderers.LabelPropertyRenderer; import com.intellij.uiDesigner.radComponents.RadComponent; import com.intellij.uiDesigner.snapShooter.SnapshotContext; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -69,7 +70,7 @@ public class IntroListModelProperty extends IntrospectedProperty { @Override public String[] getValue(final RadComponent component) { final String[] strings = (String[])component.getDelegee().getClientProperty(CLIENT_PROPERTY_KEY_PREFIX + getName()); if (strings == null) { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } return strings; } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/LayoutManagerRegistry.java b/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/LayoutManagerRegistry.java index 0071a2b87a39..b4d381532115 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/LayoutManagerRegistry.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/LayoutManagerRegistry.java @@ -61,7 +61,7 @@ public class LayoutManagerRegistry { } public static String[] getLayoutManagerNames() { - final String[] layoutManagerNames = ourLayoutManagerRegistry.keySet().toArray(new String[0]); + final String[] layoutManagerNames = ourLayoutManagerRegistry.keySet().toArray(ArrayUtil.EMPTY_STRING_ARRAY); Arrays.sort(layoutManagerNames); return layoutManagerNames; } diff --git a/xml/impl/src/com/intellij/psi/impl/source/xml/SchemaPrefixReference.java b/xml/impl/src/com/intellij/psi/impl/source/xml/SchemaPrefixReference.java index f95cc263521c..9bcbb28a7df4 100644 --- a/xml/impl/src/com/intellij/psi/impl/source/xml/SchemaPrefixReference.java +++ b/xml/impl/src/com/intellij/psi/impl/source/xml/SchemaPrefixReference.java @@ -21,6 +21,7 @@ import com.intellij.psi.PsiReferenceBase; import com.intellij.psi.xml.XmlAttribute; import com.intellij.psi.xml.XmlElement; import com.intellij.psi.xml.XmlTag; +import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.xml.util.XmlUtil; import org.jetbrains.annotations.NotNull; @@ -58,7 +59,7 @@ public class SchemaPrefixReference extends PsiReferenceBase { @NotNull public Object[] getVariants() { - return new Object[0]; + return ArrayUtil.EMPTY_OBJECT_ARRAY; } @Override From b32acd226a9d8fee5679a694a96bc31fc88aa44b Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Tue, 16 Feb 2010 14:36:19 +0300 Subject: [PATCH 13/93] cleanup --- .../HighlightSuppressedWarningsHandler.java | 2 +- .../daemon/impl/LocalInspectionsPass.java | 4 ++-- .../ex/GlobalInspectionContextImpl.java | 19 +++++++++---------- 3 files changed, 12 insertions(+), 13 deletions(-) diff --git a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java index 19aa7cc0fd60..c7211eb840e5 100644 --- a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java @@ -117,7 +117,7 @@ public class HighlightSuppressedWarningsHandler extends HighlightUsagesHandlerBa final GlobalInspectionContextImpl context = managerEx.createNewGlobalContext(false); tool.initialize(context); ((RefManagerImpl)context.getRefManager()).inspectionReadActionStarted(); - pass.doInspectInBatch(managerEx, new InspectionProfileEntry[]{tool}, false); + pass.doInspectInBatch(managerEx, Collections.singletonList(tool), false); for (HighlightInfo info : pass.getInfos()) { final PsiElement element = CollectHighlightsUtil.findCommonParent(myFile, info.startOffset, info.endOffset); if (element != null) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java index c74efd2d06b1..f789c6ce3407 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java @@ -118,12 +118,12 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass inspect(tools, iManager, true, true); } - public void doInspectInBatch(final InspectionManagerEx iManager, InspectionProfileEntry[] toolWrappers, boolean ignoreSuppressed) { + public void doInspectInBatch(final InspectionManagerEx iManager, List toolWrappers, boolean ignoreSuppressed) { myDescriptors = new ArrayList(); myLevels = new ArrayList(); myTools = new ArrayList(); - Map tool2Wrapper = new THashMap(toolWrappers.length); + Map tool2Wrapper = new THashMap(toolWrappers.size()); for (InspectionProfileEntry toolWrapper : toolWrappers) { tool2Wrapper.put(((LocalInspectionToolWrapper)toolWrapper).getTool(), (LocalInspectionToolWrapper)toolWrapper); } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java index 3e3dd8df1e65..4e3256258f1a 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java @@ -420,7 +420,7 @@ public class GlobalInspectionContextImpl implements GlobalInspectionContext { public void run() { LOG.info("Code inspection finished"); - final InspectionResultsView view = new InspectionResultsView(myProject, getCurrentProfile(), + InspectionResultsView view = new InspectionResultsView(myProject, getCurrentProfile(), scope, GlobalInspectionContextImpl.this, new InspectionRVContentProviderImpl(myProject)); if (!view.update() && !getUIOptions().SHOW_ONLY_DIFF) { @@ -469,11 +469,11 @@ public class GlobalInspectionContextImpl implements GlobalInspectionContext { } private void runTools(final List needRepeatSearchRequest, final AnalysisScope scope, final InspectionManager manager) { - final List usedTools = new ArrayList(); + final List globalTools = new ArrayList(); final List localTools = new ArrayList(); - initializeTools(usedTools, localTools); + initializeTools(globalTools, localTools); ((RefManagerImpl)getRefManager()).initializeAnnotators(); - for (Tools tools : usedTools) { + for (Tools tools : globalTools) { for (ScopeToolState state : tools.getTools()) { final InspectionTool tool = (InspectionTool)state.getTool(); try { @@ -510,14 +510,13 @@ public class GlobalInspectionContextImpl implements GlobalInspectionContext { scope.accept(new PsiRecursiveElementVisitor() { @Override public void visitFile(PsiFile file) { - final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null) { incrementJobDoneAmount(LOCAL_ANALYSIS, ProjectUtil.calcRelativeToProjectPath(virtualFile, myProject)); } final FileViewProvider viewProvider = psiManager.findViewProvider(virtualFile); - final com.intellij.openapi.editor.Document document = viewProvider != null ? viewProvider.getDocument() : null; + final com.intellij.openapi.editor.Document document = viewProvider == null ? null : viewProvider.getDocument(); if (document == null || virtualFile.getFileType().isBinary()) return; //do not inspect binary files final LocalInspectionsPass pass = new LocalInspectionsPass(file, document, 0, file.getTextLength()); try { @@ -528,7 +527,7 @@ public class GlobalInspectionContextImpl implements GlobalInspectionContext { lTools.add(enabledTool); } } - pass.doInspectInBatch((InspectionManagerEx)manager, lTools.toArray(new InspectionProfileEntry[lTools.size()]), true); + pass.doInspectInBatch((InspectionManagerEx)manager, lTools, true); } catch (ProcessCanceledException e) { throw e; @@ -540,7 +539,7 @@ public class GlobalInspectionContextImpl implements GlobalInspectionContext { }); } - public void initializeTools(List tools, List localTools) { + public void initializeTools(List globalTools, List localTools) { myJobDescriptors = new ArrayList(); final InspectionProfileImpl profile = new InspectionProfileImpl((InspectionProfileImpl)getCurrentProfile()); final List usedTools = profile.getAllEnabledInspectionTools(); @@ -553,7 +552,7 @@ public class GlobalInspectionContextImpl implements GlobalInspectionContext { appendJobDescriptor(LOCAL_ANALYSIS); } else { - tools.add(currentTools); + globalTools.add(currentTools); JobDescriptor[] jobDescriptors = tool.getJobDescriptors(); for (JobDescriptor jobDescriptor : jobDescriptors) { appendJobDescriptor(jobDescriptor); @@ -565,7 +564,7 @@ public class GlobalInspectionContextImpl implements GlobalInspectionContext { } } for (GlobalInspectionContextExtension extension : myExtensions.values()) { - extension.performPreRunActivities(tools, localTools, this); + extension.performPreRunActivities(globalTools, localTools, this); } } From df51747db56f6172d302b706c12298fa9b61b302 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Tue, 16 Feb 2010 15:41:19 +0300 Subject: [PATCH 14/93] cleanup --- .../classParsing/MemberInfoExternalizer.java | 8 +++---- .../compiler/classParsing/MethodInfo.java | 2 +- .../impl/OneProjectItemCompileScope.java | 2 +- .../intellij/compiler/make/CacheUtils.java | 2 +- .../intellij/compiler/make/Dependency.java | 2 +- .../make/DependencyCacheNavigator.java | 4 ++-- .../debugger/engine/DebugProcessImpl.java | 2 +- .../intellij/debugger/engine/JVMNameUtil.java | 2 +- .../debugger/engine/PositionManagerImpl.java | 4 ++-- .../debugger/engine/SuspendManagerImpl.java | 2 +- .../expression/CodeFragmentEvaluator.java | 2 +- .../intellij/debugger/impl/InvokeThread.java | 2 +- .../watch/DebuggerTreeNodeExpression.java | 2 +- .../impl/watch/NodeDescriptorFactoryImpl.java | 2 +- .../options/CompileStepBeforeRun.java | 6 ++--- .../configuration/CommonJavaParameters.java | 3 ++- .../ui/configuration/ClasspathPanel.java | 8 +++---- .../configuration/LibraryChooserElement.java | 2 +- .../artifacts/LayoutTreeComponent.java | 3 ++- .../artifacts/nodes/PackagingElementNode.java | 3 ++- .../completion/JavaCompletionContributor.java | 5 ++-- .../CopyPasteReferenceProcessor.java | 3 ++- .../folding/impl/JavaFoldingBuilder.java | 11 ++------- .../JavaImplementationTextSelectioner.java | 2 +- .../codeInsight/lookup/LookupItemUtil.java | 2 +- .../PsiJavaCodeReferenceElementImpl.java | 4 ++-- .../impl/source/parsing/JavadocParsing.java | 2 +- .../source/tree/JavaChangeUtilSupport.java | 2 +- .../tree/java/PsiReferenceExpressionImpl.java | 4 ++-- .../tree/java/ReplaceExpressionUtil.java | 2 +- .../psi/scope/util/PsiScopesUtil.java | 4 ++-- .../refactoring/IntroduceHandlerBase.java | 2 +- .../ChangeSignatureDialog.java | 2 +- .../changeSignature/MethodCallUsageInfo.java | 2 +- .../extractMethod/ControlFlowWrapper.java | 2 +- .../rename/JavaNameSuggestionProvider.java | 2 +- .../PsiNamedElementAutomaticRenamer.java | 9 ++------ .../util/classRefs/ClassInstanceScanner.java | 2 +- .../execution/runners/ProgramRunnerUtil.java | 2 +- .../completion/CodeCompletionHandlerBase.java | 13 ++++------- .../completion/CompletionData.java | 4 ++-- .../folding/impl/DocumentFoldingInfo.java | 2 +- .../intellij/extapi/psi/PsiElementBase.java | 2 +- .../find/actions/ShowUsagesAction.java | 3 ++- .../FavoritesTreeStructure.java | 2 +- .../nodes/ProjectViewDirectoryHelper.java | 2 +- .../openapi/roots/impl/ContentEntryImpl.java | 2 +- .../FormattingDocumentModelImpl.java | 5 ++-- .../psi/impl/file/impl/FileManagerImpl.java | 2 +- .../psi/impl/search/PsiSearchHelperImpl.java | 2 +- .../SmartPointerManagerImpl.java | 2 +- .../codeStyle/CodeStyleManagerImpl.java | 4 ++-- .../impl/providers/FileReferenceSet.java | 2 +- .../psi/impl/source/tree/SharedImplUtil.java | 2 +- .../TemplateDataElementType.java | 4 ++-- .../rename/RenameHandlerRegistry.java | 3 ++- .../rename/naming/AutomaticRenamer.java | 9 ++------ .../rename/naming/NameSuggester.java | 4 ++-- .../execution/process/ProcessHandler.java | 2 +- .../intellij/ide/plugins/PluginManager.java | 2 +- .../ide/util/treeView/TreeBuilderUtil.java | 2 +- .../roots/ui/util/CompositeAppearance.java | 2 +- .../src/com/intellij/ui/ListUtil.java | 2 +- .../com/intellij/ui/table/BaseTableView.java | 5 ++-- .../src/com/intellij/ide/IdeEventQueue.java | 4 ++-- .../intellij/ide/impl/DataManagerImpl.java | 4 ++-- .../com/intellij/ide/impl/DataValidator.java | 4 ++-- .../actionSystem/impl/ActionManagerImpl.java | 4 ++-- .../openapi/actionSystem/impl/Utils.java | 2 +- .../impl/stores/ComponentStoreImpl.java | 2 +- .../diff/impl/incrementalMerge/MergeList.java | 4 ++-- .../impl/processing/PreferWholeLines.java | 3 +-- .../fileEditor/impl/EditorHistoryManager.java | 2 +- .../fileEditor/impl/EditorsSplitters.java | 2 +- .../openapi/project/DumbServiceImpl.java | 2 +- .../openapi/vfs/impl/win32/Win32Kernel.java | 2 +- .../src/com/intellij/ui/EditorComboBox.java | 3 ++- .../intellij/util/PendingEventDispatcher.java | 3 +-- .../sm/runner/TestSuiteStack.java | 7 ++++-- .../ui/statistics/StatisticsTableModel.java | 2 +- .../testFramework/PlatformTestUtil.java | 3 ++- .../usages/UsageInfo2UsageAdapter.java | 3 +-- .../openapi/diff/impl/highlighting/Util.java | 2 +- .../util/src/com/intellij/util/ArrayUtil.java | 23 ++++++++++++------- .../src/com/intellij/util/ReflectionUtil.java | 6 ++--- .../containers/VariableWidthIntArray.java | 9 ++++---- .../intellij/util/xmlb/OptionTagBinding.java | 3 ++- .../ide/actions/StartUseVcsDialog.java | 3 ++- .../openapi/vcs/actions/VcsGroupsWrapper.java | 5 ++-- .../openapi/vcs/ex/LineStatusTracker.java | 4 ++-- .../com/intellij/openapi/vcs/ex/Range.java | 2 +- .../xdebugger/impl/ui/XDebugSessionTab.java | 3 ++- .../TestDataNavigationHandler.java | 2 +- .../ant/config/execution/OutputParser2.java | 2 +- .../explorer/AntExplorerTreeStructure.java | 2 +- .../actions/AddFileOrDirectoryAction.java | 2 +- .../cvsSupport2/actions/IgnoreFileAction.java | 4 +--- .../CvsApplicationLevelConfiguration.java | 2 +- .../cvsAdd/AddFileOperation.java | 2 +- .../AdminWriterOnCache.java | 2 +- .../org/jetbrains/git4idea/ssh/SSHMain.java | 4 ++-- .../GroovyParameterInfoHandler.java | 4 ++-- .../psi/impl/auxiliary/GrLabelReference.java | 3 ++- .../CompleteReferenceExpression.java | 4 ++-- .../types/GrCodeReferenceElementImpl.java | 2 +- .../junit2/segments/InputObjectRegistry.java | 2 +- .../execution/junit2/ui/StatisticsTable.java | 2 +- .../MavenArtifactCoordinatesConverter.java | 2 +- .../references/MavenPropertyPsiReference.java | 3 ++- .../references/PropertyReferenceBase.java | 2 +- .../dialogs/browser/DeleteOptionsDialog.java | 3 ++- .../dialogs/browser/ImportOptionsDialog.java | 3 ++- .../dialogs/browser/MkdirOptionsDialog.java | 3 ++- .../designSurface/GridDropLocation.java | 5 ++-- .../xslt/context/XsltContextProvider.java | 3 ++- .../xslt/impl/references/ModeReference.java | 4 ++-- .../plugins/xpathView/XPathEvalAction.java | 2 +- .../intellij/util/xml/impl/DomAnchorImpl.java | 4 ++-- .../util/xml/impl/DomFileElementImpl.java | 2 +- .../util/xml/impl/DomInvocationHandler.java | 4 ++-- .../highlighting/DomElementsInspection.java | 2 +- .../xml/model/impl/BaseDomModelFactory.java | 3 ++- .../completion/XmlCompletionData.java | 2 +- .../CompositeLanguageFileViewProvider.java | 2 +- .../source/parsing/xml/OldXmlParsing.java | 2 +- .../impl/source/xml/XmlEntityDeclImpl.java | 2 +- .../psi/impl/source/xml/XmlEntityRefImpl.java | 3 ++- .../xml/impl/ExternalDocumentValidator.java | 11 +++------ 128 files changed, 212 insertions(+), 221 deletions(-) diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberInfoExternalizer.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberInfoExternalizer.java index ffaa5d227fcd..a807bd59f126 100644 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberInfoExternalizer.java +++ b/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberInfoExternalizer.java @@ -57,7 +57,7 @@ public class MemberInfoExternalizer { else if (tag == FIELD_INFO_TAG) { return new FieldInfo(in); } - LOG.assertTrue(false, "Unknown member info"); + LOG.error("Unknown member info"); return null; } @@ -69,7 +69,7 @@ public class MemberInfoExternalizer { else if (tag == MEMBER_REFERENCE_INFO_TAG) { return new MemberReferenceInfo(in); } - LOG.assertTrue(false, "Unknown declaration info tag: " + tag); + LOG.error("Unknown declaration info tag: " + tag); return null; } @@ -108,7 +108,7 @@ public class MemberInfoExternalizer { else if (tag == ENUM_CONSTANT_VALUE_TAG) { return new EnumConstantValue(in); } - LOG.assertTrue(false, "Unknown constant value type " + tag); + LOG.error("Unknown constant value type " + tag); return null; } @@ -120,7 +120,7 @@ public class MemberInfoExternalizer { out.writeByte(FIELD_INFO_TAG); } else { - LOG.assertTrue(false, "Unknown member info"); + LOG.error("Unknown member info"); } info.save(out); } diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/MethodInfo.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/MethodInfo.java index 1aa0cda20e28..c18d9ae801d7 100644 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/MethodInfo.java +++ b/java/compiler/impl/src/com/intellij/compiler/classParsing/MethodInfo.java @@ -161,7 +161,7 @@ public class MethodInfo extends MemberInfo { String descriptor = symbolTable.getSymbol(getDescriptor()); int endIndex = descriptor.indexOf(')'); if (endIndex <= 0) { - LOG.assertTrue(false, "Corrupted method descriptor: "+descriptor); + LOG.error("Corrupted method descriptor: " + descriptor); } myParameterDescriptors = parseParameterDescriptors(descriptor.substring(1, endIndex)); } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/OneProjectItemCompileScope.java b/java/compiler/impl/src/com/intellij/compiler/impl/OneProjectItemCompileScope.java index c815ecde5e45..d85b28af44e8 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/OneProjectItemCompileScope.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/OneProjectItemCompileScope.java @@ -71,7 +71,7 @@ public class OneProjectItemCompileScope extends UserDataHolderBase implements Co public Module[] getAffectedModules() { final Module module = ModuleUtil.findModuleForFile(myFile, myProject); if (module == null) { - LOG.assertTrue(false, "Module is null for file " + myFile.getPresentableUrl()); + LOG.error("Module is null for file " + myFile.getPresentableUrl()); return Module.EMPTY_ARRAY; } return new Module[] {module}; diff --git a/java/compiler/impl/src/com/intellij/compiler/make/CacheUtils.java b/java/compiler/impl/src/com/intellij/compiler/make/CacheUtils.java index 1514175abc88..e2ce0fa640d7 100644 --- a/java/compiler/impl/src/com/intellij/compiler/make/CacheUtils.java +++ b/java/compiler/impl/src/com/intellij/compiler/make/CacheUtils.java @@ -47,7 +47,7 @@ public class CacheUtils { String descriptor = symbolTable.getSymbol(methodDeclarationId.getDescriptor()); int endIndex = descriptor.indexOf(')'); if (endIndex <= 0) { - LOG.assertTrue(false, "Corrupted method descriptor: "+descriptor); + LOG.error("Corrupted method descriptor: " + descriptor); } return parseSignature(descriptor.substring(1, endIndex)); } diff --git a/java/compiler/impl/src/com/intellij/compiler/make/Dependency.java b/java/compiler/impl/src/com/intellij/compiler/make/Dependency.java index 3eb5aed1eeb0..cf50003bc0e4 100644 --- a/java/compiler/impl/src/com/intellij/compiler/make/Dependency.java +++ b/java/compiler/impl/src/com/intellij/compiler/make/Dependency.java @@ -97,7 +97,7 @@ public class Dependency { String descriptorStr = symbolTable.getSymbol(descriptor); int endIndex = descriptorStr.indexOf(')'); if (endIndex <= 0) { - LOG.assertTrue(false, "Corrupted method descriptor: "+ descriptorStr); + LOG.error("Corrupted method descriptor: " + descriptorStr); } myParameterDescriptors = parseParameterDescriptors(descriptorStr.substring(1, endIndex)); } diff --git a/java/compiler/impl/src/com/intellij/compiler/make/DependencyCacheNavigator.java b/java/compiler/impl/src/com/intellij/compiler/make/DependencyCacheNavigator.java index 29c595abf304..a93caa2aeb54 100644 --- a/java/compiler/impl/src/com/intellij/compiler/make/DependencyCacheNavigator.java +++ b/java/compiler/impl/src/com/intellij/compiler/make/DependencyCacheNavigator.java @@ -39,7 +39,7 @@ public class DependencyCacheNavigator { int superQName = myCache.getSuperQualifiedName(classQName); if (classQName == superQName) { - LOG.assertTrue(false, "Superclass qualified name is the same as class' name: " + classQName); + LOG.error("Superclass qualified name is the same as class' name: " + classQName); return; } @@ -70,7 +70,7 @@ public class DependencyCacheNavigator { public void walkSubClasses(int fromClassQName, ClassInfoProcessor processor) throws CacheCorruptedException { for (int subQName : myCache.getSubclasses(fromClassQName)) { if (fromClassQName == subQName) { - LOG.assertTrue(false, "Subclass qualified name is the same as class' name: " + fromClassQName); + LOG.error("Subclass qualified name is the same as class' name: " + fromClassQName); return; } if (subQName != Cache.UNKNOWN) { diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java index c05df216afbf..e9cd41bdbc0f 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java @@ -245,7 +245,7 @@ public abstract class DebugProcessImpl implements DebugProcess { @SuppressWarnings({"HardCodedStringLiteral"}) protected void commitVM(VirtualMachine vm) { if (!isInInitialState()) { - LOG.assertTrue(false, "State is invalid " + myState.get()); + LOG.error("State is invalid " + myState.get()); } DebuggerManagerThreadImpl.assertIsManagerThread(); myPositionManager = createPositionManager(); diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/JVMNameUtil.java b/java/debugger/impl/src/com/intellij/debugger/engine/JVMNameUtil.java index f5e40da93aea..6faffeba0813 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/JVMNameUtil.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/JVMNameUtil.java @@ -95,7 +95,7 @@ public class JVMNameUtil { buffer.append(getPrimitiveSignature(psiType.getCanonicalText())); } else { - LOG.assertTrue(false, "unknown type " + type.getCanonicalText()); + LOG.error("unknown type " + type.getCanonicalText()); } } diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java index 8b8813ebe377..1c0134e06326 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java @@ -215,12 +215,12 @@ public class PositionManagerImpl implements PositionManager { if(PsiUtil.isLocalOrAnonymousClass(psiClass)) { final PsiClass parentNonLocal = JVMNameUtil.getTopLevelParentClass(psiClass); if(parentNonLocal == null) { - LOG.assertTrue(false, "Local or anonymous class has no non-local parent"); + LOG.error("Local or anonymous class has no non-local parent"); return Collections.emptyList(); } final String parentClassName = JVMNameUtil.getNonAnonymousClassName(parentNonLocal); if(parentClassName == null) { - LOG.assertTrue(false, "The name of a parent of a local (anonymous) class is null"); + LOG.error("The name of a parent of a local (anonymous) class is null"); return Collections.emptyList(); } final List outers = myDebugProcess.getVirtualMachineProxy().classesByName(parentClassName); diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerImpl.java index 6acf537430c9..6d5c2b3ae382 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerImpl.java @@ -120,7 +120,7 @@ public class SuspendManagerImpl implements SuspendManager { if (thread != null) { // check that thread is suspended at the moment try { if (!thread.isSuspended()) { - LOG.assertTrue(false, "Context thread must be suspended"); + LOG.error("Context thread must be suspended"); } } catch (ObjectCollectedException ignored) {} diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/CodeFragmentEvaluator.java b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/CodeFragmentEvaluator.java index 5fb1e8b2823a..6572d44e2570 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/CodeFragmentEvaluator.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/CodeFragmentEvaluator.java @@ -86,7 +86,7 @@ public class CodeFragmentEvaluator extends BlockStatementEvaluator{ return vm.mirrorOf((String)value); } else { - LOG.assertTrue(false, "unknown default initializer type " + value.getClass().getName()); + LOG.error("unknown default initializer type " + value.getClass().getName()); return null; } } diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java b/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java index b041959ed403..6848a3f3450b 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java @@ -129,7 +129,7 @@ public abstract class InvokeThread { } if(getCurrentRequest() != current) { - LOG.assertTrue(false, "Expected " + current + " instead of " + getCurrentRequest()); + LOG.error("Expected " + current + " instead of " + getCurrentRequest()); } processEvent(myEvents.get()); diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeExpression.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeExpression.java index bb89a974ac0e..f744512122e8 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeExpression.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeExpression.java @@ -266,7 +266,7 @@ public class DebuggerTreeNodeExpression { return ((ValueDescriptorImpl)node.getDescriptor()).getTreeEvaluation(node, context); } else { - LOG.assertTrue(false, node.getDescriptor() != null ? node.getDescriptor().getClass().getName() : "null"); + LOG.error(node.getDescriptor() != null ? node.getDescriptor().getClass().getName() : "null"); return null; } } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/NodeDescriptorFactoryImpl.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/NodeDescriptorFactoryImpl.java index 575f1260d37e..9596b397b222 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/NodeDescriptorFactoryImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/NodeDescriptorFactoryImpl.java @@ -138,7 +138,7 @@ public class NodeDescriptorFactoryImpl implements NodeDescriptorFactory { final DescriptorData descriptorData; if (objRef == null ) { if (!field.isStatic()) { - LOG.assertTrue(false, "Object reference is null for non-static field: " + field); + LOG.error("Object reference is null for non-static field: " + field); } descriptorData = new StaticFieldData(field); } diff --git a/java/execution/impl/src/com/intellij/compiler/options/CompileStepBeforeRun.java b/java/execution/impl/src/com/intellij/compiler/options/CompileStepBeforeRun.java index d165861a020c..88c56e8ca770 100644 --- a/java/execution/impl/src/com/intellij/compiler/options/CompileStepBeforeRun.java +++ b/java/execution/impl/src/com/intellij/compiler/options/CompileStepBeforeRun.java @@ -102,10 +102,8 @@ public class CompileStepBeforeRun extends BeforeRunTaskProvider 0) { for (Module module : modules) { if (module == null) { - LOG.assertTrue( - false, - "RunConfiguration should not return null modules. Configuration=" + runConfiguration.getName() + "; class=" + runConfiguration.getClass().getName() - ); + LOG.error("RunConfiguration should not return null modules. Configuration=" + runConfiguration.getName() + "; class=" + + runConfiguration.getClass().getName()); } } scope = compilerManager.createModulesCompileScope(modules, true); diff --git a/java/execution/impl/src/com/intellij/execution/junit2/configuration/CommonJavaParameters.java b/java/execution/impl/src/com/intellij/execution/junit2/configuration/CommonJavaParameters.java index 8d411dbd9bd9..f32438d59ee4 100644 --- a/java/execution/impl/src/com/intellij/execution/junit2/configuration/CommonJavaParameters.java +++ b/java/execution/impl/src/com/intellij/execution/junit2/configuration/CommonJavaParameters.java @@ -32,6 +32,7 @@ import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.RawCommandLineEditor; +import com.intellij.util.ArrayUtil; import javax.swing.*; import java.awt.*; @@ -152,7 +153,7 @@ public class CommonJavaParameters extends JPanel { final List macros = new ArrayList(PathMacros.getInstance().getUserMacroNames()); macros.add("MODULE_DIR"); - final JList list = new JList(macros.toArray(new String[macros.size()])); + final JList list = new JList(ArrayUtil.toStringArray(macros)); final JBPopup popup = JBPopupFactory.getInstance().createListPopupBuilder(list).setItemChoosenCallback(new Runnable() { public void run() { final Object value = list.getSelectedValue(); diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ClasspathPanel.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ClasspathPanel.java index 3e57d38f4728..9d04aa700dbd 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ClasspathPanel.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ClasspathPanel.java @@ -18,8 +18,6 @@ package com.intellij.openapi.roots.ui.configuration; import com.intellij.ide.DataManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.module.Module; @@ -530,7 +528,7 @@ public class ClasspathPanel extends JPanel { } } } - LOG.assertTrue(false, "Unknown library " + item); + LOG.error("Unknown library " + item); return null; } @@ -549,7 +547,7 @@ public class ClasspathPanel extends JPanel { } } } - LOG.assertTrue(false, "Unknown library " + item); + LOG.error("Unknown library " + item); return null; } @@ -886,7 +884,7 @@ public class ClasspathPanel extends JPanel { if (columnIndex == ITEM_COLUMN) { return item; } - LOG.assertTrue(false, "Incorrect column index: " + columnIndex); + LOG.error("Incorrect column index: " + columnIndex); return null; } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/LibraryChooserElement.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/LibraryChooserElement.java index 54386314ffa9..99c2c8efebd6 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/LibraryChooserElement.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/LibraryChooserElement.java @@ -56,7 +56,7 @@ public class LibraryChooserElement { myLibrary = library; myOrderEntry = orderEntry; if (myLibrary == null && myOrderEntry == null) { - LOG.assertTrue(false, "Both library and order entry are null"); + LOG.error("Both library and order entry are null"); myName = ProjectBundle.message("module.libraries.unknown.item"); } else { diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTreeComponent.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTreeComponent.java index 3b7c3a3ad4d9..db8f14791cb1 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTreeComponent.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTreeComponent.java @@ -44,6 +44,7 @@ import com.intellij.ui.treeStructure.SimpleNode; import com.intellij.ui.treeStructure.SimpleTreeBuilder; import com.intellij.ui.treeStructure.SimpleTreeStructure; import com.intellij.ui.treeStructure.WeightBasedComparator; +import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NonNls; @@ -288,7 +289,7 @@ public class LayoutTreeComponent implements DnDTarget, Disposable { myBuilder.addSubtreeToUpdate(treeNode, new Runnable() { public void run() { List> nodes = myTree.findNodes(toSelect); - myBuilder.select(nodes.toArray(new Object[nodes.size()]), null); + myBuilder.select(ArrayUtil.toObjectArray(nodes), null); } }); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/nodes/PackagingElementNode.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/nodes/PackagingElementNode.java index 349016a15a2e..7e1e8e653623 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/nodes/PackagingElementNode.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/nodes/PackagingElementNode.java @@ -27,6 +27,7 @@ import com.intellij.packaging.elements.PackagingElement; import com.intellij.packaging.ui.ArtifactEditorContext; import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.treeStructure.SimpleNode; +import com.intellij.util.ArrayUtil; import com.intellij.util.SmartList; import com.intellij.util.StringBuilderSpinAllocator; import org.jetbrains.annotations.NotNull; @@ -81,7 +82,7 @@ public class PackagingElementNode> extends Artifac @Override public Object[] getEqualityObjects() { - return myPackagingElements.toArray(new Object[myPackagingElements.size()]); + return ArrayUtil.toObjectArray(myPackagingElements); } @Override diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java index 6c6c209a4d78..d6d33237a64a 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java @@ -222,12 +222,11 @@ public class JavaCompletionContributor extends CompletionContributor { final Object[] variants = reference.getVariants(); if (variants == null) { - LOG.assertTrue(false, "Reference=" + reference); + LOG.error("Reference=" + reference); } for (Object completion : variants) { if (completion == null) { - LOG.assertTrue(false, "Position=" + insertedElement + "\n;Reference=" + reference + "\n;variants=" + Arrays.toString( - variants)); + LOG.error("Position=" + insertedElement + "\n;Reference=" + reference + "\n;variants=" + Arrays.toString(variants)); } if (completion instanceof LookupElement) { result.addElement((LookupElement)completion); diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/CopyPasteReferenceProcessor.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/CopyPasteReferenceProcessor.java index dabe31bccb74..3f70ed37a9e4 100644 --- a/java/java-impl/src/com/intellij/codeInsight/editorActions/CopyPasteReferenceProcessor.java +++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/CopyPasteReferenceProcessor.java @@ -26,6 +26,7 @@ import com.intellij.openapi.project.DumbService; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.*; +import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.Nullable; @@ -238,7 +239,7 @@ public class CopyPasteReferenceProcessor implements CopyPastePostProcessor { } if (array.isEmpty()) return; - Object[] selectedObjects = array.toArray(new Object[array.size()]); + Object[] selectedObjects = ArrayUtil.toObjectArray(array); Arrays.sort( selectedObjects, new Comparator() { diff --git a/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java b/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java index bdea5103dccd..a2455da108b2 100644 --- a/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java +++ b/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java @@ -516,15 +516,8 @@ public class JavaFoldingBuilder extends FoldingBuilderEx implements DumbAware { final String baseClassName = quick ? anonymousClass.getBaseClassReference().getReferenceName() : anonymousClass.getBaseClassType().resolve().getName(); if (lastLineEnd >= seq.length() || firstLineStart >= seq.length() || firstLineStart < 0) { - LOG.assertTrue(false, "llE=" + - lastLineEnd + - "; fLS=" + - firstLineStart + - "; len=" + - seq.length() + - "rE=" + - rangeEnd + - "; class=" + baseClassName); + LOG.error("llE=" + lastLineEnd + "; fLS=" + firstLineStart + "; len=" + seq.length() + "rE=" + rangeEnd + "; class=" + + baseClassName); } final String params = StringUtil.join(method.getParameterList().getParameters(), new Function() { diff --git a/java/java-impl/src/com/intellij/codeInsight/hint/JavaImplementationTextSelectioner.java b/java/java-impl/src/com/intellij/codeInsight/hint/JavaImplementationTextSelectioner.java index 8e5800d295c6..8028a96d4a08 100644 --- a/java/java-impl/src/com/intellij/codeInsight/hint/JavaImplementationTextSelectioner.java +++ b/java/java-impl/src/com/intellij/codeInsight/hint/JavaImplementationTextSelectioner.java @@ -46,7 +46,7 @@ public class JavaImplementationTextSelectioner implements ImplementationTextSele return element.getTextRange().getStartOffset(); } else { - LOG.assertTrue(false, "Element should not be null: " + parent.getText()); + LOG.error("Element should not be null: " + parent.getText()); return parent.getTextRange().getStartOffset(); } } diff --git a/java/java-impl/src/com/intellij/codeInsight/lookup/LookupItemUtil.java b/java/java-impl/src/com/intellij/codeInsight/lookup/LookupItemUtil.java index 4e53c23a2c6d..aca3dff1c9d9 100644 --- a/java/java-impl/src/com/intellij/codeInsight/lookup/LookupItemUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/lookup/LookupItemUtil.java @@ -137,7 +137,7 @@ public class LookupItemUtil{ } if (s == null) { - LOG.assertTrue(false, "Null string for object: " + object + " of class " + (object != null ?object.getClass():null)); + LOG.error("Null string for object: " + object + " of class " + (object != null ? object.getClass() : null)); } if (object instanceof LookupValueWithTail) { item.setAttribute(LookupItem.TAIL_TEXT_ATTR, " " + ((LookupValueWithTail)object).getTailText()); diff --git a/java/java-impl/src/com/intellij/psi/impl/source/PsiJavaCodeReferenceElementImpl.java b/java/java-impl/src/com/intellij/psi/impl/source/PsiJavaCodeReferenceElementImpl.java index 6a99cc098da4..5144c7793908 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/PsiJavaCodeReferenceElementImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/PsiJavaCodeReferenceElementImpl.java @@ -354,7 +354,7 @@ public class PsiJavaCodeReferenceElementImpl extends CompositePsiElement impleme public JavaResolveResult[] multiResolve(final boolean incompleteCode) { final PsiManagerEx manager = getManager(); if (manager == null) { - LOG.assertTrue(false, "getManager() == null!"); + LOG.error("getManager() == null!"); return JavaResolveResult.EMPTY_ARRAY; } @@ -400,7 +400,7 @@ public class PsiJavaCodeReferenceElementImpl extends CompositePsiElement impleme return JavaResolveResult.EMPTY_ARRAY; } else { - LOG.assertTrue(false, "Invalid java reference!"); + LOG.error("Invalid java reference!"); return JavaResolveResult.EMPTY_ARRAY; } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/parsing/JavadocParsing.java b/java/java-impl/src/com/intellij/psi/impl/source/parsing/JavadocParsing.java index d5439d0dce6f..42dfd622a4bf 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/parsing/JavadocParsing.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/parsing/JavadocParsing.java @@ -331,7 +331,7 @@ public class JavadocParsing extends Parsing { LeafElement tokenElement = myParsing.createTokenElement(lexer); IElementType type = lexer.getTokenType(); if (!TOKEN_FILTER.contains(type)) { - LOG.assertTrue(false, "Missed token should be space or asterisks:" + tokenElement); + LOG.error("Missed token should be space or asterisks:" + tokenElement); throw new RuntimeException(); } if (last != null) { diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/JavaChangeUtilSupport.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/JavaChangeUtilSupport.java index 1bc212c954c8..14b44609ccc5 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/JavaChangeUtilSupport.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/JavaChangeUtilSupport.java @@ -436,7 +436,7 @@ public class JavaChangeUtilSupport implements TreeGenerator, TreeCopyHandler { } } else { - LOG.assertTrue(false, "Wrong element type: " + original.getElementType()); + LOG.error("Wrong element type: " + original.getElementType()); } } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java index 8cb2b20f6a6f..deea549bc0d1 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java @@ -284,7 +284,7 @@ public class PsiReferenceExpressionImpl extends ExpressionPsiElement implements public JavaResolveResult[] multiResolve(boolean incompleteCode) { final PsiManagerEx manager = getManager(); if (manager == null) { - LOG.assertTrue(false, "getManager() == null!"); + LOG.error("getManager() == null!"); return null; } ResolveResult[] results = manager.getResolveCache().resolveWithCaching(this, OurGenericsResolver.INSTANCE, true, incompleteCode); @@ -619,7 +619,7 @@ public class PsiReferenceExpressionImpl extends ExpressionPsiElement implements if (nameChild == null) { final TreeElement dot = (TreeElement)findChildByRole(ChildRole.DOT); if (dot == null) { - LOG.assertTrue(false, this); + LOG.error(toString()); } return new TextRange(dot.getStartOffsetInParent() + dot.getTextLength(), getTextLength()); } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/ReplaceExpressionUtil.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/ReplaceExpressionUtil.java index b18e8b8f0e1a..f016798a5f6b 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/ReplaceExpressionUtil.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/ReplaceExpressionUtil.java @@ -154,7 +154,7 @@ public class ReplaceExpressionUtil implements Constants { return 14; } else { - LOG.assertTrue(false, "Unknown element type:"+i); + LOG.error("Unknown element type:" + i); return -1; } } diff --git a/java/java-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java b/java/java-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java index bae8d6c2d350..22c5be988e64 100644 --- a/java/java-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java +++ b/java/java-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java @@ -233,7 +233,7 @@ public class PsiScopesUtil { } } else{ - LOG.assertTrue(false, "Unknown name element " + referenceNameElement + " in reference " + ref.getText() + "(" + ref + ")"); + LOG.error("Unknown name element " + referenceNameElement + " in reference " + ref.getText() + "(" + ref + ")"); } } else if (referenceNameElement instanceof PsiIdentifier){ @@ -243,7 +243,7 @@ public class PsiScopesUtil { resolveAndWalk(processor, ref, null); } else{ - LOG.assertTrue(false, "Unknown name element " + referenceNameElement + " in reference " + ref.getText() + "(" + ref + ")"); + LOG.error("Unknown name element " + referenceNameElement + " in reference " + ref.getText() + "(" + ref + ")"); } } else{ diff --git a/java/java-impl/src/com/intellij/refactoring/IntroduceHandlerBase.java b/java/java-impl/src/com/intellij/refactoring/IntroduceHandlerBase.java index 3216086a31ca..bccfa30c379f 100644 --- a/java/java-impl/src/com/intellij/refactoring/IntroduceHandlerBase.java +++ b/java/java-impl/src/com/intellij/refactoring/IntroduceHandlerBase.java @@ -54,7 +54,7 @@ public abstract class IntroduceHandlerBase { invokeImpl(project, (PsiLocalVariable)tempExpr, editor); } else { - LOG.assertTrue(false, "elements[0] should be PsiExpression or PsiLocalVariable"); + LOG.error("elements[0] should be PsiExpression or PsiLocalVariable"); } } diff --git a/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureDialog.java b/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureDialog.java index 6e8f0acb09b1..510c5e1892c4 100644 --- a/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureDialog.java @@ -238,7 +238,7 @@ public class ChangeSignatureDialog extends RefactoringDialog { final PsiElementFactory factory = JavaPsiFacade.getInstance(myMethod.getProject()).getElementFactory(); final PsiTypeElement typeElement = myMethod.getReturnTypeElement(); if (typeElement == null) { - LOG.assertTrue(false, myMethod.getClass().getName()); + LOG.error(myMethod.getClass().getName()); return panel; } myReturnTypeCodeFragment = factory.createTypeCodeFragment(typeElement.getText(), myMethod.getParameterList(), true, true); diff --git a/java/java-impl/src/com/intellij/refactoring/changeSignature/MethodCallUsageInfo.java b/java/java-impl/src/com/intellij/refactoring/changeSignature/MethodCallUsageInfo.java index eacc2e9fbc59..616ec7f5c32e 100644 --- a/java/java-impl/src/com/intellij/refactoring/changeSignature/MethodCallUsageInfo.java +++ b/java/java-impl/src/com/intellij/refactoring/changeSignature/MethodCallUsageInfo.java @@ -52,7 +52,7 @@ public class MethodCallUsageInfo extends UsageInfo { else if (parent instanceof PsiAnonymousClass) { return ((PsiNewExpression)parent.getParent()).resolveConstructor(); } - LOG.assertTrue(false, "Unknown reference"); + LOG.error("Unknown reference"); return null; } diff --git a/java/java-impl/src/com/intellij/refactoring/extractMethod/ControlFlowWrapper.java b/java/java-impl/src/com/intellij/refactoring/extractMethod/ControlFlowWrapper.java index ffe10f406a71..23bd6406fdf5 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractMethod/ControlFlowWrapper.java +++ b/java/java-impl/src/com/intellij/refactoring/extractMethod/ControlFlowWrapper.java @@ -281,7 +281,7 @@ public class ControlFlowWrapper { if (myFlowStart <= startOffset && endOffset <= myFlowEnd) continue; } else { - LOG.assertTrue(false, exitStatement); + LOG.error(String.valueOf(exitStatement)); continue; } diff --git a/java/java-impl/src/com/intellij/refactoring/rename/JavaNameSuggestionProvider.java b/java/java-impl/src/com/intellij/refactoring/rename/JavaNameSuggestionProvider.java index 8b8414794e19..23a2b12cc3bc 100644 --- a/java/java-impl/src/com/intellij/refactoring/rename/JavaNameSuggestionProvider.java +++ b/java/java-impl/src/com/intellij/refactoring/rename/JavaNameSuggestionProvider.java @@ -165,7 +165,7 @@ public class JavaNameSuggestionProvider implements NameSuggestionProvider { result.add(suggestProperlyCasedName(prefix, NameUtil.splitNameIntoWords(name))); } result.add(suggestProperlyCasedName(prefix, NameUtil.splitNameIntoWords(name.toLowerCase()))); - return result.toArray(new String[result.size()]); + return ArrayUtil.toStringArray(result); } } diff --git a/java/java-impl/src/com/intellij/refactoring/rename/naming/PsiNamedElementAutomaticRenamer.java b/java/java-impl/src/com/intellij/refactoring/rename/naming/PsiNamedElementAutomaticRenamer.java index dd0e4c62973d..b5c4e74566c4 100644 --- a/java/java-impl/src/com/intellij/refactoring/rename/naming/PsiNamedElementAutomaticRenamer.java +++ b/java/java-impl/src/com/intellij/refactoring/rename/naming/PsiNamedElementAutomaticRenamer.java @@ -45,13 +45,8 @@ public abstract class PsiNamedElementAutomaticRenamer String canonicalName = nameToCanonicalName(elementName, element); final String newCanonicalName = suggester.suggestName(canonicalName); if (newCanonicalName.length() == 0) { - LOG.assertTrue(false, - "oldName = " + getOldName() + - ", newName = " + getNewName() + - ", name = " + elementName + - ", canonicalName = " + canonicalName + - ", newCanonicalName = " + newCanonicalName - ); + LOG.error("oldName = " + getOldName() + ", newName = " + getNewName() + ", name = " + elementName + ", canonicalName = " + + canonicalName + ", newCanonicalName = " + newCanonicalName); } return canonicalNameToName(newCanonicalName, element); } diff --git a/java/java-impl/src/com/intellij/refactoring/util/classRefs/ClassInstanceScanner.java b/java/java-impl/src/com/intellij/refactoring/util/classRefs/ClassInstanceScanner.java index 99f8f33fcfaf..cc72b6682993 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/classRefs/ClassInstanceScanner.java +++ b/java/java-impl/src/com/intellij/refactoring/util/classRefs/ClassInstanceScanner.java @@ -186,7 +186,7 @@ public class ClassInstanceScanner extends DelegatingClassReferenceVisitor { visitor.visitReadUsage(expression, null, referencedElement); } else { - LOG.assertTrue(false, "Unknown variation of class instance usage"); + LOG.error("Unknown variation of class instance usage"); } } diff --git a/platform/lang-api/src/com/intellij/execution/runners/ProgramRunnerUtil.java b/platform/lang-api/src/com/intellij/execution/runners/ProgramRunnerUtil.java index 2fe12089b83a..1362af5b7213 100644 --- a/platform/lang-api/src/com/intellij/execution/runners/ProgramRunnerUtil.java +++ b/platform/lang-api/src/com/intellij/execution/runners/ProgramRunnerUtil.java @@ -44,7 +44,7 @@ public class ProgramRunnerUtil { String message = ExecutionBundle.message("error.running.configuration.with.error.error.message", runProfile != null? runProfile.getName() : "Run profile", e.getMessage()); if (ApplicationManager.getApplication().isUnitTestMode()) { - LOG.assertTrue(false, message); + LOG.error(message); } else { if (message.contains("87") && e instanceof ProcessNotCreatedException) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java index 0892b7696ce9..efd1e6381a12 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java @@ -396,7 +396,7 @@ public class CodeCompletionHandlerBase implements CodeInsightActionHandler { if (fileCopy == null) { PsiElement elementAfterCommit = findElementAt(hostFile, hostStartOffset); if (wasInjected) { - LOG.assertTrue(false, "No injected fragmnent found at offset " + hostStartOffset + " in the patched file copy, found: " + elementAfterCommit); + LOG.error("No injected fragmnent found at offset " + hostStartOffset + " in the patched file copy, found: " + elementAfterCommit); } fileCopy = elementAfterCommit == null ? oldFileCopy : elementAfterCommit.getContainingFile(); } @@ -420,11 +420,8 @@ public class CodeCompletionHandlerBase implements CodeInsightActionHandler { final String allDoc = hostFile.getViewProvider().getDocument().getText(); String docText = allDoc.substring(Math.max(0, context.getStartOffset() - 10), Math.min(allDoc.length(), context.getStartOffset() + 10)); - LOG.assertTrue(false, "offset " + newContext.getStartOffset() + " at:\n" + - "text=\"" + injectedFile.getText() + "\"\n" + - "instance=" + injectedFile + "\n" + - "patcher=" + patcher + "\n" + - "docText=" + docText); + LOG.error("offset " + newContext.getStartOffset() + " at:\n" + "text=\"" + injectedFile.getText() + "\"\n" + "instance=" + + injectedFile + "\n" + "patcher=" + patcher + "\n" + "docText=" + docText); } EditorFactory.getInstance().releaseEditor(editor); return Pair.create(newContext, element); @@ -433,7 +430,7 @@ public class CodeCompletionHandlerBase implements CodeInsightActionHandler { } PsiElement element = findElementAt(fileCopy, context.getStartOffset()); if (element == null) { - LOG.assertTrue(false, "offset " + context.getStartOffset() + " at:\ntext=\"" + fileCopy.getText() + "\"\ninstance=" + fileCopy); + LOG.error("offset " + context.getStartOffset() + " at:\ntext=\"" + fileCopy.getText() + "\"\ninstance=" + fileCopy); } return Pair.create(context, element); } @@ -463,7 +460,7 @@ public class CodeCompletionHandlerBase implements CodeInsightActionHandler { Project project = context.project; Editor editor = context.editor; if (!ApplicationManager.getApplication().isUnitTestMode() && context.editor.getComponent().getRootPane() == null) { - LOG.assertTrue(false, "null root pane"); + LOG.error("null root pane"); } for (final CompletionContributor contributor : CompletionContributor.forParameters(parameters)) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionData.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionData.java index 7f234341b844..58257600360f 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionData.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionData.java @@ -248,7 +248,7 @@ public class CompletionData { s = ((PresentableLookupValue)object).getPresentation(); } else { - LOG.assertTrue(false, "Null string for object: " + object + " of class " + (object != null ?object.getClass():null)); + LOG.error("Null string for object: " + object + " of class " + (object != null ? object.getClass() : null)); } LookupItem item = new LookupItem(object, s); @@ -311,7 +311,7 @@ public class CompletionData { for (Object completion : completions) { if (completion == null) { - LOG.assertTrue(false, "Position=" + position + "\n;Reference=" + reference + "\n;variants=" + Arrays.toString(completions)); + LOG.error("Position=" + position + "\n;Reference=" + reference + "\n;variants=" + Arrays.toString(completions)); } if (completion instanceof PsiElement) { final PsiElement psiElement = (PsiElement)completion; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java index a667dd956f43..8f1cd78588a9 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java @@ -181,7 +181,7 @@ public class DocumentFoldingInfo implements JDOMExternalizable, CodeFoldingState PsiElement restoredElement = FoldingPolicy.restoreBySignature(psiElement.getContainingFile(), signature); if (!psiElement.equals(restoredElement)){ restoredElement = FoldingPolicy.restoreBySignature(psiElement.getContainingFile(), signature); - LOG.assertTrue(false, "element:" + psiElement + ", signature:" + signature + ", file:" + psiElement.getContainingFile()); + LOG.error("element:" + psiElement + ", signature:" + signature + ", file:" + psiElement.getContainingFile()); } Element e = new Element(ELEMENT_TAG); diff --git a/platform/lang-impl/src/com/intellij/extapi/psi/PsiElementBase.java b/platform/lang-impl/src/com/intellij/extapi/psi/PsiElementBase.java index b8d550e237db..51b3594a0fda 100644 --- a/platform/lang-impl/src/com/intellij/extapi/psi/PsiElementBase.java +++ b/platform/lang-impl/src/com/intellij/extapi/psi/PsiElementBase.java @@ -243,7 +243,7 @@ public abstract class PsiElementBase extends ElementBase implements NavigatableP protected T findNotNullChildByClass(Class aClass) { final T child = findChildByClass(aClass); if (child == null) { - LOG.assertTrue(false, getText() + "\n parent=" + getParent().getText()); + LOG.error(getText() + "\n parent=" + getParent().getText()); } return child; } diff --git a/platform/lang-impl/src/com/intellij/find/actions/ShowUsagesAction.java b/platform/lang-impl/src/com/intellij/find/actions/ShowUsagesAction.java index 69d744506b30..a286f77354af 100644 --- a/platform/lang-impl/src/com/intellij/find/actions/ShowUsagesAction.java +++ b/platform/lang-impl/src/com/intellij/find/actions/ShowUsagesAction.java @@ -59,6 +59,7 @@ import com.intellij.usages.impl.NullUsage; import com.intellij.usages.impl.UsageNode; import com.intellij.usages.impl.UsageViewImpl; import com.intellij.usages.rules.UsageFilteringRuleProvider; +import com.intellij.util.ArrayUtil; import com.intellij.util.Icons; import com.intellij.util.Processor; import com.intellij.util.messages.MessageBusConnection; @@ -364,7 +365,7 @@ public class ShowUsagesAction extends AnAction { } protected Object[] getAllElements() { - return data.toArray(new Object[data.size()]); + return ArrayUtil.toObjectArray(data); } protected String getElementText(Object element) { diff --git a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeStructure.java b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeStructure.java index 191f66396613..6a9a22165cef 100644 --- a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeStructure.java +++ b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeStructure.java @@ -100,7 +100,7 @@ public class FavoritesTreeStructure extends ProjectTreeStructure { if (result.isEmpty()) { result.add(getEmptyScreen()); } - return result.toArray(new Object[result.size()]); + return ArrayUtil.toObjectArray(result); } catch (Exception e) { } diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/ProjectViewDirectoryHelper.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/ProjectViewDirectoryHelper.java index adf7c33ace82..e2341a1be15a 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/ProjectViewDirectoryHelper.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/ProjectViewDirectoryHelper.java @@ -223,7 +223,7 @@ public class ProjectViewDirectoryHelper { } } else { - LOG.assertTrue(false, "Either PsiFile or PsiDirectory expected as a child of " + child.getParent() + ", but was " + child); + LOG.error("Either PsiFile or PsiDirectory expected as a child of " + child.getParent() + ", but was " + child); } } } diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/impl/ContentEntryImpl.java b/platform/lang-impl/src/com/intellij/openapi/roots/impl/ContentEntryImpl.java index eccbbbf3ce53..f7260d85a6c6 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/impl/ContentEntryImpl.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/impl/ContentEntryImpl.java @@ -218,7 +218,7 @@ public class ContentEntryImpl extends RootModelComponentBase implements ContentE final String rootUrl = getUrl(); try { if (!FileUtil.isAncestor(new File(rootUrl), new File(url), false)) { - LOG.assertTrue(false, "The file " + url + " is not under content entry root " + rootUrl); + LOG.error("The file " + url + " is not under content entry root " + rootUrl); } } catch (IOException e) { diff --git a/platform/lang-impl/src/com/intellij/psi/formatter/FormattingDocumentModelImpl.java b/platform/lang-impl/src/com/intellij/psi/formatter/FormattingDocumentModelImpl.java index 9276f2b051f4..84d0cf06351e 100644 --- a/platform/lang-impl/src/com/intellij/psi/formatter/FormattingDocumentModelImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/formatter/FormattingDocumentModelImpl.java @@ -42,10 +42,11 @@ public class FormattingDocumentModelImpl implements FormattingDocumentModel{ Document document = getDocumentToBeUsedFor(file); if (document != null) { if (PsiDocumentManager.getInstance(file.getProject()).isUncommited(document)) { - LOG.assertTrue(false, "Document is uncommited"); + LOG.error("Document is uncommited"); } if (!document.getText().equals(file.getText())) { - LOG.assertTrue(false, "Document and psi file texts should be equal : \nDocument text:\n" + document.getText() + "\nFile text:\n" + file.getText()); + LOG.error( + "Document and psi file texts should be equal : \nDocument text:\n" + document.getText() + "\nFile text:\n" + file.getText()); } return new FormattingDocumentModelImpl(document, file); } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java index 9153e01dc4d1..b7dd5cc7ddbf 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java @@ -312,7 +312,7 @@ public class FileManagerImpl implements FileManager { ApplicationManager.getApplication().assertReadAccessAllowed(); if (!vFile.isValid()) { - LOG.assertTrue(false, "Invalid file: " + vFile); + LOG.error("Invalid file: " + vFile); return null; } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java index fe97f81cca29..d8fd4fa99440 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java @@ -103,7 +103,7 @@ public class PsiSearchHelperImpl implements PsiSearchHelper { return todoPattern; } } - LOG.assertTrue(false, "Could not find matching TODO pattern for index pattern " + pattern.getPatternString()); + LOG.error("Could not find matching TODO pattern for index pattern " + pattern.getPatternString()); return null; } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerManagerImpl.java index ce5583246b2d..3e1a0f9da35d 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerManagerImpl.java @@ -126,7 +126,7 @@ public class SmartPointerManagerImpl extends SmartPointerManager { @NotNull public SmartPsiElementPointer createSmartPsiElementPointer(E element) { if (!element.isValid()) { - LOG.assertTrue(false, "Invalid element:" + element); + LOG.error("Invalid element:" + element); } PsiFile file = element.getContainingFile(); diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java index 987edc4db892..155c9951d2c8 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java @@ -149,10 +149,10 @@ public class CodeStyleManagerImpl extends CodeStyleManager { final PsiElement start = findElementInTreeWithFormatterEnabled(file, startOffset); final PsiElement end = findElementInTreeWithFormatterEnabled(file, endOffset); if (start != null && !start.isValid()) { - LOG.assertTrue(false, "start=" + start + "; file=" + file); + LOG.error("start=" + start + "; file=" + file); } if (end != null && !end.isValid()) { - LOG.assertTrue(false, "end=" + start + "; end=" + file); + LOG.error("end=" + start + "; end=" + file); } boolean formatFromStart = startOffset == 0; diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java b/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java index 93342a6f8877..2a21662b0a99 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java @@ -266,7 +266,7 @@ public class FileReferenceSet { private PsiFile getContainingFile() { PsiFile file = myElement.getContainingFile(); if (file == null) { - LOG.assertTrue(false, "Invalid element: " + myElement); + LOG.error("Invalid element: " + myElement); } return file.getOriginalFile(); diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/SharedImplUtil.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/SharedImplUtil.java index cc2113e6182d..f99a11945d1d 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/SharedImplUtil.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/SharedImplUtil.java @@ -85,7 +85,7 @@ public class SharedImplUtil { if (tree instanceof FileElement) return ((FileElement)tree).getCharTable(); tree = tree.getTreeParent(); } - LOG.assertTrue(false, "Invalid root element"); + LOG.error("Invalid root element"); return null; } diff --git a/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateDataElementType.java b/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateDataElementType.java index 1e9b71dbcc3a..cb243e0c26b0 100644 --- a/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateDataElementType.java +++ b/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateDataElementType.java @@ -156,11 +156,11 @@ public class TemplateDataElementType extends IFileElementType implements ITempla final CharSequence buffer = lexer.getBufferSequence(); final int tokenStart = lexer.getTokenStart(); if (tokenStart < 0 || tokenStart > buffer.length()) { - LOG.assertTrue(false, "Invalid start: " + tokenStart + "; " + lexer); + LOG.error("Invalid start: " + tokenStart + "; " + lexer); } final int tokenEnd = lexer.getTokenEnd(); if (tokenEnd < 0 || tokenEnd > buffer.length()) { - LOG.assertTrue(false, "Invalid end: " + tokenEnd + "; " + lexer); + LOG.error("Invalid end: " + tokenEnd + "; " + lexer); } return new OuterLanguageElementImpl(outerElementType, table.intern(buffer, tokenStart, tokenEnd)); diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameHandlerRegistry.java b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameHandlerRegistry.java index 9d3994f7bcad..65a64ab876c1 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameHandlerRegistry.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameHandlerRegistry.java @@ -26,6 +26,7 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.lang.TitledHandler; import com.intellij.refactoring.util.RadioUpDownListener; +import com.intellij.util.ArrayUtil; import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.Nullable; @@ -80,7 +81,7 @@ public class RenameHandlerRegistry { } if (availableHandlers.size() == 1) return availableHandlers.values().iterator().next(); if (availableHandlers.size() > 1) { - final String[] strings = availableHandlers.keySet().toArray(new String[availableHandlers.keySet().size()]); + final String[] strings = ArrayUtil.toStringArray(availableHandlers.keySet()); final HandlersChooser chooser = new HandlersChooser(PlatformDataKeys.PROJECT.getData(dataContext), strings); chooser.show(); if (chooser.isOK()) { diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/naming/AutomaticRenamer.java b/platform/lang-impl/src/com/intellij/refactoring/rename/naming/AutomaticRenamer.java index 7f1519cd2e7e..655afe2866c6 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/naming/AutomaticRenamer.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/naming/AutomaticRenamer.java @@ -99,13 +99,8 @@ public abstract class AutomaticRenamer { String canonicalName = nameToCanonicalName(name, element); final String newCanonicalName = suggester.suggestName(canonicalName); if (newCanonicalName.length() == 0) { - LOG.assertTrue(false, - "oldClassName = " + oldClassName + - ", newClassName = " + newClassName + - ", name = " + name + - ", canonicalName = " + canonicalName + - ", newCanonicalName = " + newCanonicalName - ); + LOG.error("oldClassName = " + oldClassName + ", newClassName = " + newClassName + ", name = " + name + ", canonicalName = " + + canonicalName + ", newCanonicalName = " + newCanonicalName); } String newName = canonicalNameToName(newCanonicalName, element); if (!newName.equals(name)) { diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/naming/NameSuggester.java b/platform/lang-impl/src/com/intellij/refactoring/rename/naming/NameSuggester.java index 0abd6dd647e2..591c57481614 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/naming/NameSuggester.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/naming/NameSuggester.java @@ -184,8 +184,8 @@ public class NameSuggester { final int propertyWordFirst = matches.get(first); if (first >= myOldClassName.length || last >= myOldClassName.length) { - LOG.assertTrue(false, "old class name = " + myOldClassNameAsGiven + ", new class name = " + myNewClassNameAsGiven + - ", propertyWords = " + Arrays.asList(propertyWords).toString()); + LOG.error("old class name = " + myOldClassNameAsGiven + ", new class name = " + myNewClassNameAsGiven + ", propertyWords = " + + Arrays.asList(propertyWords).toString()); } final String replacement = suggestReplacement(propertyWords[propertyWordFirst], newString); diff --git a/platform/platform-api/src/com/intellij/execution/process/ProcessHandler.java b/platform/platform-api/src/com/intellij/execution/process/ProcessHandler.java index 9c8e83fffee4..e7cb96652371 100644 --- a/platform/platform-api/src/com/intellij/execution/process/ProcessHandler.java +++ b/platform/platform-api/src/com/intellij/execution/process/ProcessHandler.java @@ -58,7 +58,7 @@ public abstract class ProcessHandler extends UserDataHolderBase { myEventMulticaster.startNotified(new ProcessEvent(this)); } else { - LOG.assertTrue(false, "startNotify called already"); + LOG.error("startNotify called already"); } } diff --git a/platform/platform-api/src/com/intellij/ide/plugins/PluginManager.java b/platform/platform-api/src/com/intellij/ide/plugins/PluginManager.java index 4ba1aef918a9..ea08b49757b8 100644 --- a/platform/platform-api/src/com/intellij/ide/plugins/PluginManager.java +++ b/platform/platform-api/src/com/intellij/ide/plugins/PluginManager.java @@ -470,7 +470,7 @@ public class PluginManager { final ClassLoader loader = pluginDescriptor.getPluginClassLoader(); if (loader == null) { - getLogger().assertTrue(false, "Plugin class loader should be initialized for plugin " + id); + getLogger().error("Plugin class loader should be initialized for plugin " + id); } classLoaders.add(loader); } diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/TreeBuilderUtil.java b/platform/platform-api/src/com/intellij/ide/util/treeView/TreeBuilderUtil.java index 89624b54605a..9493ea3539c9 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/TreeBuilderUtil.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/TreeBuilderUtil.java @@ -53,7 +53,7 @@ public class TreeBuilderUtil { final Object userObject = childNode.getUserObject(); if (tree.isPathSelected(path)) { if (!(userObject instanceof NodeDescriptor)) { - LOG.assertTrue(false, "Node: " + childNode + "; userObject: " + userObject + " of class " + userObject.getClass()); + LOG.error("Node: " + childNode + "; userObject: " + userObject + " of class " + userObject.getClass()); } selectionPaths.add(storeElementsOnly ? ((NodeDescriptor)userObject).getElement() : path); } diff --git a/platform/platform-api/src/com/intellij/openapi/roots/ui/util/CompositeAppearance.java b/platform/platform-api/src/com/intellij/openapi/roots/ui/util/CompositeAppearance.java index eb9b280b865e..1f9112f016de 100644 --- a/platform/platform-api/src/com/intellij/openapi/roots/ui/util/CompositeAppearance.java +++ b/platform/platform-api/src/com/intellij/openapi/roots/ui/util/CompositeAppearance.java @@ -68,7 +68,7 @@ public class CompositeAppearance implements ModifiableCellAppearance { for (Iterator iterator = mySections.iterator(); iterator.hasNext();) { TextSection textSection = iterator.next(); if (textSection == null) { - LOG.assertTrue(false, "index: " + index + " size: " + mySections.size()); + LOG.error("index: " + index + " size: " + mySections.size()); iterator.remove(); } } diff --git a/platform/platform-api/src/com/intellij/ui/ListUtil.java b/platform/platform-api/src/com/intellij/ui/ListUtil.java index dc3c86baac34..66a380463143 100644 --- a/platform/platform-api/src/com/intellij/ui/ListUtil.java +++ b/platform/platform-api/src/com/intellij/ui/ListUtil.java @@ -268,7 +268,7 @@ public class ListUtil { if (model instanceof FilteringListModel) return FILTERED_MODEL; if (model == null) LOG.assertTrue(false); - else LOG.assertTrue(false, "Unknown model class: " + model.getClass().getName()); + else LOG.error("Unknown model class: " + model.getClass().getName()); return null; } diff --git a/platform/platform-api/src/com/intellij/ui/table/BaseTableView.java b/platform/platform-api/src/com/intellij/ui/table/BaseTableView.java index 59a0643d45ee..f58b24c6e381 100644 --- a/platform/platform-api/src/com/intellij/ui/table/BaseTableView.java +++ b/platform/platform-api/src/com/intellij/ui/table/BaseTableView.java @@ -101,8 +101,7 @@ public abstract class BaseTableView extends Table { final int modelIndex = column.getModelIndex(); storage.put(orderPropertyName(i), String.valueOf(modelIndex)); if (storedColumns[modelIndex]) { - LOG.assertTrue(false, - "columnCount: " + columnCount + " current: " + i + " modelINdex: " + modelIndex); + LOG.error("columnCount: " + columnCount + " current: " + i + " modelINdex: " + modelIndex); } storedColumns[modelIndex] = true; } @@ -160,7 +159,7 @@ public abstract class BaseTableView extends Table { for (int i = 0; i < model.getColumnCount(); i++) if (model.getColumn(i).getModelIndex() == index) return i; - LOG.assertTrue(false, "Total: " + model.getColumnCount() + " index: "+ index); + LOG.error("Total: " + model.getColumnCount() + " index: " + index); return index; } } diff --git a/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java b/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java index 4ad3015d48fe..6f66e323ef01 100644 --- a/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java +++ b/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java @@ -234,7 +234,7 @@ public class IdeEventQueue extends EventQueue { synchronized (myLock) { final boolean wasRemoved = myIdleListeners.remove(runnable); if (!wasRemoved) { - LOG.assertTrue(false, "unknown runnable: " + runnable); + LOG.error("unknown runnable: " + runnable); } final MyFireIdleRequest request = myListener2Request.remove(runnable); LOG.assertTrue(request != null); @@ -260,7 +260,7 @@ public class IdeEventQueue extends EventQueue { synchronized (myLock) { final boolean wasRemoved = myActivityListeners.remove(runnable); if (!wasRemoved) { - LOG.assertTrue(false, "unknown runnable: " + runnable); + LOG.error("unknown runnable: " + runnable); } } } diff --git a/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java b/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java index 775f44ab6b83..649f6708c328 100644 --- a/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java @@ -290,8 +290,8 @@ public class DataManagerImpl extends DataManager implements ApplicationComponent myEventCount + "; current event count = " + currentEventCount ); */ - LOG.assertTrue(false, "cannot share data context between Swing events; initial event count = " + myEventCount + - "; current event count = " + currentEventCount); + LOG.error("cannot share data context between Swing events; initial event count = " + myEventCount + "; current event count = " + + currentEventCount); } Component _component = myRef.get(); diff --git a/platform/platform-impl/src/com/intellij/ide/impl/DataValidator.java b/platform/platform-impl/src/com/intellij/ide/impl/DataValidator.java index a2e4e3f4062f..c2b0462573ab 100644 --- a/platform/platform-impl/src/com/intellij/ide/impl/DataValidator.java +++ b/platform/platform-impl/src/com/intellij/ide/impl/DataValidator.java @@ -85,8 +85,8 @@ public abstract class DataValidator { public T[] findInvalid(final String dataId, T[] array, final Object dataSource) { for (T element : array) { if (element == null) { - LOG.assertTrue(false, "Data isn't valid. " + dataId + "=null Provided by: " + dataSource.getClass().getName() + - " (" + dataSource.toString() + ")"); + LOG.error( + "Data isn't valid. " + dataId + "=null Provided by: " + dataSource.getClass().getName() + " (" + dataSource.toString() + ")"); } T invalid = myElementValidator.findInvalid(dataId, element, dataSource); if (invalid != null) { diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java index 520db075c1ad..0048b5fde244 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java @@ -839,7 +839,7 @@ public final class ActionManagerImpl extends ActionManagerEx implements Applicat private static void assertActionIsGroupOrStub(final AnAction action) { if (!(action instanceof ActionGroup || action instanceof ActionStub)) { - LOG.assertTrue(false, "Action : "+action + "; class: "+action.getClass()); + LOG.error("Action : " + action + "; class: " + action.getClass()); } } @@ -1147,7 +1147,7 @@ public final class ActionManagerImpl extends ActionManagerEx implements Applicat public void removeTimerListener(TimerListener listener){ final boolean removed = myTimerListeners.remove(listener); if (!removed) { - LOG.assertTrue(false, "Unknown listener " + listener); + LOG.error("Unknown listener " + listener); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java index 0f444fb37a8b..6c537cb7bcba 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java @@ -99,7 +99,7 @@ public class Utils{ AnAction child = children[i]; if (child == null) { String groupId = ActionManager.getInstance().getId(group); - LOG.assertTrue(false, "action is null: i=" + i + " group=" + group + " group id=" + groupId); + LOG.error("action is null: i=" + i + " group=" + group + " group id=" + groupId); continue; } diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/ComponentStoreImpl.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/ComponentStoreImpl.java index f40da2a5825b..341d3d3caf24 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/ComponentStoreImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/ComponentStoreImpl.java @@ -348,7 +348,7 @@ abstract class ComponentStoreImpl implements IComponentStore { private static String getComponentName(@NotNull final PersistentStateComponent persistentStateComponent) { final State stateSpec = getStateSpec(persistentStateComponent); if (stateSpec == null) { - LOG.assertTrue(false, "Null state spec for " + persistentStateComponent); + LOG.error("Null state spec for " + persistentStateComponent); } return stateSpec.name(); } diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/MergeList.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/MergeList.java index 24a24125fd66..eae0f578e829 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/MergeList.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/MergeList.java @@ -90,7 +90,7 @@ public class MergeList implements ChangeList.Parent, UserDataHolder { rightChanges.add(SimpleChange.fromRanges(ranges[1], new TextRange(rightTextLength, rightTextLength), mergeList.myChanges[1])); leftChanges.add(SimpleChange.fromRanges(ranges[1], new TextRange(leftTextLength, leftTextLength), mergeList.myChanges[0])); } else { - LOG.assertTrue(false, "Left Text: " + leftText + "\n" + "Right Text: " + rightText + "\nBase Text: " + baseText); + LOG.error("Left Text: " + leftText + "\n" + "Right Text: " + rightText + "\nBase Text: " + baseText); } } else { rightChanges.add(SimpleChange.fromRanges(ranges[1], ranges[2], mergeList.myChanges[1])); @@ -98,7 +98,7 @@ public class MergeList implements ChangeList.Parent, UserDataHolder { } else if (ranges[2] == null) { if (ranges[0] == null) { - LOG.assertTrue(false, "Left Text: " + leftText + "\n" + "Right Text: " + rightText + "\nBase Text: " + baseText); + LOG.error("Left Text: " + leftText + "\n" + "Right Text: " + rightText + "\nBase Text: " + baseText); } leftChanges.add(SimpleChange.fromRanges(ranges[1], ranges[0], mergeList.myChanges[0])); } diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/processing/PreferWholeLines.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/processing/PreferWholeLines.java index edcac10b3e3b..2a6a01c10414 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/processing/PreferWholeLines.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/processing/PreferWholeLines.java @@ -30,8 +30,7 @@ class PreferWholeLines implements DiffCorrection { DiffFragment nextFragment = fragments[i + 1]; FragmentSide side = FragmentSide.chooseSide(fragment); if (nextFragment.isOneSide()) { - LOG.assertTrue(false, - "<" + side.getText(fragment) + "> <" + side.getOtherText(nextFragment) + ">"); + LOG.error("<" + side.getText(fragment) + "> <" + side.getOtherText(nextFragment) + ">"); } if (StringUtil.startsWithChar(side.getText(fragment), '\n') && StringUtil.startsWithChar(side.getText(nextFragment), '\n') && diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java index 4c034522dac0..619ae78e7d40 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java @@ -125,7 +125,7 @@ public final class EditorHistoryManager extends AbstractProjectComponent impleme final FileEditor[] editors = editorsWithProviders.getFirst(); final FileEditorProvider[] oldProviders = editorsWithProviders.getSecond(); if (editors.length <= 0) { - LOG.assertTrue(false, "No editors for file " + file.getPresentableUrl()); + LOG.error("No editors for file " + file.getPresentableUrl()); } final FileEditor selectedEditor = editorManager.getSelectedEditor(file); LOG.assertTrue(selectedEditor != null); diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java index 0953b839cf6d..3041414f2323 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java @@ -148,7 +148,7 @@ public final class EditorsSplitters extends JPanel { return res; } else { - LOG.assertTrue(false, comp != null ? comp.getClass().getName() : null); + LOG.error(comp != null ? comp.getClass().getName() : null); return null; } } diff --git a/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java b/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java index bfd46bad00cc..b2b1c86543bc 100644 --- a/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java @@ -308,7 +308,7 @@ public class DumbServiceImpl extends DumbService { final IndexUpdateRunnable nextUpdateRunnable = myUpdatesQueue.pullFirst(); // run next action under already existing progress indicator if (!myActionQueue.offer(new Ref(nextUpdateRunnable.myAction))) { - LOG.assertTrue(false, "Action queue rejected next updateRunnable!"); + LOG.error("Action queue rejected next updateRunnable!"); nextUpdateRunnable.run(); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java index 5fce05c6b919..66d976010ac4 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java @@ -58,7 +58,7 @@ public class Win32Kernel { names.add(info.name); } - return names.toArray(new String[names.size()]); + return ArrayUtil.toStringArray(names); } public boolean exists(String path) { diff --git a/platform/platform-impl/src/com/intellij/ui/EditorComboBox.java b/platform/platform-impl/src/com/intellij/ui/EditorComboBox.java index 1d701013e79c..5b320c544bed 100644 --- a/platform/platform-impl/src/com/intellij/ui/EditorComboBox.java +++ b/platform/platform-impl/src/com/intellij/ui/EditorComboBox.java @@ -29,6 +29,7 @@ import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.TextComponentAccessor; +import com.intellij.util.ArrayUtil; import javax.swing.*; import java.awt.*; @@ -199,7 +200,7 @@ public class EditorComboBox extends JComboBox implements DocumentListener { objects.add(itemAt); } } - setModel(new DefaultComboBoxModel(objects.toArray(new Object[objects.size()]))); + setModel(new DefaultComboBoxModel(ArrayUtil.toObjectArray(objects))); } private class MyEditor implements ComboBoxEditor { diff --git a/platform/platform-impl/src/com/intellij/util/PendingEventDispatcher.java b/platform/platform-impl/src/com/intellij/util/PendingEventDispatcher.java index adffad01cf50..e70784de9bdb 100644 --- a/platform/platform-impl/src/com/intellij/util/PendingEventDispatcher.java +++ b/platform/platform-impl/src/com/intellij/util/PendingEventDispatcher.java @@ -171,8 +171,7 @@ public class PendingEventDispatcher { private void dispatch(Method method, Object[] args) { assertDispatchThread(); if(myCurrentDispatchMethod != null) { - LOG.assertTrue(false, - "Event cannot be raised when dispatching another event is in progress. Dispatching " + myCurrentDispatchMethod.getName()); + LOG.error("Event cannot be raised when dispatching another event is in progress. Dispatching " + myCurrentDispatchMethod.getName()); } method.setAccessible(true); diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/TestSuiteStack.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/TestSuiteStack.java index 7887db9c3c7c..9033ed9ea731 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/TestSuiteStack.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/TestSuiteStack.java @@ -55,13 +55,16 @@ public class TestSuiteStack { @NotNull public SMTestProxy popSuite(final String suiteName) throws EmptyStackException { if (myStack.isEmpty()) { - LOG.assertTrue(false, "Pop error: Test runner tried to close test suite which has been already closed or wasn't started at all. Unexpected suite name [" + suiteName + "]"); + LOG.error( + "Pop error: Test runner tried to close test suite which has been already closed or wasn't started at all. Unexpected suite name [" + + suiteName + "]"); return null; } final SMTestProxy currentSuite = myStack.pop(); if (!suiteName.equals(currentSuite.getName())) { - LOG.assertTrue(false, "Pop error: Unexpected closing suite. Expected [" + suiteName + "] but [" + currentSuite.getName() + "] was found. Rest of stack: " + getSuitePathPresentation()); + LOG.error("Pop error: Unexpected closing suite. Expected [" + suiteName + "] but [" + currentSuite.getName() + + "] was found. Rest of stack: " + getSuitePathPresentation()); return null; } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsTableModel.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsTableModel.java index 274dcba28801..dfd0ba5b6685 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsTableModel.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsTableModel.java @@ -136,7 +136,7 @@ public class StatisticsTableModel extends ListTableModel { public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) { // Setting value is prevented! - LOG.assertTrue(false, "value: " + aValue + " row: " + rowIndex + " column: " + columnIndex); + LOG.error("value: " + aValue + " row: " + rowIndex + " column: " + columnIndex); } @Nullable diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java index e0c0b24009cf..800f286f6b6f 100644 --- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java +++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java @@ -29,6 +29,7 @@ import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Alarm; +import com.intellij.util.ArrayUtil; import com.intellij.util.SystemProperties; import com.intellij.util.ui.UIUtil; import junit.framework.Assert; @@ -230,7 +231,7 @@ public class PlatformTestUtil { if (comparator != null) { ArrayList list = new ArrayList(Arrays.asList(children)); Collections.sort(list, comparator); - children = list.toArray(new Object[list.size()]); + children = ArrayUtil.toObjectArray(list); } for (Object child : children) { currentLine = doPrint(buffer, currentLevel + 1, child, structure, comparator, maxRowCount, currentLine, paddingChar); diff --git a/platform/usageView/src/com/intellij/usages/UsageInfo2UsageAdapter.java b/platform/usageView/src/com/intellij/usages/UsageInfo2UsageAdapter.java index 06ce759a280f..7d10f844cf4b 100644 --- a/platform/usageView/src/com/intellij/usages/UsageInfo2UsageAdapter.java +++ b/platform/usageView/src/com/intellij/usages/UsageInfo2UsageAdapter.java @@ -84,8 +84,7 @@ public class UsageInfo2UsageAdapter implements UsageInModule, UsageInLibrary, Us myLineNumber = getLineNumber(document, startOffset); if (endOffset > document.getTextLength()) { - LOG.assertTrue(false, - "Invalid usage info, psiElement:" + element + " end offset: " + endOffset + " psiFile: " + psiFile.getName()); + LOG.error("Invalid usage info, psiElement:" + element + " end offset: " + endOffset + " psiFile: " + psiFile.getName()); } myRangeMarkers.add(document.createRangeMarker(startOffset, endOffset)); diff --git a/platform/util/src/com/intellij/openapi/diff/impl/highlighting/Util.java b/platform/util/src/com/intellij/openapi/diff/impl/highlighting/Util.java index d0e72eff5b23..1356eb6d20af 100644 --- a/platform/util/src/com/intellij/openapi/diff/impl/highlighting/Util.java +++ b/platform/util/src/com/intellij/openapi/diff/impl/highlighting/Util.java @@ -72,7 +72,7 @@ public class Util { String[] lines1 = splitByLines(fragment.getText1()); String[] lines2 = splitByLines(fragment.getText2()); if (lines1 != null && lines2 != null && lines1.length != lines2.length) { - LOG.assertTrue(false, "1:<" + fragment.getText1() + "> 2:<" + fragment.getText2() + ">"); + LOG.error("1:<" + fragment.getText1() + "> 2:<" + fragment.getText2() + ">"); } int length = lines1 == null ? lines2.length : lines1.length; DiffFragment[] lines = new DiffFragment[length]; diff --git a/platform/util/src/com/intellij/util/ArrayUtil.java b/platform/util/src/com/intellij/util/ArrayUtil.java index 8c8f973b1206..879d4539fffc 100644 --- a/platform/util/src/com/intellij/util/ArrayUtil.java +++ b/platform/util/src/com/intellij/util/ArrayUtil.java @@ -34,14 +34,15 @@ public class ArrayUtil { public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; public static final int [] EMPTY_INT_ARRAY = new int[0]; public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0]; - public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; - public static final String[] EMPTY_STRING_ARRAY = new String[0]; - public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; + @SuppressWarnings({"SSBasedInspection"}) public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; + @SuppressWarnings({"SSBasedInspection"}) public static final String[] EMPTY_STRING_ARRAY = new String[0]; + @SuppressWarnings({"SSBasedInspection"}) public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; public static final long[] EMPTY_LONG_ARRAY = new long[0]; public static final Collection[] EMPTY_COLLECTION_ARRAY = new Collection[0]; public static final CharSequence EMPTY_CHAR_SEQUENCE = new CharArrayCharSequence(EMPTY_CHAR_ARRAY); - public static byte[] realloc (final byte [] array, final int newSize) { + @NotNull + public static byte[] realloc (@NotNull byte [] array, final int newSize) { if (newSize == 0) { return EMPTY_BYTE_ARRAY; } @@ -56,7 +57,8 @@ public class ArrayUtil { return result; } - public static int[] realloc (final int [] array, final int newSize) { + @NotNull + public static int[] realloc (@NotNull int [] array, final int newSize) { if (newSize == 0) { return EMPTY_INT_ARRAY; } @@ -71,13 +73,15 @@ public class ArrayUtil { return result; } - public static int[] append(int[] array, int value) { + @NotNull + public static int[] append(@NotNull int[] array, int value) { array = realloc(array, array.length + 1); array[array.length - 1] = value; return array; } - public static char[] realloc (final char[] array, final int newSize) { + @NotNull + public static char[] realloc (@NotNull char[] array, final int newSize) { if (newSize == 0) { return EMPTY_CHAR_ARRAY; } @@ -117,7 +121,8 @@ public class ArrayUtil { return collection.toArray(new String[collection.size()]); } - public static T[] mergeArrays(T[] a1, T[] a2, Class aClass) { + @NotNull + public static T[] mergeArrays(@NotNull T[] a1, @NotNull T[] a2, @NotNull Class aClass) { if (a1.length == 0) { return a2; } @@ -156,10 +161,12 @@ public class ArrayUtil { * @param src array to which the element should be appended. * @param element object to be appended to the end of src array. */ + @NotNull public static T[] append(@NotNull final T[] src,final T element){ return append(src, element, (Class)src.getClass().getComponentType()); } + @NotNull public static T[] append(@NotNull T[] src, final T element, @NotNull Class componentType) { int length=src.length; T[] result=(T[])Array.newInstance(componentType, length+ 1); diff --git a/platform/util/src/com/intellij/util/ReflectionUtil.java b/platform/util/src/com/intellij/util/ReflectionUtil.java index 394f67ac39f5..0bff817da623 100644 --- a/platform/util/src/com/intellij/util/ReflectionUtil.java +++ b/platform/util/src/com/intellij/util/ReflectionUtil.java @@ -65,10 +65,8 @@ public class ReflectionUtil { final TypeVariable typeVariable = (TypeVariable)resolved; index = ArrayUtil.find(ReflectionCache.getTypeParameters(anInterface), typeVariable); if (index < 0) { - LOG.assertTrue(false, "Cannot resolve type variable:\n" + - "typeVariable = " + typeVariable + "\n" + - "genericDeclaration = " + declarationToString(typeVariable.getGenericDeclaration()) + "\n" + - "searching in " + declarationToString(anInterface)); + LOG.error("Cannot resolve type variable:\n" + "typeVariable = " + typeVariable + "\n" + "genericDeclaration = " + + declarationToString(typeVariable.getGenericDeclaration()) + "\n" + "searching in " + declarationToString(anInterface)); } final Type type = i < genericInterfaces.length ? genericInterfaces[i] : aClass.getGenericSuperclass(); if (type instanceof Class) { diff --git a/platform/util/src/com/intellij/util/containers/VariableWidthIntArray.java b/platform/util/src/com/intellij/util/containers/VariableWidthIntArray.java index ef5cc676d492..f82ca19646ec 100644 --- a/platform/util/src/com/intellij/util/containers/VariableWidthIntArray.java +++ b/platform/util/src/com/intellij/util/containers/VariableWidthIntArray.java @@ -82,13 +82,13 @@ public final class VariableWidthIntArray implements Cloneable { case SHORT: return shortArray[index]; case BYTE: return byteArray[index]; } - LOG.assertTrue( false, "No array allocated" ); + LOG.error("No array allocated"); return 0; } public void put( int index, int value ) { if( value < minValue || value > maxValue ) { - LOG.assertTrue( false, "Value out of domain" ); + LOG.error("Value out of domain"); } switch( arrayType ) { @@ -97,7 +97,7 @@ public final class VariableWidthIntArray implements Cloneable { case BYTE: byteArray[index] = (byte)value; return; } - LOG.assertTrue( false, "No array allocated" ); + LOG.error("No array allocated"); } public Object clone() throws CloneNotSupportedException { @@ -118,7 +118,8 @@ public final class VariableWidthIntArray implements Cloneable { case INT: System.arraycopy( intArray, from, intArray, to, count ); break; case SHORT: System.arraycopy( shortArray, from, shortArray, to, count ); break; case BYTE: System.arraycopy( byteArray, from, byteArray, to, count ); break; - default: LOG.assertTrue( false, "Invalid array type" ); + default: + LOG.error("Invalid array type"); } } diff --git a/platform/util/src/com/intellij/util/xmlb/OptionTagBinding.java b/platform/util/src/com/intellij/util/xmlb/OptionTagBinding.java index 2a7c8e6b9f78..e076e3632735 100644 --- a/platform/util/src/com/intellij/util/xmlb/OptionTagBinding.java +++ b/platform/util/src/com/intellij/util/xmlb/OptionTagBinding.java @@ -18,6 +18,7 @@ package com.intellij.util.xmlb; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.JDOMUtil; +import com.intellij.util.ArrayUtil; import org.jdom.Attribute; import org.jdom.Content; import org.jdom.Element; @@ -87,7 +88,7 @@ class OptionTagBinding implements Binding { } if (children.size() > 0) { - Object value = myBinding.deserialize(accessor.read(o), children.toArray(new Object[children.size()])); + Object value = myBinding.deserialize(accessor.read(o), ArrayUtil.toObjectArray(children)); accessor.write(o, value); } else { diff --git a/platform/vcs-impl/src/com/intellij/ide/actions/StartUseVcsDialog.java b/platform/vcs-impl/src/com/intellij/ide/actions/StartUseVcsDialog.java index 61b699d9281f..7b67aef3f0f5 100644 --- a/platform/vcs-impl/src/com/intellij/ide/actions/StartUseVcsDialog.java +++ b/platform/vcs-impl/src/com/intellij/ide/actions/StartUseVcsDialog.java @@ -19,6 +19,7 @@ import com.intellij.openapi.help.HelpManager; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.MultiLineLabelUI; import com.intellij.openapi.vcs.VcsBundle; +import com.intellij.util.ArrayUtil; import com.intellij.util.ui.UIUtil; import javax.swing.*; @@ -113,7 +114,7 @@ public class StartUseVcsDialog extends DialogWrapper { keys.add(""); keys.addAll(displayNames); Collections.sort(keys); - return keys.toArray(new Object[keys.size()]); + return ArrayUtil.toObjectArray(keys); } private static class VcsCombo extends JComboBox { diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/actions/VcsGroupsWrapper.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/actions/VcsGroupsWrapper.java index 7cbd28e6314f..acdee8ce2017 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/actions/VcsGroupsWrapper.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/actions/VcsGroupsWrapper.java @@ -44,9 +44,8 @@ public class VcsGroupsWrapper extends DefaultActionGroup { 0)); for (AnAction child : children) { if (!(child instanceof StandardVcsGroup)) { - LOG.assertTrue(false, - "Any version control group should extends com.intellij.openapi.vcs.actions.StandardVcsGroup class. Groupd class: " + - child.getClass().getName() + ", group ID: " + ActionManager.getInstance().getId(child)); + LOG.error("Any version control group should extends com.intellij.openapi.vcs.actions.StandardVcsGroup class. Groupd class: " + + child.getClass().getName() + ", group ID: " + ActionManager.getInstance().getId(child)); } else { validChildren.add(child); diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.java index 44c0946f3b13..f476453ee4b3 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.java @@ -390,7 +390,7 @@ public class LineStatusTracker { myRanges.addAll(rangesAfterChange); if (myHighlighterCount != myRanges.size()) { - LOG.assertTrue(false, "Highlighters: " + myHighlighterCount + ", ranges: " + myRanges.size()); + LOG.error("Highlighters: " + myHighlighterCount + ", ranges: " + myRanges.size()); } myRanges = mergeRanges(myRanges); @@ -401,7 +401,7 @@ public class LineStatusTracker { } if (myHighlighterCount != myRanges.size()) { - LOG.assertTrue(false, "Highlighters: " + myHighlighterCount + ", ranges: " + myRanges.size()); + LOG.error("Highlighters: " + myHighlighterCount + ", ranges: " + myRanges.size()); } } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/Range.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/Range.java index 2e341af96700..eba9acb089a3 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/Range.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/Range.java @@ -53,7 +53,7 @@ public class Range { if ((change.deleted > 0) && (change.inserted > 0)) return MODIFIED; if ((change.deleted > 0)) return DELETED; if ((change.inserted > 0)) return INSERTED; - LOG.assertTrue(false, "Unknown change type"); + LOG.error("Unknown change type"); return 0; } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebugSessionTab.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebugSessionTab.java index 4a2be06fd5d3..23129e1810c3 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebugSessionTab.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebugSessionTab.java @@ -40,6 +40,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.registry.Registry; import com.intellij.ui.content.Content; import com.intellij.ui.content.tabs.PinToolwindowTabAction; +import com.intellij.util.ArrayUtil; import com.intellij.xdebugger.XDebugProcess; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XDebuggerBundle; @@ -132,7 +133,7 @@ public class XDebugSessionTab extends DebuggerLogConsoleManagerBase { public XDebugSessionData saveData() { final List watchExpressions = myWatchesView.getWatchExpressions(); - return new XDebugSessionData(watchExpressions.toArray(new String[watchExpressions.size()])); + return new XDebugSessionData(ArrayUtil.toStringArray(watchExpressions)); } public ExecutionConsole getConsole() { diff --git a/plugins/IdeaTestAssistant/src/com/intellij/testAssistant/TestDataNavigationHandler.java b/plugins/IdeaTestAssistant/src/com/intellij/testAssistant/TestDataNavigationHandler.java index 0856f6cd98f3..8682806dc338 100644 --- a/plugins/IdeaTestAssistant/src/com/intellij/testAssistant/TestDataNavigationHandler.java +++ b/plugins/IdeaTestAssistant/src/com/intellij/testAssistant/TestDataNavigationHandler.java @@ -99,7 +99,7 @@ public class TestDataNavigationHandler implements GutterIconNavigationHandler index) return; myLastPacketIndex++; diff --git a/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorerTreeStructure.java b/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorerTreeStructure.java index bcfbce834253..5049c3356a37 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorerTreeStructure.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorerTreeStructure.java @@ -64,7 +64,7 @@ final class AntExplorerTreeStructure extends AbstractTreeStructure { else if (element instanceof AntBuildTarget) { return new AntTargetNodeDescriptor(myProject, parentDescriptor, (AntBuildTargetBase)element); } - LOG.assertTrue(false, "Unknown element for this tree structure " + element); + LOG.error("Unknown element for this tree structure " + element); return null; } diff --git a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/AddFileOrDirectoryAction.java b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/AddFileOrDirectoryAction.java index 827878244f3e..0ad0135e5991 100644 --- a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/AddFileOrDirectoryAction.java +++ b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/AddFileOrDirectoryAction.java @@ -104,7 +104,7 @@ public class AddFileOrDirectoryAction extends ActionOnSelectedElement { Collection roots = new CreateTreeOnFileList(filesToAdd, project, includeAllRoots).getRoots(); if (roots.size() == 0) { - LOG.assertTrue(false, filesToAdd); + LOG.error(filesToAdd.toString()); } if (showDialog){ diff --git a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/IgnoreFileAction.java b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/IgnoreFileAction.java index a16592798c9c..aeef0caf2a9b 100644 --- a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/IgnoreFileAction.java +++ b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/IgnoreFileAction.java @@ -113,9 +113,7 @@ public class IgnoreFileAction extends AnAction { VirtualFile cvsIgnoreFile = CvsVfsUtil.refreshAndfFindChild(parent, CvsUtil.CVS_IGNORE_FILE); if (cvsIgnoreFile == null) { String path = parent.getPath() + "/" + CvsUtil.CVS_IGNORE_FILE; - LOG.assertTrue(false, - String.valueOf(CvsVfsUtil.findFileByPath(path)) + " " + parent.getPath() + " " + - new File(VfsUtil.virtualToIoFile(parent), CvsUtil.CVS_IGNORE_FILE).isFile()); + LOG.error(String.valueOf(CvsVfsUtil.findFileByPath(path)) + " " + parent.getPath() + " " + new File(VfsUtil.virtualToIoFile(parent), CvsUtil.CVS_IGNORE_FILE).isFile()); return; } diff --git a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/config/CvsApplicationLevelConfiguration.java b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/config/CvsApplicationLevelConfiguration.java index cdb94979508b..b807b713baaf 100644 --- a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/config/CvsApplicationLevelConfiguration.java +++ b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/config/CvsApplicationLevelConfiguration.java @@ -147,7 +147,7 @@ public class CvsApplicationLevelConfiguration implements ApplicationComponent, J return result; } catch (Exception ex) { - LOG.assertTrue(false, "userHome = " + userHome + ", presenation = " + presentation); + LOG.error("userHome = " + userHome + ", presenation = " + presentation); return ""; } } diff --git a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/cvsAdd/AddFileOperation.java b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/cvsAdd/AddFileOperation.java index 62fe1b7dec69..dbea13021049 100644 --- a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/cvsAdd/AddFileOperation.java +++ b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/cvsAdd/AddFileOperation.java @@ -45,7 +45,7 @@ public class AddFileOperation extends CvsOperationOnFiles { List fileObjects = command.getFileObjects().getFileObjects(); for (final AbstractFileObject fileObject: fileObjects) { if (fileObject.getParent() == null) { - LOG.assertTrue(false, "Local Root: " + getLocalRootFor(root) + ", Files: " + myFiles); + LOG.error("Local Root: " + getLocalRootFor(root) + ", Files: " + myFiles); } } } diff --git a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/javacvsSpecificImpls/AdminWriterOnCache.java b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/javacvsSpecificImpls/AdminWriterOnCache.java index 32400daadd5b..b77014a99714 100644 --- a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/javacvsSpecificImpls/AdminWriterOnCache.java +++ b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/javacvsSpecificImpls/AdminWriterOnCache.java @@ -118,7 +118,7 @@ public class AdminWriterOnCache implements IAdminWriter { } public void pruneDirectory(DirectoryObject directoryObject, ICvsFileSystem cvsFileSystem) { - LOG.assertTrue(false, "Cannot be called"); + LOG.error("Cannot be called"); } public void editFile(FileObject fileObject, diff --git a/plugins/git4idea/src/org/jetbrains/git4idea/ssh/SSHMain.java b/plugins/git4idea/src/org/jetbrains/git4idea/ssh/SSHMain.java index 991226263ce0..8eb04a347743 100644 --- a/plugins/git4idea/src/org/jetbrains/git4idea/ssh/SSHMain.java +++ b/plugins/git4idea/src/org/jetbrains/git4idea/ssh/SSHMain.java @@ -440,7 +440,7 @@ public class SSHMain { database.addHostkeys(knownHostFile); } final List algorithms = myHost.getHostKeyAlgorithms(); - c.setServerHostKeyAlgorithms(algorithms.toArray(new String[algorithms.size()])); + c.setServerHostKeyAlgorithms(ArrayUtil.toStringArray(algorithms)); } /** @@ -520,7 +520,7 @@ public class SSHMain { return rc; } else { - return result.toArray(new String[result.size()]); + return ArrayUtil.toStringArray(result); } } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parameterInfo/GroovyParameterInfoHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parameterInfo/GroovyParameterInfoHandler.java index 019dfba4f977..a312c60674a0 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parameterInfo/GroovyParameterInfoHandler.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parameterInfo/GroovyParameterInfoHandler.java @@ -68,7 +68,7 @@ public class GroovyParameterInfoHandler implements ParameterInfoHandler knownKeys = new ArrayList(myKnownObjects.keySet()); Collections.sort(knownKeys); diff --git a/plugins/junit/src/com/intellij/execution/junit2/ui/StatisticsTable.java b/plugins/junit/src/com/intellij/execution/junit2/ui/StatisticsTable.java index 2a079c63aac2..bb8eca3b22e2 100644 --- a/plugins/junit/src/com/intellij/execution/junit2/ui/StatisticsTable.java +++ b/plugins/junit/src/com/intellij/execution/junit2/ui/StatisticsTable.java @@ -73,7 +73,7 @@ public class StatisticsTable extends ListTableModel { } public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) { - LOG.assertTrue(false, "value: " + aValue + " row: " + rowIndex + " column: " + columnIndex); + LOG.error("value: " + aValue + " row: " + rowIndex + " column: " + columnIndex); } public boolean isCellEditable(final int rowIndex, final int columnIndex) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesConverter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesConverter.java index 34eb8e1aec71..0bd0966ed633 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesConverter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesConverter.java @@ -312,7 +312,7 @@ public abstract class MavenArtifactCoordinatesConverter extends ResolvingConvert private String[] getGroupIdVariants(MavenProjectIndicesManager manager, MavenDomShortArtifactCoordinates coordinates) { if (DomUtil.hasXml(coordinates.getGroupId())) { Set strings = manager.getGroupIds(); - return strings.toArray(new String[strings.size()]); + return ArrayUtil.toStringArray(strings); } return MavenArtifactUtil.DEFAULT_GROUPS; } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java index 71234c65b98f..37ebc09c5559 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java @@ -28,6 +28,7 @@ import com.intellij.psi.xml.XmlDocument; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import com.intellij.psi.xml.XmlTagChild; +import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.Icons; import com.intellij.util.IncorrectOperationException; @@ -199,7 +200,7 @@ public class MavenPropertyPsiReference extends MavenPsiReference { public Object[] getVariants() { List result = new ArrayList(); collectVariants(result); - return result.toArray(new Object[result.size()]); + return ArrayUtil.toObjectArray(result); } protected void collectVariants(List result) { diff --git a/plugins/properties/src/com/intellij/lang/properties/references/PropertyReferenceBase.java b/plugins/properties/src/com/intellij/lang/properties/references/PropertyReferenceBase.java index 479b6b701bd3..a9300721225b 100644 --- a/plugins/properties/src/com/intellij/lang/properties/references/PropertyReferenceBase.java +++ b/plugins/properties/src/com/intellij/lang/properties/references/PropertyReferenceBase.java @@ -105,7 +105,7 @@ public abstract class PropertyReferenceBase implements PsiPolyVariantReference, else {*/ ElementManipulator manipulator = ElementManipulators.getManipulator(myElement); if (manipulator == null) { - LOG.assertTrue(false, "Cannot find manipulator for " + myElement + " of class " + myElement.getClass()); + LOG.error("Cannot find manipulator for " + myElement + " of class " + myElement.getClass()); } return manipulator.handleContentChange(myElement, getRangeInElement(), newElementName); /*}*/ diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DeleteOptionsDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DeleteOptionsDialog.java index c48319cb8625..6d569fce7b67 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DeleteOptionsDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DeleteOptionsDialog.java @@ -18,6 +18,7 @@ package org.jetbrains.idea.svn.dialogs.browser; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.vcs.VcsConfiguration; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; @@ -92,7 +93,7 @@ public class DeleteOptionsDialog extends DialogWrapper { final ArrayList messages = VcsConfiguration.getInstance(myProject).getRecentMessages(); Collections.reverse(messages); - final String[] model = messages.toArray(new String[messages.size()]); + final String[] model = ArrayUtil.toStringArray(messages); final JComboBox messagesBox = new JComboBox(model); messagesBox.setRenderer(new MessageBoxCellRenderer()); panel.add(messagesBox, gc); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/ImportOptionsDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/ImportOptionsDialog.java index d16e78bb0d3e..6de82420a5d8 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/ImportOptionsDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/ImportOptionsDialog.java @@ -22,6 +22,7 @@ import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.vcs.VcsConfiguration; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.DepthCombo; @@ -165,7 +166,7 @@ public class ImportOptionsDialog extends DialogWrapper implements ActionListener final ArrayList messages = VcsConfiguration.getInstance(myProject).getRecentMessages(); Collections.reverse(messages); - final String[] model = messages.toArray(new String[messages.size()]); + final String[] model = ArrayUtil.toStringArray(messages); final JComboBox messagesBox = new JComboBox(model); messagesBox.setRenderer(new MessageBoxCellRenderer()); panel.add(messagesBox, gc); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/MkdirOptionsDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/MkdirOptionsDialog.java index 5f69a79898f1..0333d4f555e3 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/MkdirOptionsDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/MkdirOptionsDialog.java @@ -19,6 +19,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.vcs.VcsConfiguration; import com.intellij.ui.DocumentAdapter; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import org.tmatesoft.svn.core.SVNException; @@ -64,7 +65,7 @@ public class MkdirOptionsDialog extends DialogWrapper { final ArrayList messages = VcsConfiguration.getInstance(project).getRecentMessages(); Collections.reverse(messages); - final String[] model = messages.toArray(new String[messages.size()]); + final String[] model = ArrayUtil.toStringArray(messages); myMessagesBox.setModel(new DefaultComboBoxModel(model)); myMessagesBox.setRenderer(new MessageBoxCellRenderer()); } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GridDropLocation.java b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GridDropLocation.java index c66cae060f30..d4c89d4fe0ef 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GridDropLocation.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GridDropLocation.java @@ -209,9 +209,8 @@ public class GridDropLocation implements ComponentDropLocation { RadComponent old = container.findComponentInRect(row + relativeRow, column + relativeCol, rowSpan, colSpan); if (old != null) { - LOG.assertTrue(false, - "Drop rectangle not empty: (" + (row + relativeRow) + ", " + (column + relativeCol) - + ", " + rowSpan + ", " + colSpan + "), component ID=" + old.getId()); + LOG.error("Drop rectangle not empty: (" + (row + relativeRow) + ", " + (column + relativeCol) + ", " + rowSpan + ", " + colSpan + + "), component ID=" + old.getId()); } final GridConstraints constraints = c.getConstraints(); diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltContextProvider.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltContextProvider.java index 979dee5ddfd9..45378bd859c6 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltContextProvider.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltContextProvider.java @@ -27,6 +27,7 @@ import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.*; +import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.xml.XmlAttributeDescriptor; import com.intellij.xml.XmlElementDescriptor; @@ -264,7 +265,7 @@ public class XsltContextProvider extends ContextProvider { } //noinspection unchecked - return new Result(names, names.dependencies.toArray(new Object[names.dependencies.size()])); + return new Result(names, ArrayUtil.toObjectArray(names.dependencies)); } }, false); } diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/references/ModeReference.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/references/ModeReference.java index 27b2dfafba7f..b28d84643769 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/references/ModeReference.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/references/ModeReference.java @@ -77,7 +77,7 @@ class ModeReference extends SimpleAttributeReference implements PsiPolyVariantRe final PsiElement[] modes = ResolveUtil.collect(getMatcher().variantMatcher()); l.addAll(Arrays.asList(modes)); } - return l.toArray(new Object[l.size()]); + return ArrayUtil.toObjectArray(l); } return ArrayUtil.EMPTY_OBJECT_ARRAY; } @@ -165,7 +165,7 @@ class ModeReference extends SimpleAttributeReference implements PsiPolyVariantRe lookups.add(new NamespaceLookup(prefix)); } - return lookups.toArray(new Object[lookups.size()]); + return ArrayUtil.toObjectArray(lookups); } public void registerQuickfix(HighlightInfo highlightInfo, PrefixReference psiReference) { diff --git a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java index 1a821147747b..cc56c4838485 100644 --- a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java +++ b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java @@ -235,7 +235,7 @@ public class XPathEvalAction extends XPathAction { } else if (result instanceof Boolean) { Messages.showMessageDialog(result.toString(), "XPath result (Boolean)", Messages.getInformationIcon()); } else { - LOG.assertTrue(false, "Unknown XPath result: " + result); + LOG.error("Unknown XPath result: " + result); } } catch (XPathSyntaxException e) { LOG.debug(e); diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java b/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java index 7912652468eb..234de3afe58c 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java @@ -38,7 +38,7 @@ public abstract class DomAnchorImpl { public static DomAnchorImpl createAnchor(@NotNull T t) { final DomElement parent = t.getParent(); if (parent == null) { - LOG.assertTrue(false, "Parent null: " + t); + LOG.error("Parent null: " + t); } if (parent instanceof DomFileElementImpl) { @@ -73,7 +73,7 @@ public abstract class DomAnchorImpl { } } diag.append("Child name: ").append(t.getXmlElementName()).append(";").append(t.getXmlElementNamespaceKey()); - LOG.assertTrue(false, diag); + LOG.error(diag.toString()); } return new IndexedAnchor(parentAnchor, description, index); } diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/DomFileElementImpl.java b/xml/dom-impl/src/com/intellij/util/xml/impl/DomFileElementImpl.java index b03360b4bc12..a4d19f215895 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/DomFileElementImpl.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/DomFileElementImpl.java @@ -270,7 +270,7 @@ public class DomFileElementImpl implements DomFileElement< if (fileElement == null) { final FileDescriptionCachedValueProvider provider = myManager.getOrCreateCachedValueProvider(myFile); String s = provider.getFileElementWithLogging(); - LOG.assertTrue(false, "Null, log=" + s); + LOG.error("Null, log=" + s); } else { assert false: this + " does not equal to " + fileElement; } diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java b/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java index fca7ce5da904..c7decb64abd3 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java @@ -79,7 +79,7 @@ public abstract class DomInvocationHandler" + parameter.getName()); + LOG.error("No converter specified: String<->" + parameter.getName()); } return converter; } @@ -139,7 +139,7 @@ public abstract class DomInvocationHandler(result[0], deps.toArray(new Object[deps.size()])); + return new CachedValueProvider.Result(result[0], ArrayUtil.toObjectArray(deps)); } finally { targetElement.putUserData(EVALUATION_IN_PROCESS, null); diff --git a/xml/impl/src/com/intellij/xml/impl/ExternalDocumentValidator.java b/xml/impl/src/com/intellij/xml/impl/ExternalDocumentValidator.java index da409f4e1e23..17e875218422 100644 --- a/xml/impl/src/com/intellij/xml/impl/ExternalDocumentValidator.java +++ b/xml/impl/src/com/intellij/xml/impl/ExternalDocumentValidator.java @@ -316,14 +316,9 @@ public class ExternalDocumentValidator { private static void assertValidElement(PsiElement currentElement, PsiElement originalElement, String message) { if (currentElement==null) { XmlTag tag = PsiTreeUtil.getParentOfType(originalElement, XmlTag.class); - LOG.assertTrue( - false, - "The validator message:"+ message+ " is bound to null node,\n" + - "initial element:"+originalElement.getText()+",\n"+ - "parent:" + originalElement.getParent()+",\n" + - "tag:" + (tag != null? tag.getText():"null") + ",\n" + - "offset in tag: " + (originalElement.getTextOffset() - (tag == null ? 0 : tag.getTextOffset())) - ); + LOG.error("The validator message:" + message + " is bound to null node,\n" + "initial element:" + originalElement.getText() + ",\n" + + "parent:" + originalElement.getParent() + ",\n" + "tag:" + (tag != null ? tag.getText() : "null") + ",\n" + + "offset in tag: " + (originalElement.getTextOffset() - (tag == null ? 0 : tag.getTextOffset()))); } } From d1135a6d9b3ccbd5c2ab415274cfb87e0851f4d0 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Tue, 16 Feb 2010 15:45:24 +0300 Subject: [PATCH 15/93] diagnostics --- .../com/intellij/psi/impl/search/AnnotatedElementsSearcher.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/java-impl/src/com/intellij/psi/impl/search/AnnotatedElementsSearcher.java b/java/java-impl/src/com/intellij/psi/impl/search/AnnotatedElementsSearcher.java index 5621622de856..f5f32578f121 100644 --- a/java/java-impl/src/com/intellij/psi/impl/search/AnnotatedElementsSearcher.java +++ b/java/java-impl/src/com/intellij/psi/impl/search/AnnotatedElementsSearcher.java @@ -79,7 +79,7 @@ public class AnnotatedElementsSearcher implements QueryExecutor Date: Tue, 16 Feb 2010 15:58:56 +0300 Subject: [PATCH 16/93] cleanup --- .../intellij/refactoring/rename/RenameViewDescriptor.java | 5 +++-- .../com/intellij/openapi/execution/ParametersListTest.java | 2 +- .../util/src/com/intellij/openapi/util/JDOMExternalizer.java | 2 +- .../idea/maven/execution/EditMavenPropertyDialog.java | 2 +- .../uiDesigner/radComponents/LayoutManagerRegistry.java | 2 +- 5 files changed, 7 insertions(+), 6 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameViewDescriptor.java b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameViewDescriptor.java index 73766302979a..734d4a2ba264 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameViewDescriptor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameViewDescriptor.java @@ -63,8 +63,9 @@ class RenameViewDescriptor implements UsageViewDescriptor{ } - myProcessedElementsHeader = StringUtil.join(processedElementsHeaders.toArray(ArrayUtil.EMPTY_STRING_ARRAY),", "); - myCodeReferencesText = RefactoringBundle.message("references.in.code.to.0", StringUtil.join(codeReferences.toArray(ArrayUtil.EMPTY_STRING_ARRAY), ", ")); + myProcessedElementsHeader = StringUtil.join(ArrayUtil.toStringArray(processedElementsHeaders), ", "); + myCodeReferencesText = RefactoringBundle.message("references.in.code.to.0", StringUtil.join(ArrayUtil.toStringArray(codeReferences), + ", ")); } @NotNull diff --git a/platform/platform-impl/testSrc/com/intellij/openapi/execution/ParametersListTest.java b/platform/platform-impl/testSrc/com/intellij/openapi/execution/ParametersListTest.java index 3dc85de6c6c4..d792a353759e 100644 --- a/platform/platform-impl/testSrc/com/intellij/openapi/execution/ParametersListTest.java +++ b/platform/platform-impl/testSrc/com/intellij/openapi/execution/ParametersListTest.java @@ -38,7 +38,7 @@ public class ParametersListTest extends TestCase { private void checkTokenizer(String parmsString, String[] expected) { ParametersList params = new ParametersList(); params.addParametersString(parmsString); - String[] strings = params.getList().toArray(ArrayUtil.EMPTY_STRING_ARRAY); + String[] strings = ArrayUtil.toStringArray(params.getList()); CHECK.compareAll(expected, strings); } } diff --git a/platform/util/src/com/intellij/openapi/util/JDOMExternalizer.java b/platform/util/src/com/intellij/openapi/util/JDOMExternalizer.java index 4b23c3a6f12a..72dc236f0935 100644 --- a/platform/util/src/com/intellij/openapi/util/JDOMExternalizer.java +++ b/platform/util/src/com/intellij/openapi/util/JDOMExternalizer.java @@ -74,7 +74,7 @@ public class JDOMExternalizer { else { mapRoot = root; } - final String[] names = map.keySet().toArray(ArrayUtil.EMPTY_STRING_ARRAY); + final String[] names = ArrayUtil.toStringArray(map.keySet()); Arrays.sort(names); for (String name : names) { @NonNls final Element element = new Element(entryName); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java index 09a96bd0c2a6..9ef8c87e6679 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java @@ -76,7 +76,7 @@ public class EditMavenPropertyDialog extends DialogWrapper { } private void fillAvailableProperties() { - String[] keys = myAvailableProperties.keySet().toArray(ArrayUtil.EMPTY_STRING_ARRAY); + String[] keys = ArrayUtil.toStringArray(myAvailableProperties.keySet()); myNameBox.setModel(new DefaultComboBoxModel(keys)); } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/LayoutManagerRegistry.java b/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/LayoutManagerRegistry.java index b4d381532115..a4b79b719573 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/LayoutManagerRegistry.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/LayoutManagerRegistry.java @@ -61,7 +61,7 @@ public class LayoutManagerRegistry { } public static String[] getLayoutManagerNames() { - final String[] layoutManagerNames = ourLayoutManagerRegistry.keySet().toArray(ArrayUtil.EMPTY_STRING_ARRAY); + final String[] layoutManagerNames = ArrayUtil.toStringArray(ourLayoutManagerRegistry.keySet()); Arrays.sort(layoutManagerNames); return layoutManagerNames; } From 17b0ee4319777a672563af95f885db42e5391749 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Wed, 17 Feb 2010 12:15:11 +0300 Subject: [PATCH 17/93] cleanup --- .../com/intellij/debugger/engine/SuspendContextImpl.java | 2 +- .../intellij/codeInsight/daemon/LineMarkerProviders.java | 4 +++- .../com/intellij/codeInsight/lookup/impl/LookupImpl.java | 7 ++++--- .../src/com/intellij/openapi/editor/impl/EditorImpl.java | 2 +- .../util/src/com/intellij/openapi/diagnostic/Logger.java | 3 +++ .../com/intellij/xml/impl/schema/XmlNSDescriptorImpl.java | 2 +- 6 files changed, 13 insertions(+), 7 deletions(-) diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java index aa5128b9bbab..2d7baf56ee96 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java @@ -102,7 +102,7 @@ public abstract class SuspendContextImpl implements SuspendContext { private void assertNotResumed() { if (myIsResumed) { if (myDebugProcess.isAttached()) { - LOG.assertTrue(false, "Cannot access SuspendContext. SuspendContext is resumed."); + LOG.error("Cannot access SuspendContext. SuspendContext is resumed."); } } } diff --git a/platform/lang-api/src/com/intellij/codeInsight/daemon/LineMarkerProviders.java b/platform/lang-api/src/com/intellij/codeInsight/daemon/LineMarkerProviders.java index 1e6734d10156..05974940c789 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/daemon/LineMarkerProviders.java +++ b/platform/lang-api/src/com/intellij/codeInsight/daemon/LineMarkerProviders.java @@ -17,14 +17,16 @@ package com.intellij.codeInsight.daemon; import com.intellij.lang.LanguageExtension; +import org.jetbrains.annotations.NonNls; /** * @author yole */ public class LineMarkerProviders extends LanguageExtension { public static LineMarkerProviders INSTANCE = new LineMarkerProviders(); + @NonNls public static final String EP_NAME = "com.intellij.codeInsight.lineMarkerProvider"; private LineMarkerProviders() { - super("com.intellij.codeInsight.lineMarkerProvider"); + super(EP_NAME); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java index f691ed92aac2..1c1ddc61914e 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java @@ -424,7 +424,8 @@ public class LookupImpl extends LightweightHint implements Lookup, Disposable { Dimension dim = getComponent().getPreferredSize(); int lookupStart = getLookupStart(); if (lookupStart < 0) { - LOG.assertTrue(false, lookupStart + "; minprefix=" + myMinPrefixLength + "; offset=" + myEditor.getCaretModel().getOffset() + "; element=" + getPsiElement()); + LOG.error(lookupStart + "; minprefix=" + myMinPrefixLength + "; offset=" + myEditor.getCaretModel().getOffset() + "; element=" + + getPsiElement()); } LogicalPosition pos = myEditor.offsetToLogicalPosition(lookupStart); @@ -434,7 +435,7 @@ public class LookupImpl extends LightweightHint implements Lookup, Disposable { JComponent internalComponent = myEditor.getContentComponent(); final JRootPane rootPane = editorComponent.getRootPane(); if (rootPane == null) { - LOG.assertTrue(false, myArranger); + LOG.error(myArranger); } JLayeredPane layeredPane = rootPane.getLayeredPane(); Point layeredPanePoint=SwingUtilities.convertPoint(internalComponent,location, layeredPane); @@ -921,7 +922,7 @@ public class LookupImpl extends LightweightHint implements Lookup, Disposable { if (isVisible() && !ApplicationManager.getApplication().isUnitTestMode()) { if (myEditor.getComponent().getRootPane() == null) { - LOG.assertTrue(false, "Null root pane"); + LOG.error("Null root pane"); } Point point = calculatePosition(); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java index f0b00ade31cd..143acf9b0642 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java @@ -2041,7 +2041,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi if (fontType == Font.ITALIC) return myItalicFontMetrics; if (fontType == Font.BOLD + Font.ITALIC) return myBoldItalicFontMetrics; - LOG.assertTrue(false, "Unknown font type: " + fontType); + LOG.error("Unknown font type: " + fontType); return myPlainFontMetrics; } diff --git a/platform/util/src/com/intellij/openapi/diagnostic/Logger.java b/platform/util/src/com/intellij/openapi/diagnostic/Logger.java index 4ed1375bb24a..e86bbe89e9f6 100644 --- a/platform/util/src/com/intellij/openapi/diagnostic/Logger.java +++ b/platform/util/src/com/intellij/openapi/diagnostic/Logger.java @@ -47,6 +47,9 @@ public abstract class Logger { public void error(@NonNls String message) { error(message, new Throwable(), ArrayUtil.EMPTY_STRING_ARRAY); } + public void error(Object message) { + error(String.valueOf(message)); + } public void error(@NonNls String message, @NonNls String... details) { error(message, new Throwable(), details); diff --git a/xml/impl/src/com/intellij/xml/impl/schema/XmlNSDescriptorImpl.java b/xml/impl/src/com/intellij/xml/impl/schema/XmlNSDescriptorImpl.java index afff733e8c73..1b8f70bc81c6 100644 --- a/xml/impl/src/com/intellij/xml/impl/schema/XmlNSDescriptorImpl.java +++ b/xml/impl/src/com/intellij/xml/impl/schema/XmlNSDescriptorImpl.java @@ -915,7 +915,7 @@ public class XmlNSDescriptorImpl implements XmlNSDescriptor,Validator Date: Wed, 17 Feb 2010 12:29:19 +0300 Subject: [PATCH 18/93] cleanup --- .../ide/util/gotoByName/DefaultSymbolNavigationContributor.java | 2 +- .../src/com/intellij/psi/impl/compiled/ClsParsingUtil.java | 2 +- .../introduceParameter/IntroduceParameterProcessor.java | 2 +- java/openapi/src/com/intellij/psi/util/TypeConversionUtil.java | 2 +- .../src/com/intellij/formatting/InitialInfoBuilder.java | 2 +- .../com/intellij/pom/references/PomReferenceServiceImpl.java | 2 +- .../src/com/intellij/psi/impl/SharedPsiElementImplUtil.java | 2 +- platform/util/src/com/intellij/openapi/util/IconLoader.java | 2 +- .../intellij/cvsSupport2/actions/AddFileOrDirectoryAction.java | 2 +- xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/java/java-impl/src/com/intellij/ide/util/gotoByName/DefaultSymbolNavigationContributor.java b/java/java-impl/src/com/intellij/ide/util/gotoByName/DefaultSymbolNavigationContributor.java index fb5a995ba555..beba42382ee0 100644 --- a/java/java-impl/src/com/intellij/ide/util/gotoByName/DefaultSymbolNavigationContributor.java +++ b/java/java-impl/src/com/intellij/ide/util/gotoByName/DefaultSymbolNavigationContributor.java @@ -136,7 +136,7 @@ public class DefaultSymbolNavigationContributor implements ChooseByNameContribut return 3; } else{ - LOG.error(element.toString()); + LOG.error(element); return 0; } } diff --git a/java/java-impl/src/com/intellij/psi/impl/compiled/ClsParsingUtil.java b/java/java-impl/src/com/intellij/psi/impl/compiled/ClsParsingUtil.java index d0efe8a5b65c..b9a9a07350a5 100644 --- a/java/java-impl/src/com/intellij/psi/impl/compiled/ClsParsingUtil.java +++ b/java/java-impl/src/com/intellij/psi/impl/compiled/ClsParsingUtil.java @@ -63,7 +63,7 @@ public class ClsParsingUtil { return new ClsLiteralExpressionImpl(parent, exprText, expr.getType(), value); //it seems ok to make literal expression with non-literal text } } - LOG.error(expr.toString()); + LOG.error(expr); return null; } } diff --git a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java index 94b79585d4de..0ae7342287fd 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java @@ -511,7 +511,7 @@ public class IntroduceParameterProcessor extends BaseRefactoringProcessor implem removeParametersFromCall(argList); } else { - LOG.error(element.getParent().toString()); + LOG.error(element.getParent()); } } diff --git a/java/openapi/src/com/intellij/psi/util/TypeConversionUtil.java b/java/openapi/src/com/intellij/psi/util/TypeConversionUtil.java index deeacf849071..1647efb410fe 100644 --- a/java/openapi/src/com/intellij/psi/util/TypeConversionUtil.java +++ b/java/openapi/src/com/intellij/psi/util/TypeConversionUtil.java @@ -685,7 +685,7 @@ public class TypeConversionUtil { IS_ASSIGNABLE_BIT_SET[rightTypeIndex][leftTypeIndex]; } if (!(right instanceof PsiClassType)) { - LOG.error(right.toString()); + LOG.error(right); } if (left instanceof PsiPrimitiveType) { return isUnboxable((PsiPrimitiveType)left, (PsiClassType)right); diff --git a/platform/lang-impl/src/com/intellij/formatting/InitialInfoBuilder.java b/platform/lang-impl/src/com/intellij/formatting/InitialInfoBuilder.java index a95646da5554..7f99f4858127 100644 --- a/platform/lang-impl/src/com/intellij/formatting/InitialInfoBuilder.java +++ b/platform/lang-impl/src/com/intellij/formatting/InitialInfoBuilder.java @@ -315,6 +315,6 @@ class InitialInfoBuilder { buffer.append('\n'); } - LOG.error(buffer.toString()); + LOG.error(buffer); } } diff --git a/platform/lang-impl/src/com/intellij/pom/references/PomReferenceServiceImpl.java b/platform/lang-impl/src/com/intellij/pom/references/PomReferenceServiceImpl.java index 2c4088c9e48e..9c7be766862b 100644 --- a/platform/lang-impl/src/com/intellij/pom/references/PomReferenceServiceImpl.java +++ b/platform/lang-impl/src/com/intellij/pom/references/PomReferenceServiceImpl.java @@ -127,7 +127,7 @@ public class PomReferenceServiceImpl extends PomReferenceService { @SuppressWarnings({"unchecked"}) final PomReferenceProvider provider = trinity.getFirst(); for (PomReference reference : provider.getReferencesByElement(context, trinity.getSecond())) { if (reference == null) { - LOG.error(context.toString()); + LOG.error(context); } if (offsetMatches(offset, reference)) { result.add(reference); diff --git a/platform/lang-impl/src/com/intellij/psi/impl/SharedPsiElementImplUtil.java b/platform/lang-impl/src/com/intellij/psi/impl/SharedPsiElementImplUtil.java index da6835d54a42..abf7f58357fa 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/SharedPsiElementImplUtil.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/SharedPsiElementImplUtil.java @@ -65,7 +65,7 @@ public class SharedPsiElementImplUtil { private static void addReferences(int offset, PsiElement element, final Collection outReferences) { for (final PsiReference reference : element.getReferences()) { if (reference == null) { - LOG.error(element.toString()); + LOG.error(element); } final TextRange range = reference.getRangeInElement(); if (range.getStartOffset() <= offset && offset <= range.getEndOffset()) { diff --git a/platform/util/src/com/intellij/openapi/util/IconLoader.java b/platform/util/src/com/intellij/openapi/util/IconLoader.java index ded2a4dc6776..5ce17117a722 100644 --- a/platform/util/src/com/intellij/openapi/util/IconLoader.java +++ b/platform/util/src/com/intellij/openapi/util/IconLoader.java @@ -170,7 +170,7 @@ public final class IconLoader { Icon disabledIcon = ourIcon2DisabledIcon.get(icon); if (disabledIcon == null) { if (!ImageLoader.isGoodSize(icon)) { - LOG.error(icon.toString()); // # 22481 + LOG.error(icon); // # 22481 return EMPTY_ICON; } final BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); diff --git a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/AddFileOrDirectoryAction.java b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/AddFileOrDirectoryAction.java index 0ad0135e5991..727dd4574bd5 100644 --- a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/AddFileOrDirectoryAction.java +++ b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/AddFileOrDirectoryAction.java @@ -104,7 +104,7 @@ public class AddFileOrDirectoryAction extends ActionOnSelectedElement { Collection roots = new CreateTreeOnFileList(filesToAdd, project, includeAllRoots).getRoots(); if (roots.size() == 0) { - LOG.error(filesToAdd.toString()); + LOG.error(filesToAdd); } if (showDialog){ diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java b/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java index 234de3afe58c..4971ded53d23 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java @@ -73,7 +73,7 @@ public abstract class DomAnchorImpl { } } diag.append("Child name: ").append(t.getXmlElementName()).append(";").append(t.getXmlElementNamespaceKey()); - LOG.error(diag.toString()); + LOG.error(diag); } return new IndexedAnchor(parentAnchor, description, index); } From 1391fc7c8a63461d4c045c11e4ebcc97a2f0c93f Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Wed, 17 Feb 2010 13:32:50 +0300 Subject: [PATCH 19/93] checkcanceled --- .../cache/impl/IndexCacheManagerImpl.java | 35 ++++++++++--------- .../DuplicateStringLiteralInspection.java | 27 ++++++++------ 2 files changed, 35 insertions(+), 27 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/psi/impl/cache/impl/IndexCacheManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/cache/impl/IndexCacheManagerImpl.java index c2f9254dad6d..9585b99a6bee 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/cache/impl/IndexCacheManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/cache/impl/IndexCacheManagerImpl.java @@ -20,6 +20,7 @@ import com.intellij.ide.caches.CacheUpdater; import com.intellij.injected.editor.VirtualFileWindow; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; @@ -78,6 +79,23 @@ public class IndexCacheManagerImpl implements CacheManager{ } public boolean processFilesWithWord(@NotNull final Processor psiFileProcessor, @NotNull final String word, final short occurrenceMask, @NotNull final GlobalSearchScope scope, final boolean caseSensitively) { + final Set vFiles = new THashSet(); + final GlobalSearchScope projectScope = GlobalSearchScope.allScope(myProject); + ApplicationManager.getApplication().runReadAction(new Runnable() { + public void run() { + FileBasedIndex.getInstance().processValues(IdIndex.NAME, new IdIndexEntry(word, caseSensitively), null, new FileBasedIndex.ValueProcessor() { + public boolean process(final VirtualFile file, final Integer value) { + ProgressManager.checkCanceled(); + final int mask = value.intValue(); + if ((mask & occurrenceMask) != 0) { + vFiles.add(file); + } + return true; + } + }, projectScope); + } + }); + final ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex(); final Processor virtualFileProcessor = new Processor() { @@ -97,29 +115,14 @@ public class IndexCacheManagerImpl implements CacheManager{ } }; - final Set vFiles = new THashSet(); - final GlobalSearchScope projectScope = GlobalSearchScope.allScope(myProject); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - FileBasedIndex.getInstance().processValues(IdIndex.NAME, new IdIndexEntry(word, caseSensitively), null, new FileBasedIndex.ValueProcessor() { - public boolean process(final VirtualFile file, final Integer value) { - final int mask = value.intValue(); - if ((mask & occurrenceMask) != 0) { - vFiles.add(file); - } - return true; - } - }, projectScope); - } - }); // IMPORTANT!!! // Since implementation of virtualFileProcessor.process() may call indices dierctly or indirectly, // we cannot call it inside FileBasedIndex.processValues() method // If we do, deadlocks are possible (IDEADEV-42137). So first we obtain files with the word specified, // and then process them not holding indices' read lock. - for (VirtualFile vFile : vFiles) { + ProgressManager.checkCanceled(); if (!virtualFileProcessor.process(vFile)) { return false; } diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/duplicateStringLiteral/DuplicateStringLiteralInspection.java b/plugins/java-i18n/src/com/intellij/codeInspection/duplicateStringLiteral/DuplicateStringLiteralInspection.java index b32d1cb7625f..f24409ca70c0 100644 --- a/plugins/java-i18n/src/com/intellij/codeInspection/duplicateStringLiteral/DuplicateStringLiteralInspection.java +++ b/plugins/java-i18n/src/com/intellij/codeInspection/duplicateStringLiteral/DuplicateStringLiteralInspection.java @@ -21,6 +21,7 @@ import com.intellij.codeInspection.*; import com.intellij.codeInspection.ex.BaseLocalInspectionTool; import com.intellij.codeInspection.i18n.JavaI18nUtil; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.text.StringUtil; @@ -111,27 +112,31 @@ public class DuplicateStringLiteralInspection extends BaseLocalInspectionTool { Set resultFiles = null; for (String word : words) { - if (word.length() >= MIN_STRING_LENGTH) { - final Set files = new THashSet(); - searchHelper.processAllFilesWithWordInLiterals(word, scope, new CommonProcessors.CollectProcessor(files)); - if (resultFiles == null) { - resultFiles = files; - } - else { - resultFiles.retainAll(files); - } - if (resultFiles.isEmpty()) return; + if (word.length() < MIN_STRING_LENGTH) { + continue; } + ProgressManager.checkCanceled(); + final Set files = new THashSet(); + searchHelper.processAllFilesWithWordInLiterals(word, scope, new CommonProcessors.CollectProcessor(files)); + if (resultFiles == null) { + resultFiles = files; + } + else { + resultFiles.retainAll(files); + } + if (resultFiles.isEmpty()) return; } if (resultFiles == null || resultFiles.isEmpty()) return; final List foundExpr = new ArrayList(); for (PsiFile file : resultFiles) { + ProgressManager.checkCanceled(); CharSequence text = file.getViewProvider().getContents(); StringSearcher searcher = new StringSearcher(stringToFind, true, true); for (int offset = LowLevelSearchUtil.searchWord(text, 0, text.length(), searcher); offset >= 0; offset = LowLevelSearchUtil.searchWord(text, offset + searcher.getPattern().length(), text.length(), searcher) ) { + ProgressManager.checkCanceled(); PsiElement element = file.findElementAt(offset); if (element == null || !(element.getParent() instanceof PsiLiteralExpression)) continue; PsiLiteralExpression expression = (PsiLiteralExpression)element.getParent(); @@ -143,6 +148,7 @@ public class DuplicateStringLiteralInspection extends BaseLocalInspectionTool { if (foundExpr.isEmpty()) return; Set classes = new THashSet(); for (PsiElement aClass : foundExpr) { + ProgressManager.checkCanceled(); do { aClass = PsiTreeUtil.getParentOfType(aClass, PsiClass.class); } @@ -168,7 +174,6 @@ public class DuplicateStringLiteralInspection extends BaseLocalInspectionTool { (thisFile ? " " + InspectionsBundle.message("inspection.duplicates.message.in.this.file") : ""); } }, ", " + BR); - } else { classList = StringUtil.join(tenClassesMost, new Function() { From 8dc5a61beeb561b5220dca693143315ba9c56372 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Wed, 17 Feb 2010 13:46:22 +0300 Subject: [PATCH 20/93] http://ea.jetbrains.com/browser/ea_problems/18753 --- .../psi/impl/smartPointers/SelfElementInfo.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SelfElementInfo.java b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SelfElementInfo.java index ae9784c0063d..d72a009ef33a 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SelfElementInfo.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SelfElementInfo.java @@ -21,7 +21,11 @@ import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.*; +import com.intellij.psi.PsiDocumentManager; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiManager; +import org.jetbrains.annotations.NotNull; /** * User: cdr @@ -111,7 +115,7 @@ class SelfElementInfo implements SmartPointerElementInfo { return null; } - public static PsiFile restoreFile(PsiFile file, Project project) { + public static PsiFile restoreFile(PsiFile file,@NotNull Project project) { if (file == null) return null; if (file.isValid()) return file; VirtualFile virtualFile = file.getVirtualFile(); @@ -120,7 +124,7 @@ class SelfElementInfo implements SmartPointerElementInfo { if (vParent == null || !vParent.isDirectory()) return null; String name = file.getName(); VirtualFile child = vParent.findChild(name); - if (child == null) return null; + if (child == null || !child.isValid()) return null; file = PsiManager.getInstance(project).findFile(child); if (file == null || !file.isValid()) return null; return file; From fbd3ae562a29e87a30838bb9299511832892259d Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Wed, 17 Feb 2010 14:44:25 +0300 Subject: [PATCH 21/93] NPE --- .../module/impl/scopes/LibraryRuntimeClasspathScope.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/openapi/module/impl/scopes/LibraryRuntimeClasspathScope.java b/platform/lang-impl/src/com/intellij/openapi/module/impl/scopes/LibraryRuntimeClasspathScope.java index a749b352e4a4..3f8d0c76c902 100644 --- a/platform/lang-impl/src/com/intellij/openapi/module/impl/scopes/LibraryRuntimeClasspathScope.java +++ b/platform/lang-impl/src/com/intellij/openapi/module/impl/scopes/LibraryRuntimeClasspathScope.java @@ -52,9 +52,9 @@ public class LibraryRuntimeClasspathScope extends GlobalSearchScope { public boolean equals(Object object) { if (object == this) return true; - if (object.getClass() != LibraryRuntimeClasspathScope.class) return false; + if (object == null || object.getClass() != LibraryRuntimeClasspathScope.class) return false; - final LibraryRuntimeClasspathScope that = ((LibraryRuntimeClasspathScope)object); + final LibraryRuntimeClasspathScope that = (LibraryRuntimeClasspathScope)object; return that.myModules.equals(myModules); } From 67512435b2b41f6e58463af38a8f2fa17563f022 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Wed, 17 Feb 2010 15:16:20 +0300 Subject: [PATCH 22/93] array type can be null --- java/java-impl/src/com/intellij/slicer/CanItBeNullAction.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/java-impl/src/com/intellij/slicer/CanItBeNullAction.java b/java/java-impl/src/com/intellij/slicer/CanItBeNullAction.java index 4dddb17afc00..8ab184d66e97 100644 --- a/java/java-impl/src/com/intellij/slicer/CanItBeNullAction.java +++ b/java/java-impl/src/com/intellij/slicer/CanItBeNullAction.java @@ -54,7 +54,7 @@ public class CanItBeNullAction extends AnAction { else { type = null; } - return type instanceof PsiClassType; + return type instanceof PsiClassType || type instanceof PsiArrayType; } @Override From c9a180abf758c37b56d263f3388e8949cb2adb32 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Wed, 17 Feb 2010 16:48:57 +0300 Subject: [PATCH 23/93] do not run annotators and injectors in performance test --- .../tree/injected/JavaConcatenationInjectorManager.java | 6 +++--- .../source/tree/injected/InjectedLanguageManagerImpl.java | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java index f067d7eb25e0..a4603ae44544 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java @@ -150,6 +150,7 @@ public class JavaConcatenationInjectorManager implements ProjectComponent, Modif } private static final Key> INJECTED_PSI_IN_CONCATENATION = Key.create("INJECTED_PSI_IN_CONCATENATION"); + private final Concatenation2InjectorAdapter myConcatenation2InjectorAdapter = new Concatenation2InjectorAdapter(); private class Concatenation2InjectorAdapter implements MultiHostInjector { public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) { if (myConcatenationInjectors.isEmpty()) return; @@ -206,9 +207,8 @@ public class JavaConcatenationInjectorManager implements ProjectComponent, Modif } } else { - MultiHostInjector adapter = new Concatenation2InjectorAdapter(); - if (myRegisteredConcatenationAdapter.compareAndSet(null, adapter)) { - myInjectedLanguageManager.registerMultiHostInjector(adapter); + if (myRegisteredConcatenationAdapter.compareAndSet(null, myConcatenation2InjectorAdapter)) { + myInjectedLanguageManager.registerMultiHostInjector(myConcatenation2InjectorAdapter); } } } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageManagerImpl.java index 6dbea2e861e1..a03d3c5e03b8 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageManagerImpl.java @@ -65,7 +65,7 @@ public class InjectedLanguageManagerImpl extends InjectedLanguageManager { myProject = project; myDumbService = dumbService; - final ExtensionPoint multiPoint = Extensions.getArea(project).getExtensionPoint(MULTIHOST_INJECTOR_EP_NAME); + final ExtensionPoint multiPoint = Extensions.getArea(project).getExtensionPoint(MultiHostInjector.MULTIHOST_INJECTOR_EP_NAME); multiPoint.addExtensionPointListener(new ExtensionPointListener() { public void extensionAdded(MultiHostInjector injector, @Nullable PluginDescriptor pluginDescriptor) { registerMultiHostInjector(injector); From 2b21c5f0cb4ab7d194e8aa91c0b4659ff42add3f Mon Sep 17 00:00:00 2001 From: Maxim Shafirov Date: Wed, 17 Feb 2010 19:31:48 +0300 Subject: [PATCH 24/93] testdata updated. --- .../introduceParameterObject/copyJavadoc/before/Test.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/java-tests/testData/refactoring/introduceParameterObject/copyJavadoc/before/Test.java b/java/java-tests/testData/refactoring/introduceParameterObject/copyJavadoc/before/Test.java index 124187af21df..f9260f0d7dc6 100644 --- a/java/java-tests/testData/refactoring/introduceParameterObject/copyJavadoc/before/Test.java +++ b/java/java-tests/testData/refactoring/introduceParameterObject/copyJavadoc/before/Test.java @@ -8,4 +8,4 @@ class Test { } void bar(String s){} -} \ No newline at end of file +} From 91aef11320604f43d20fd90d2e2dea2c77e48916 Mon Sep 17 00:00:00 2001 From: "Maxim.Mossienko" Date: Wed, 17 Feb 2010 22:03:55 +0300 Subject: [PATCH 25/93] IDEA-52023 Highlight usages does not work for ActionScript in MXML Script block --- .../impl/IdentifierHighlighterPass.java | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/IdentifierHighlighterPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/IdentifierHighlighterPass.java index dbf760b25923..07e50a9763a4 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/IdentifierHighlighterPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/IdentifierHighlighterPass.java @@ -31,9 +31,11 @@ import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; +import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; +import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.util.Processor; @@ -78,13 +80,26 @@ public class IdentifierHighlighterPass extends TextEditorHighlightingPass { return; } - final PsiElement myTarget = TargetElementUtilBase.getInstance().findTargetElement(myEditor, TargetElementUtilBase.ELEMENT_NAME_ACCEPTED | TargetElementUtilBase.REFERENCED_ELEMENT_ACCEPTED, myCaretOffset); + int flags = TargetElementUtilBase.ELEMENT_NAME_ACCEPTED | TargetElementUtilBase.REFERENCED_ELEMENT_ACCEPTED; + PsiElement myTarget = TargetElementUtilBase.getInstance().findTargetElement(myEditor, flags, myCaretOffset); + + if (myTarget == null) { + if (!PsiDocumentManager.getInstance(myProject).isUncommited(myEditor.getDocument())) { + // when document is committed, try to check injected stuff - it's fast + Editor injectedEditor = InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(myEditor, myFile, myCaretOffset); + if (injectedEditor != null) { + myTarget = TargetElementUtilBase.getInstance().findTargetElement(injectedEditor, flags, injectedEditor.getCaretModel().getOffset()); + } + } + } + if (myTarget != null) { final ReadWriteAccessDetector detector = ReadWriteAccessDetector.findDetector(myTarget); + final PsiElement finalMyTarget = myTarget; ReferencesSearch.search(myTarget, new LocalSearchScope(myFile)).forEach(new Processor() { public boolean process(final PsiReference psiReference) { final TextRange textRange = HighlightUsagesHandler.getRangeToHighlight(psiReference); - if (detector == null || detector.getReferenceAccess(myTarget, psiReference) == ReadWriteAccessDetector.Access.Read) { + if (detector == null || detector.getReferenceAccess(finalMyTarget, psiReference) == ReadWriteAccessDetector.Access.Read) { myReadAccessRanges.add(textRange); } else { From 1af018001c71a8861739a8b86e4fc57947c74c91 Mon Sep 17 00:00:00 2001 From: peter Date: Wed, 17 Feb 2010 21:53:07 +0000 Subject: [PATCH 26/93] dependencies for tests --- resources/resources.iml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/resources/resources.iml b/resources/resources.iml index a04c7f90e067..7a87e487dc3a 100644 --- a/resources/resources.iml +++ b/resources/resources.iml @@ -9,6 +9,8 @@ + + From 559a26e039eca87139e83ad2cae16ea7757f46ac Mon Sep 17 00:00:00 2001 From: peter Date: Wed, 17 Feb 2010 21:53:45 +0000 Subject: [PATCH 27/93] don't change variable names groovy's evaluation code fragment, generate them already substituted --- .../debugger/GroovyCodeFragmentFactory.java | 112 +++++++----------- 1 file changed, 42 insertions(+), 70 deletions(-) diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java index d20e6053370e..cff9590d02fb 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java @@ -56,32 +56,15 @@ import java.util.Random; */ public class GroovyCodeFragmentFactory implements CodeFragmentFactory { private static final String EVAL_NAME = "_JETGROOVY_EVAL_"; - - private static String createProperty(String text, String imports) { - String classText = "\"" + - imports + - "class DUMMY { " + - "public groovy.lang.Closure " + - EVAL_NAME + " = {" + text + "}}\""; - - return "final java.lang.ClassLoader parentLoader = clazz.getClassLoader();\n" + - " final groovy.lang.GroovyClassLoader loader = new groovy.lang.GroovyClassLoader(parentLoader);\n" + - " final java.lang.Class c = loader.parseClass(" + - classText + - ", \"DUMMY.groovy\");\n" + - " int i;\n" + - " java.lang.reflect.Field[] fields = c.getFields();\n" + - " for (int j = 0; j < fields.length; j++) if (fields[j].getName().equals(\"_JETGROOVY_EVAL_\")) {i = j; break;}\n" + - " final java.lang.reflect.Field field = fields[i];\n" + - " final java.lang.Object closure = field.get(c.newInstance());\n"; - } + private static final String IMPORTS = "___$$IMPORTS$$___"; + private static final String TEXT = "___$$TEXT$$___"; private static String unwrapVals(List vals) { - return "java.lang.Object[] vals = new java.lang.Object[]{" + StringUtil.join(vals, ",") + "};\n" + - "java.lang.Object[] resVals = new java.lang.Object[" + vals.size() + "];\n" + - "for (int iii =0; iii, GroovyFile> pair = externalParameters(text, context); GroovyFile toEval = pair.second; final Map parameters = pair.first; @@ -103,76 +85,66 @@ public class GroovyCodeFragmentFactory implements CodeFragmentFactory { text = toEval.getText(); + final String groovyText = StringUtil.join(names, ", ") + "->" + stripImports(text, toEval); PsiClass contextClass = PsiUtil.getContextClass(context); boolean isStatic = isStaticContext(context); StringBuffer javaText = new StringBuffer(); - javaText.append("groovy.lang.MetaClass mc;\n"); - javaText.append("java.lang.Class clazz;\n"); + javaText.append("groovy.lang.MetaClass |mc;\n"); + javaText.append("java.lang.Class |clazz;\n"); if (!isStatic) { - javaText.append("clazz = ((java.lang.Object)this).getClass();\n"); - javaText.append("mc = ((groovy.lang.GroovyObject)this).getMetaClass();\n"); + javaText.append("|clazz = ((java.lang.Object)this).getClass();\n"); + javaText.append("|mc = ((groovy.lang.GroovyObject)this).getMetaClass();\n"); } else { - javaText.append("clazz = java.lang.Class.forName(\"").append(contextClass.getQualifiedName()).append("\");\n"); - javaText.append("mc = groovy.lang.GroovySystem.getMetaClassRegistry().getMetaClass(clazz);\n"); + assert contextClass != null; + javaText.append("|clazz = java.lang.Class.forName(\"").append(contextClass.getQualifiedName()).append("\");\n"); + javaText.append("|mc = groovy.lang.GroovySystem.getMetaClassRegistry().getMetaClass(|clazz);\n"); } - javaText.append(createProperty(StringUtil.join(names, ", ") + "->" + stripImports(text, toEval), imports)); + javaText.append("final java.lang.ClassLoader |parentLoader = |clazz.getClassLoader();\n" + + " final groovy.lang.GroovyClassLoader |loader = new groovy.lang.GroovyClassLoader(|parentLoader);\n" + + " final java.lang.Class |c = |loader.parseClass("); + javaText.append("\"" + IMPORTS + "class DUMMY { " + + "public groovy.lang.Closure " + + EVAL_NAME + " = {" + TEXT + "}}\""); + javaText.append(", \"DUMMY.groovy\");\n" + + " int |i;\n" + + " java.lang.reflect.Field[] |fields = |c.getFields();\n" + + " for (int |j = 0; |j < |fields.length; |j++) if (|fields[|j].getName().equals(\"_JETGROOVY_EVAL_\")) {|i = |j; break;}\n" + + " final java.lang.reflect.Field |field = |fields[|i];\n" + + " final java.lang.Object |closure = |field.get(|c.newInstance());\n"); - javaText.append("groovy.lang.ExpandoMetaClass emc = new groovy.lang.ExpandoMetaClass(clazz);\n"); + javaText.append("groovy.lang.ExpandoMetaClass |emc = new groovy.lang.ExpandoMetaClass(|clazz);\n"); if (!isStatic) { - javaText.append("emc.setProperty(\"").append(EVAL_NAME).append("\", closure);\n"); - javaText.append("((groovy.lang.GroovyObject)this).setMetaClass(emc);\n"); + javaText.append("|emc.setProperty(\"").append(EVAL_NAME).append("\", |closure);\n"); + javaText.append("((groovy.lang.GroovyObject)this).setMetaClass(|emc);\n"); } else { - javaText.append("((groovy.lang.GroovyObject)emc.getProperty(\"static\")).setProperty(\"").append(EVAL_NAME).append("\", closure);\n"); - javaText.append("groovy.lang.GroovySystem.getMetaClassRegistry().setMetaClass(clazz, emc);\n"); + javaText.append("((groovy.lang.GroovyObject)|emc.getProperty(\"static\")).setProperty(\"").append(EVAL_NAME).append("\", |closure);\n"); + javaText.append("groovy.lang.GroovySystem.getMetaClassRegistry().setMetaClass(|clazz, |emc);\n"); } - javaText.append("emc.initialize();\n"); + javaText.append("|emc.initialize();\n"); javaText.append(unwrapVals(values)); if (!isStatic) { - javaText.append("java.lang.Object res = ((groovy.lang.MetaClassImpl)emc).invokeMethod(this, \"").append(EVAL_NAME).append("\", "). - append("resVals").append(");\n"); - javaText.append("((groovy.lang.GroovyObject)this).setMetaClass(mc);"); //try/finally is not supported + javaText.append("java.lang.Object |res = ((groovy.lang.MetaClassImpl)|emc).invokeMethod(this, \"").append(EVAL_NAME).append("\", |resVals);\n"); + javaText.append("((groovy.lang.GroovyObject)this).setMetaClass(|mc);"); //try/finally is not supported } else { - javaText.append("java.lang.Object res = ((groovy.lang.MetaClassImpl)emc).invokeStaticMethod(clazz, \"").append(EVAL_NAME) - .append("\", "). - append("resVals").append(");\n"); - javaText.append("groovy.lang.GroovySystem.getMetaClassRegistry().setMetaClass(clazz, mc);\n"); + javaText.append("java.lang.Object |res = ((groovy.lang.MetaClassImpl)|emc).invokeStaticMethod(|clazz, \"").append(EVAL_NAME).append("\", |resVals);\n"); + javaText.append("groovy.lang.GroovySystem.getMetaClassRegistry().setMetaClass(|clazz, |mc);\n"); } - javaText.append("res"); + javaText.append("|res"); final PsiElementFactory factory = JavaPsiFacade.getInstance(toEval.getProject()).getElementFactory(); - JavaCodeFragment result = factory.createCodeBlockCodeFragment(javaText.toString(), null, true); - hideInternalJavaVariables(factory, result); + + final String hiddenJavaVars = StringUtil.replace(javaText.toString(), "|", "_$$_$$$_$$$$$$$$$_" + new Random().nextInt(42)); + final String finalText = StringUtil.replace(StringUtil.replace(hiddenJavaVars, TEXT, groovyText), IMPORTS, imports); + JavaCodeFragment result = factory.createCodeBlockCodeFragment(finalText, null, true); if (contextClass != null) { result.setThisType(factory.createType(contextClass)); } return result; } - private static void hideInternalJavaVariables(final PsiElementFactory factory, JavaCodeFragment result) { - final String varPrefix = "_$$_$$$_$$$$$$$$$_" + new Random().nextInt(42); - result.accept(new PsiRecursiveElementWalkingVisitor() { - @Override - public void visitElement(PsiElement element) { - if (element instanceof PsiReferenceExpression && ((PsiReferenceExpression)element).resolve() instanceof PsiLocalVariable) { - element.replace(factory.createExpressionFromText(varPrefix + element.getText(), element)); - } - super.visitElement(element); - } - }); - result.accept(new PsiRecursiveElementWalkingVisitor() { - @Override - public void visitElement(PsiElement element) { - if (element instanceof PsiLocalVariable) { - ((PsiLocalVariable)element).setName(varPrefix + ((PsiLocalVariable)element).getName()); - } - super.visitElement(element); - } - }); - } - public static Pair, GroovyFile> externalParameters(String text, @NotNull final PsiElement context) { final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(context.getProject()); final GroovyFile toEval = factory.createGroovyFile(text, false, context); From ecb27bf3c32794f3502576697add9d7cc8ef7ea2 Mon Sep 17 00:00:00 2001 From: peter Date: Wed, 17 Feb 2010 22:08:31 +0000 Subject: [PATCH 28/93] assertions shouldn't prevent from compiling --- .../org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java index b18f4507c08f..9b8530a36c4c 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java @@ -167,6 +167,10 @@ public class GroovyCompiler extends GroovyCompilerBase { LOG.error(e); //prevent our PSI errors from failing the entire compilation } + catch (AssertionError e) { + LOG.error(e); + //prevent our PSI errors from failing the entire compilation + } } element.acceptChildren(this); From 766c9109f28edd94ed20c6cd076ed3b8fc58f0af Mon Sep 17 00:00:00 2001 From: nik Date: Thu, 18 Feb 2010 10:31:02 +0300 Subject: [PATCH 29/93] "open in browser" action moved to xml module --- .../src/messages/XmlBundle.properties | 3 + .../src/META-INF/XmlPlugin.xml | 7 +- .../ide/browsers/OpenFileInBrowserAction.java | 67 +++++++++++++++++++ .../ide/browsers/WebBrowserUrlProvider.java | 12 ++++ 4 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 xml/impl/src/com/intellij/ide/browsers/OpenFileInBrowserAction.java diff --git a/platform/platform-resources-en/src/messages/XmlBundle.properties b/platform/platform-resources-en/src/messages/XmlBundle.properties index da7f5bcc334a..eb375b8b92f5 100644 --- a/platform/platform-resources-en/src/messages/XmlBundle.properties +++ b/platform/platform-resources-en/src/messages/XmlBundle.properties @@ -159,6 +159,9 @@ browser.path.not.specified=Please, set the path to the browser at Settings / Web browser.path.not.specified.title=Browser Path Was Not Specified browser.error=Browser Error web.editor.configuration.title=Web +action.OpenInBrowser.text=Open in _Browser +action.open.file.in.browser.description=Open a selected file in browser + xml.split.tag.intention.action=Split current tag tag.name.completion.hint=Press {0} to view tags from other namespaces diff --git a/platform/platform-resources/src/META-INF/XmlPlugin.xml b/platform/platform-resources/src/META-INF/XmlPlugin.xml index 4142e22f93c1..7d838acf123f 100644 --- a/platform/platform-resources/src/META-INF/XmlPlugin.xml +++ b/platform/platform-resources/src/META-INF/XmlPlugin.xml @@ -304,11 +304,16 @@ - + + + + + + diff --git a/xml/impl/src/com/intellij/ide/browsers/OpenFileInBrowserAction.java b/xml/impl/src/com/intellij/ide/browsers/OpenFileInBrowserAction.java new file mode 100644 index 000000000000..f94b8f29a8cc --- /dev/null +++ b/xml/impl/src/com/intellij/ide/browsers/OpenFileInBrowserAction.java @@ -0,0 +1,67 @@ +package com.intellij.ide.browsers; + +import com.intellij.ide.BrowserUtil; +import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.project.DumbAwareAction; +import com.intellij.openapi.ui.Messages; +import com.intellij.psi.PsiFile; +import com.intellij.xml.XmlBundle; + +public class OpenFileInBrowserAction extends DumbAwareAction { + private static final Logger LOG = Logger.getInstance("#com.intellij.ide.browsers.OpenFileInBrowserAction"); + + public void update(AnActionEvent e) { + final DataContext dataContext = e.getDataContext(); + final PsiFile file = LangDataKeys.PSI_FILE.getData(dataContext); + final Presentation presentation = e.getPresentation(); + + if (file != null) { + presentation.setVisible(true); + presentation.setText(XmlBundle.message("action.OpenInBrowser.text")); + presentation.setDescription(XmlBundle.message("action.open.file.in.browser.description")); + + final WebBrowserUrlProvider browserUrlProvider = WebBrowserUrlProviders.getProvider(file); + presentation.setEnabled(browserUrlProvider != null); + + if (browserUrlProvider != null) { + final String actionText = browserUrlProvider.getOpenInBrowserActionText(file); + if (actionText != null) { + presentation.setText(actionText); + } + final String description = browserUrlProvider.getOpenInBrowserActionDescription(file); + if (description != null) { + presentation.setDescription(description); + } + } + + if (ActionPlaces.isPopupPlace(e.getPlace())) { + presentation.setVisible(presentation.isEnabled()); + } + } else { + presentation.setVisible(false); + presentation.setEnabled(false); + } + } + + public void actionPerformed(AnActionEvent e) { + final DataContext dataContext = e.getDataContext(); + final PsiFile psiFile = LangDataKeys.PSI_FILE.getData(dataContext); + LOG.assertTrue(psiFile != null); + final WebBrowserUrlProvider provider = WebBrowserUrlProviders.getProvider(psiFile); + if (provider != null) { + try { + final String url = provider.getUrl(psiFile, false); + ApplicationManager.getApplication().saveAll(); + BrowserUtil.launchBrowser(url); + } + catch (WebBrowserUrlProvider.BrowserException e1) { + Messages.showErrorDialog(e1.getMessage(), XmlBundle.message("browser.error")); + } + catch (Exception e1) { + LOG.error(e1); + } + } + } +} diff --git a/xml/openapi/src/com/intellij/ide/browsers/WebBrowserUrlProvider.java b/xml/openapi/src/com/intellij/ide/browsers/WebBrowserUrlProvider.java index f29270be9ccb..01a2084c0f0e 100644 --- a/xml/openapi/src/com/intellij/ide/browsers/WebBrowserUrlProvider.java +++ b/xml/openapi/src/com/intellij/ide/browsers/WebBrowserUrlProvider.java @@ -17,7 +17,9 @@ package com.intellij.ide.browsers; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; /** * @author spleaner @@ -44,4 +46,14 @@ public abstract class WebBrowserUrlProvider { * Invariant: element has not null containing psi file with not null virtual file */ public abstract boolean canHandleElement(@NotNull final PsiElement element); + + @Nullable + public String getOpenInBrowserActionText(@NotNull PsiFile file) { + return null; + } + + @Nullable + public String getOpenInBrowserActionDescription(@NotNull PsiFile file) { + return null; + } } From 32eba9c15823800c66ba424787244f6ae4e0e545 Mon Sep 17 00:00:00 2001 From: nik Date: Thu, 18 Feb 2010 11:30:49 +0300 Subject: [PATCH 30/93] custom "open in browser" action in "Remote access" plugin replaced by the common one --- platform/platform-resources/src/META-INF/XmlPlugin.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/platform/platform-resources/src/META-INF/XmlPlugin.xml b/platform/platform-resources/src/META-INF/XmlPlugin.xml index 7d838acf123f..f05c4d4b8309 100644 --- a/platform/platform-resources/src/META-INF/XmlPlugin.xml +++ b/platform/platform-resources/src/META-INF/XmlPlugin.xml @@ -310,7 +310,8 @@ - + From caa0873310af33d1fd6d88c59744b876ca76fcf5 Mon Sep 17 00:00:00 2001 From: anna Date: Wed, 17 Feb 2010 14:37:11 +0300 Subject: [PATCH 31/93] back/forward actions --- .../codeInsight/documentation/DocumentationComponent.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java index bd47348f1e2c..8c64afe9b6eb 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java @@ -269,7 +269,7 @@ public class DocumentationComponent extends JPanel implements Disposable { myForwardStack.clear(); } updateControlState(); - setData(element, text, !clean); + setData(element, text, clearHistory); if (clean) { myIsEmpty = false; } From 8d7a08581d3693f7df57b3890876f31f67c72384 Mon Sep 17 00:00:00 2001 From: anna Date: Wed, 17 Feb 2010 18:23:56 +0300 Subject: [PATCH 32/93] reuse containing file in scopes view (IDEA-25711) --- .../ide/scopeView/ClassesScopeTreeStructureExpander.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java/java-impl/src/com/intellij/ide/scopeView/ClassesScopeTreeStructureExpander.java b/java/java-impl/src/com/intellij/ide/scopeView/ClassesScopeTreeStructureExpander.java index eedc196bdc71..a08337dbe6e5 100644 --- a/java/java-impl/src/com/intellij/ide/scopeView/ClassesScopeTreeStructureExpander.java +++ b/java/java-impl/src/com/intellij/ide/scopeView/ClassesScopeTreeStructureExpander.java @@ -129,12 +129,12 @@ public class ClassesScopeTreeStructureExpander implements ScopeTreeStructureExpa final TreeNode childNode = node.getChildAt(i); if (childNode instanceof ClassNode) { final ClassNode classNode = (ClassNode)childNode; - final PsiElement psiElement = classNode.getPsiElement(); - if (psiElement != null && psiElement.isValid()) { + final PsiFile containingFile = classNode.getContainingFile(); + if (containingFile != null && containingFile.isValid()) { if (fileNodes == null) { fileNodes = new HashSet(); } - fileNodes.add(new FileNode(psiElement.getContainingFile(), true)); + fileNodes.add(new FileNode(containingFile, true)); } node.remove(classNode); } From f9dca81933526053579e070327c50ca607d607d0 Mon Sep 17 00:00:00 2001 From: anna Date: Wed, 17 Feb 2010 22:55:33 +0300 Subject: [PATCH 33/93] introduce constant: escalate visibility (IDEA-26029) --- .../BaseExpressionToFieldHandler.java | 38 ++++++---- .../IntroduceConstantDialog.form | 54 ++------------ .../IntroduceConstantDialog.java | 73 +++++-------------- .../introduceField/LocalToFieldHandler.java | 30 ++------ .../refactoring/ui/VisibilityPanel.java | 14 ++++ .../src/com/intellij/util/VisibilityUtil.java | 12 +++ 6 files changed, 79 insertions(+), 142 deletions(-) diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java index a5aae5d453b6..4aa0f8d94492 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java @@ -59,6 +59,7 @@ import com.intellij.refactoring.util.EnumConstantsUtil; import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.refactoring.util.occurences.OccurenceManager; import com.intellij.util.IncorrectOperationException; +import com.intellij.util.VisibilityUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -194,21 +195,7 @@ public abstract class BaseExpressionToFieldHandler extends IntroduceHandlerBase ChangeContextUtil.encodeContextInfo(initializer, true); PsiField field = settings.isIntroduceEnumConstant() ? EnumConstantsUtil.createEnumConstant(destClass, fieldName, initializer) : createField(fieldName, type, initializer, initializerPlace == InitializationPlace.IN_FIELD_DECLARATION && initializer != null); - if (!settings.isIntroduceEnumConstant()) { - PsiUtil.setModifierProperty(field, settings.getFieldVisibility(), true); - if (settings.isDeclareFinal()) { - PsiUtil.setModifierProperty(field, PsiModifier.FINAL, true); - } - if (settings.isDeclareStatic()) { - PsiUtil.setModifierProperty(field, PsiModifier.STATIC, true); - } - if (settings.isAnnotateAsNonNls()) { - PsiAnnotation annotation = JavaPsiFacade.getInstance(myParentClass.getProject()).getElementFactory() - .createAnnotationFromText("@" + AnnotationUtil.NON_NLS, myParentClass); - field.getModifierList().addAfter(annotation, null); - JavaCodeStyleManager.getInstance(myParentClass.getProject()).shortenClassReferences(field.getModifierList()); - } - } + PsiElement finalAnchorElement = null; if (destClass == myParentClass) { for (finalAnchorElement = anchorElement; @@ -230,6 +217,7 @@ public abstract class BaseExpressionToFieldHandler extends IntroduceHandlerBase else { field = (PsiField)destClass.add(field); } + setModifiers(field, settings, settings.isDeclareStatic(), occurrences); PsiStatement assignStatement = null; PsiElement anchorElementHere = null; if (initializerPlace == InitializationPlace.IN_CURRENT_METHOD && initializer != null || @@ -326,6 +314,26 @@ public abstract class BaseExpressionToFieldHandler extends IntroduceHandlerBase return true; } + public static void setModifiers(PsiField field, Settings settings, final boolean declareStatic, PsiExpression[] occurrences) { + if (!settings.isIntroduceEnumConstant()) { + VisibilityUtil.fixVisibility(occurrences, field, settings.getFieldVisibility()); + if (declareStatic) { + PsiUtil.setModifierProperty(field, PsiModifier.STATIC, true); + } + if (settings.isDeclareFinal()) { + PsiUtil.setModifierProperty(field, PsiModifier.FINAL, true); + } + if (settings.isAnnotateAsNonNls()) { + PsiAnnotation annotation = JavaPsiFacade.getInstance(field.getProject()).getElementFactory() + .createAnnotationFromText("@" + AnnotationUtil.NON_NLS, field); + final PsiModifierList modifierList = field.getModifierList(); + LOG.assertTrue(modifierList != null); + modifierList.addAfter(annotation, null); + } + } + JavaCodeStyleManager.getInstance(field.getProject()).shortenClassReferences(field); + } + private static PsiElement getPhysicalElement(final PsiExpression selectedExpr) { PsiElement element = selectedExpr.getUserData(ElementToWorkOn.PARENT); if (element == null) element = selectedExpr; diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.form b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.form index be37bbaa3235..08c65852f116 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.form +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.form @@ -79,52 +79,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -152,6 +106,14 @@ + + + + + + + + diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.java b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.java index 4bc51108528b..8fb93fb70d7e 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.java @@ -46,6 +46,7 @@ import com.intellij.ui.RecentsManager; import com.intellij.ui.ReferenceEditorComboWithBrowseButton; import com.intellij.ui.StateRestoringCheckBox; import com.intellij.util.IncorrectOperationException; +import com.intellij.util.ui.UIUtil; import gnu.trove.THashSet; import org.jetbrains.annotations.NonNls; @@ -77,11 +78,6 @@ class IntroduceConstantDialog extends DialogWrapper { private NameSuggestionsField myNameField; private JCheckBox myCbReplaceAll; - private JRadioButton myRbPrivate; - private JRadioButton myRbProtected; - private JRadioButton myRbpackageLocal; - private JRadioButton myRbPublic; - private TypeSelector myTypeSelector; private StateRestoringCheckBox myCbDeleteVariable; private final JavaCodeStyleManager myCodeStyleManager; @@ -95,6 +91,8 @@ class IntroduceConstantDialog extends DialogWrapper { private JLabel myNameSuggestionLabel; private JLabel myTargetClassNameLabel; private JCheckBox myCbNonNls; + private JPanel myVisibilityPanel; + private VisibilityPanel myVPanel; private final JCheckBox myIntroduceEnumConstantCb = new JCheckBox(RefactoringBundle.message("introduce.constant.enum.cb"), true); IntroduceConstantDialog(Project project, @@ -119,20 +117,11 @@ class IntroduceConstantDialog extends DialogWrapper { setTitle(IntroduceConstantHandler.REFACTORING_NAME); myCodeStyleManager = JavaCodeStyleManager.getInstance(myProject); + myVPanel = new VisibilityPanel(false, true); + myVisibilityPanel.add(myVPanel, BorderLayout.CENTER); init(); - final String ourLastVisibility = JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_VISIBILITY; - if (PsiModifier.PUBLIC.equals(ourLastVisibility)) { - myRbPublic.setSelected(true); - } else if (PsiModifier.PROTECTED.equals(ourLastVisibility)) { - myRbProtected.setSelected(true); - } else if (PsiModifier.PACKAGE_LOCAL.equals(ourLastVisibility)) { - myRbpackageLocal.setSelected(true); - } else if (PsiModifier.PRIVATE.equals(ourLastVisibility)) { - myRbPrivate.setSelected(true); - } else { - myRbPrivate.setSelected(true); - } + myVPanel.setVisibility(JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_VISIBILITY); myIntroduceEnumConstantCb.setEnabled(EnumConstantsUtil.isSuitableForEnumConstant(getSelectedType(), myTargetClass)); updateVisibilityPanel(); } @@ -155,20 +144,7 @@ class IntroduceConstantDialog extends DialogWrapper { @Modifier public String getFieldVisibility() { - 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; - } - LOG.assertTrue(false); - return null; + return myVPanel.getVisibility(); } public boolean isReplaceAllOccurrences() { @@ -301,11 +277,6 @@ class IntroduceConstantDialog extends DialogWrapper { updateTypeSelector(); - ButtonGroup bg = new ButtonGroup(); - bg.add(myRbPrivate); - bg.add(myRbpackageLocal); - bg.add(myRbProtected); - bg.add(myRbPublic); enableEnumDependant(introduceEnumConstant()); return myPanel; } @@ -319,11 +290,7 @@ class IntroduceConstantDialog extends DialogWrapper { private void enableEnumDependant(boolean enable) { if (enable) { - myRbPrivate.setEnabled(false); - myRbProtected.setEnabled(false); - myRbpackageLocal.setEnabled(false); - myRbPublic.setEnabled(true); - myRbPublic.setSelected(true); + myVPanel.disableAllButPublic(); } else { updateVisibilityPanel(); } @@ -361,19 +328,11 @@ class IntroduceConstantDialog extends DialogWrapper { } private void updateVisibilityPanel() { - if (myTargetClass == null) return; - if (myTargetClass.isInterface()) { - myRbPrivate.setEnabled(false); - myRbProtected.setEnabled(false); - myRbpackageLocal.setEnabled(false); - myRbPublic.setEnabled(true); - myRbPublic.setSelected(true); + if (myTargetClass != null && myTargetClass.isInterface()) { + myVPanel.disableAllButPublic(); } else { - myRbPrivate.setEnabled(true); - myRbProtected.setEnabled(true); - myRbpackageLocal.setEnabled(true); - myRbPublic.setEnabled(true); + UIUtil.setEnabled(myVisibilityPanel, true, true); // exclude all modifiers not visible from all occurences final Set visible = new THashSet(); visible.add(PsiModifier.PRIVATE); @@ -397,10 +356,12 @@ class IntroduceConstantDialog extends DialogWrapper { } } } - if (visible.contains(PsiModifier.PUBLIC)) myRbPublic.setSelected(true); - if (visible.contains(PsiModifier.PACKAGE_LOCAL)) myRbpackageLocal.setSelected(true); - if (visible.contains(PsiModifier.PROTECTED)) myRbProtected.setSelected(true); - if (visible.contains(PsiModifier.PRIVATE)) myRbPrivate.setSelected(true); + if (!visible.contains(getFieldVisibility())) { + if (visible.contains(PsiModifier.PUBLIC)) myVPanel.setVisibility(PsiModifier.PUBLIC); + if (visible.contains(PsiModifier.PACKAGE_LOCAL)) myVPanel.setVisibility(PsiModifier.PACKAGE_LOCAL); + if (visible.contains(PsiModifier.PROTECTED)) myVPanel.setVisibility(PsiModifier.PROTECTED); + if (visible.contains(PsiModifier.PRIVATE)) myVPanel.setVisibility(PsiModifier.PRIVATE); + } } } diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java index 9055a91074c5..7764cd42a55b 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java @@ -15,7 +15,6 @@ */ package com.intellij.refactoring.introduceField; -import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInsight.CodeInsightUtil; import com.intellij.codeInsight.TestUtil; import com.intellij.openapi.application.ApplicationManager; @@ -25,15 +24,11 @@ import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; -import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.psi.util.PsiUtil; import com.intellij.refactoring.HelpID; import com.intellij.refactoring.RefactoringBundle; -import static com.intellij.refactoring.introduceField.BaseExpressionToFieldHandler.InitializationPlace.IN_CONSTRUCTOR; -import static com.intellij.refactoring.introduceField.BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION; import com.intellij.refactoring.ui.TypeSelectorManagerImpl; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.refactoring.util.EnumConstantsUtil; @@ -41,6 +36,9 @@ import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NonNls; +import static com.intellij.refactoring.introduceField.BaseExpressionToFieldHandler.InitializationPlace.IN_CONSTRUCTOR; +import static com.intellij.refactoring.introduceField.BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION; + public class LocalToFieldHandler { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.introduceField.LocalToFieldHandler"); @@ -125,9 +123,7 @@ public class LocalToFieldHandler { final boolean isStatic = tempIsStatic; - PsiExpression[] occurences = CodeInsightUtil.findReferenceExpressions(RefactoringUtil.getVariableScope(local), - local - ); + final PsiExpression[] occurences = CodeInsightUtil.findReferenceExpressions(RefactoringUtil.getVariableScope(local), local); if (editor != null) { RefactoringUtil.highlightAllOccurences(myProject, occurences, editor); } @@ -138,7 +134,6 @@ public class LocalToFieldHandler { final String variableName = local.getName(); final String fieldName = settings.getFieldName(); final BaseExpressionToFieldHandler.InitializationPlace initializerPlace = settings.getInitializerPlace(); - final boolean declareFinal = settings.isDeclareFinal(); @Modifier final String fieldVisibility = settings.getFieldVisibility(); final PsiClass destinationClass = settings.getDestinationClass(); boolean rebindNeeded = false; @@ -146,7 +141,6 @@ public class LocalToFieldHandler { aClass = destinationClass; rebindNeeded = true; } - final boolean annotateAsNonNls = settings.isAnnotateAsNonNls(); final PsiClass aaClass = aClass; final boolean rebindNeeded1 = rebindNeeded; @@ -165,22 +159,8 @@ public class LocalToFieldHandler { final PsiMethod enclosingConstructor = BaseExpressionToFieldHandler.getEnclosingConstructor(aaClass, local); PsiField field = settings.isIntroduceEnumConstant() ? EnumConstantsUtil.createEnumConstant(aaClass, local, fieldName) : createField(local, fieldName, initializerPlace == IN_FIELD_DECLARATION); - if (!settings.isIntroduceEnumConstant()) { - if (isStatic) { - PsiUtil.setModifierProperty(field, PsiModifier.STATIC, true); - } - if (declareFinal) { - PsiUtil.setModifierProperty(field, PsiModifier.FINAL, true); - } - if (annotateAsNonNls) { - PsiAnnotation annotation = JavaPsiFacade.getInstance(local.getProject()).getElementFactory().createAnnotationFromText("@" + AnnotationUtil.NON_NLS, field); - field.getModifierList().addAfter(annotation, null); - } - PsiUtil.setModifierProperty(field, fieldVisibility, true); - } - field = (PsiField)aaClass.add(field); - JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(field); + BaseExpressionToFieldHandler.setModifiers(field, settings, isStatic, occurences); local.normalizeDeclaration(); PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement)local.getParent(); diff --git a/java/java-impl/src/com/intellij/refactoring/ui/VisibilityPanel.java b/java/java-impl/src/com/intellij/refactoring/ui/VisibilityPanel.java index 558b82a17566..95b0e3d384b8 100644 --- a/java/java-impl/src/com/intellij/refactoring/ui/VisibilityPanel.java +++ b/java/java-impl/src/com/intellij/refactoring/ui/VisibilityPanel.java @@ -144,6 +144,20 @@ public class VisibilityPanel extends JPanel { } } + 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); + } + public static interface StateChanged extends EventListener { void visibilityChanged(); } diff --git a/java/openapi/src/com/intellij/util/VisibilityUtil.java b/java/openapi/src/com/intellij/util/VisibilityUtil.java index a5505ac27d88..773717d07a02 100644 --- a/java/openapi/src/com/intellij/util/VisibilityUtil.java +++ b/java/openapi/src/com/intellij/util/VisibilityUtil.java @@ -143,4 +143,16 @@ public class VisibilityUtil { modifierList.setModifierProperty(PsiModifier.PROTECTED, false); modifierList.setModifierProperty(newVisibility, true); } + + public static void fixVisibility(PsiExpression[] expressions, PsiMember member, String newVisibility) { + if (newVisibility == null) return; + if (ESCALATE_VISIBILITY.equals(newVisibility)) { + for (PsiExpression element : expressions) { + escalateVisibility(member, element); + } + } + else { + setVisibility(member.getModifierList(), newVisibility); + } + } } From 66a9f8e8434a10d5838dcd1cd44df6090a43187b Mon Sep 17 00:00:00 2001 From: anna Date: Wed, 17 Feb 2010 23:19:15 +0300 Subject: [PATCH 34/93] wrap return value for abstract methods --- .../WrapReturnValueProcessor.java | 25 ++++++++++--------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueProcessor.java b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueProcessor.java index aabf2ac3eed0..564e16cc7adf 100644 --- a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueProcessor.java @@ -164,21 +164,22 @@ public class WrapReturnValueProcessor extends FixableUsagesRefactoringProcessor } else { boolean foundConstructor = false; - final PsiCodeBlock methodBody = method.getBody(); - assert methodBody != null; final Set returnTypes = new HashSet(); returnTypes.add(method.getReturnType()); - methodBody.accept(new JavaRecursiveElementWalkingVisitor() { - @Override - public void visitReturnStatement(final PsiReturnStatement statement) { - super.visitReturnStatement(statement); - if (PsiTreeUtil.getParentOfType(statement, PsiMethod.class) != method) return; - final PsiExpression returnValue = statement.getReturnValue(); - if (returnValue != null) { - returnTypes.add(returnValue.getType()); + final PsiCodeBlock methodBody = method.getBody(); + if (methodBody != null) { + methodBody.accept(new JavaRecursiveElementWalkingVisitor() { + @Override + public void visitReturnStatement(final PsiReturnStatement statement) { + super.visitReturnStatement(statement); + if (PsiTreeUtil.getParentOfType(statement, PsiMethod.class) != method) return; + final PsiExpression returnValue = statement.getReturnValue(); + if (returnValue != null) { + returnTypes.add(returnValue.getType()); + } } - } - }); + }); + } final PsiMethod[] constructors = existingClass.getConstructors(); constr: for (PsiMethod constructor : constructors) { From 4da84c22d90fb115c67dd3d3bd55b6a65b155968 Mon Sep 17 00:00:00 2001 From: anna Date: Wed, 17 Feb 2010 23:34:10 +0300 Subject: [PATCH 35/93] wrap return value: radio button navigation, labels for --- .../wrapreturnvalue/WrapReturnValueDialog.java | 11 +++++++++++ .../wrapreturnvalue/WrapReturnValueForm.form | 1 + 2 files changed, 12 insertions(+) diff --git a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueDialog.java b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueDialog.java index fe6aeb62e04a..fab67d602497 100644 --- a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueDialog.java @@ -22,6 +22,7 @@ import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.TypeConversionUtil; @@ -226,6 +227,16 @@ class WrapReturnValueDialog extends RefactoringDialog { UIUtil.setEnabled(myExistingClassPanel, useExistingClassButton.isSelected(), true); UIUtil.setEnabled(myNewClassPanel, createNewClassButton.isSelected(), true); UIUtil.setEnabled(myCreateInnerPanel, myCreateInnerClassButton.isSelected(), true); + final IdeFocusManager focusManager = IdeFocusManager.getInstance(myProject); + if (useExistingClassButton.isSelected()) { + focusManager.requestFocus(existingClassField, true); + } + else if (myCreateInnerClassButton.isSelected()) { + focusManager.requestFocus(myInnerClassNameTextField, true); + } + else { + focusManager.requestFocus(classNameField, true); + } validateButtons(); } diff --git a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueForm.form b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueForm.form index a3c4342ea222..e185665d4071 100644 --- a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueForm.form +++ b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueForm.form @@ -96,6 +96,7 @@ + From 9cab3913b6d6717cfa2aa13adfb13edc73c87f34 Mon Sep 17 00:00:00 2001 From: "Rustam.Vishnyakov" Date: Thu, 18 Feb 2010 13:52:08 +0300 Subject: [PATCH 36/93] Fix for incorrect PHP code indentation within HTML (WI-78) --- .../formatting/templateLanguages/BlockUtil.java | 12 ++++++++++-- .../templateLanguages/TemplateLanguageBlock.java | 10 ++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/formatting/templateLanguages/BlockUtil.java b/platform/lang-impl/src/com/intellij/formatting/templateLanguages/BlockUtil.java index 3b9f8d0bf555..1a67ea08ae70 100644 --- a/platform/lang-impl/src/com/intellij/formatting/templateLanguages/BlockUtil.java +++ b/platform/lang-impl/src/com/intellij/formatting/templateLanguages/BlockUtil.java @@ -184,16 +184,24 @@ class BlockUtil { final List children = new ArrayList(5); final TextRange range = block.getTextRange(); int childStartOffset = range.getStartOffset(); + TemplateLanguageBlock lastTLBlock = null; for (TemplateLanguageBlock tlBlock : subBlocks) { final TextRange tlTextRange = tlBlock.getTextRange(); if (tlTextRange.getStartOffset() > childStartOffset) { - children.add(new DataLanguageBlockFragmentWrapper(block, new TextRange(childStartOffset, tlTextRange.getStartOffset()))); + TextRange dataBlockTextRange = new TextRange(childStartOffset, tlTextRange.getStartOffset()); + if (tlBlock.isRequiredRange(dataBlockTextRange)) { + children.add(new DataLanguageBlockFragmentWrapper(block, dataBlockTextRange)); + } } children.add(tlBlock); + lastTLBlock = tlBlock; childStartOffset = tlTextRange.getEndOffset(); } if (range.getEndOffset() > childStartOffset) { - children.add(new DataLanguageBlockFragmentWrapper(block, new TextRange(childStartOffset, range.getEndOffset()))); + TextRange dataBlockTextRange = new TextRange(childStartOffset, range.getEndOffset()); + if (lastTLBlock == null || lastTLBlock.isRequiredRange(dataBlockTextRange) ) { + children.add(new DataLanguageBlockFragmentWrapper(block, dataBlockTextRange)); + } } return children; } diff --git a/platform/lang-impl/src/com/intellij/formatting/templateLanguages/TemplateLanguageBlock.java b/platform/lang-impl/src/com/intellij/formatting/templateLanguages/TemplateLanguageBlock.java index af5a734cf4fe..9970f478b51e 100644 --- a/platform/lang-impl/src/com/intellij/formatting/templateLanguages/TemplateLanguageBlock.java +++ b/platform/lang-impl/src/com/intellij/formatting/templateLanguages/TemplateLanguageBlock.java @@ -17,6 +17,7 @@ package com.intellij.formatting.templateLanguages; import com.intellij.formatting.*; import com.intellij.lang.ASTNode; +import com.intellij.openapi.util.TextRange; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.formatter.FormatterUtil; import com.intellij.psi.formatter.common.AbstractBlock; @@ -119,5 +120,14 @@ public abstract class TemplateLanguageBlock extends AbstractBlock implements Blo public void setParent(BlockWithParent newParent) { myParent = newParent; } + + /** + * Checks if DataLanguageBlockFragmentWrapper must be created for the given text range. + * @param range The range to check. + * @return True by default. + */ + public boolean isRequiredRange(TextRange range) { + return true; + } } From 3b5be3b19f2c6d527088840e4e47fafafc687d05 Mon Sep 17 00:00:00 2001 From: nik Date: Thu, 18 Feb 2010 14:42:30 +0300 Subject: [PATCH 37/93] xdebugger javadoc --- .../com/intellij/xdebugger/XDebugProcess.java | 39 +++++++++++++------ .../xdebugger/XDebugProcessStarter.java | 8 ++++ .../com/intellij/xdebugger/XDebugSession.java | 4 ++ .../intellij/xdebugger/XDebuggerManager.java | 10 ++++- .../intellij/xdebugger/XSourcePosition.java | 4 +- .../xdebugger/breakpoints/XBreakpoint.java | 5 +++ .../breakpoints/XBreakpointManager.java | 2 + .../breakpoints/XBreakpointType.java | 3 ++ .../breakpoints/XLineBreakpoint.java | 3 ++ .../breakpoints/XLineBreakpointType.java | 18 ++++++++- .../evaluation/XDebuggerEvaluator.java | 2 +- .../xdebugger/frame/XCompositeNode.java | 4 ++ .../xdebugger/frame/XExecutionStack.java | 6 ++- .../intellij/xdebugger/frame/XStackFrame.java | 5 +++ .../xdebugger/frame/XSuspendContext.java | 6 +++ .../com/intellij/xdebugger/frame/XValue.java | 3 ++ .../xdebugger/frame/XValueModifier.java | 2 +- .../intellij/xdebugger/frame/XValueNode.java | 4 ++ .../src/com/intellij/xdebugger/package.html | 27 +++++++++++++ 19 files changed, 137 insertions(+), 18 deletions(-) create mode 100644 platform/xdebugger-api/src/com/intellij/xdebugger/package.html diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcess.java b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcess.java index 1899ebac774f..f8cf0f91916c 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcess.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcess.java @@ -27,12 +27,22 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** + * Extends this class to provide debugging capabilities for custom language/framework. + * + * In order to start debugger by 'Debug' action for a specific run configuration implement {@link com.intellij.execution.runners.ProgramRunner} + * and call {@link XDebuggerManager#startSession} from {@link com.intellij.execution.runners.ProgramRunner#execute} method + * + * Otherwise use method {@link XDebuggerManager#startSessionAndShowTab} to start new debugging session + * * @author nik */ public abstract class XDebugProcess { private final XDebugSession mySession; private ProcessHandler myProcessHandler; + /** + * @param session pass session parameter of {@link XDebugProcessStarter#start} method to this constructor + */ protected XDebugProcess(@NotNull XDebugSession session) { mySession = session; } @@ -64,27 +74,31 @@ public abstract class XDebugProcess { } /** - * Interrupt debugging process and call {@link XDebugSession#positionReached(com.intellij.xdebugger.frame.XSuspendContext)} - * when next line in current method/function is reached + * Interrupt debugging process and call {@link XDebugSession#positionReached} + * when next line in current method/function is reached. + * Do not call this method directly. Use {@link XDebugSession#pause()} instead */ public void startPausing() { } /** - * Resume execution and call {@link XDebugSession#positionReached(com.intellij.xdebugger.frame.XSuspendContext)} - * when next line in current method/function is reached + * Resume execution and call {@link XDebugSession#positionReached} + * when next line in current method/function is reached. + * Do not call this method directly. Use {@link XDebugSession#stepOver} instead */ public abstract void startStepOver(); /** - * Resume execution and call {@link XDebugSession#positionReached(com.intellij.xdebugger.frame.XSuspendContext)} - * when next line is reached + * Resume execution and call {@link XDebugSession#positionReached} + * when next line is reached. + * Do not call this method directly. Use {@link XDebugSession#stepInto} instead */ public abstract void startStepInto(); /** - * Resume execution and call {@link XDebugSession#positionReached(com.intellij.xdebugger.frame.XSuspendContext)} - * after returning from current method/function + * Resume execution and call {@link XDebugSession#positionReached} + * after returning from current method/function. + * Do not call this method directly. Use {@link XDebugSession#stepOut} instead */ public abstract void startStepOut(); @@ -98,18 +112,21 @@ public abstract class XDebugProcess { } /** - * Stop debugging and dispose resources + * Stop debugging and dispose resources. + * Do not call this method directly. Use {@link XDebugSession#stop} instead */ public abstract void stop(); /** - * Resume execution + * Resume execution. + * Do not call this method directly. Use {@link XDebugSession#resume} instead */ public abstract void resume(); /** * Resume execution and call {@link XDebugSession#positionReached(com.intellij.xdebugger.frame.XSuspendContext)} - * when position is reached + * when position is reached. + * Do not call this method directly. Use {@link XDebugSession#runToPosition} instead * @param position position in source code */ public abstract void runToPosition(@NotNull XSourcePosition position); diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcessStarter.java b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcessStarter.java index 54405346eab2..d37afc05b5dd 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcessStarter.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcessStarter.java @@ -18,10 +18,18 @@ package com.intellij.xdebugger; import org.jetbrains.annotations.NotNull; /** + * Factory class for {@link XDebugProcess} implementation. Used by {@link XDebuggerManager} to start a new debugging session + * * @author nik */ public abstract class XDebugProcessStarter { + /** + * Create a new instance of {@link XDebugProcess} implementation. Note that session isn't initialized when this method is + * called so in order to perform code depending on session parameter override {@link XDebugProcess#sessionInitialized} method + * @param session session to be passed to {@link XDebugProcess#XDebugProcess} constructor + * @return new {@link XDebugProcess} instance + */ @NotNull public abstract XDebugProcess start(@NotNull XDebugSession session); diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugSession.java b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugSession.java index 11ad6fb38e77..4a24013a7074 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugSession.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugSession.java @@ -31,6 +31,10 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; /** + * Instances of this class are created by the debugging subsystem when {@link XDebuggerManager#startSession} or + * {@link XDebuggerManager#startSessionAndShowTab} method is called. It isn't supposed to be implemented by a plugin. + * + * Instance of this class can be obtained from {@link XDebugProcess#getSession()} method and used to control debugging process * @author nik */ public interface XDebugSession extends AbstractDebuggerSession { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebuggerManager.java b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebuggerManager.java index 5b0ac76e7bf8..0682a127e83e 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebuggerManager.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebuggerManager.java @@ -48,13 +48,21 @@ public abstract class XDebuggerManager { @Nullable public abstract XDebugSession getCurrentSession(); + /** + * Start a new debugging session. Use this method only if debugging is started by using standard 'Debug' action i.e. this methods is called + * from {@link com.intellij.execution.runners.ProgramRunner#execute} method. Otherwise use {@link #startSessionAndShowTab} method + */ @NotNull public abstract XDebugSession startSession(@NotNull final ProgramRunner runner, @NotNull ExecutionEnvironment env, @Nullable RunContentDescriptor contentToReuse, @NotNull XDebugProcessStarter processStarter); + /** + * Start a new debugging session and open 'Debug' tool window + * @param sessionName title of 'Debug' tool window + */ @NotNull public abstract XDebugSession startSessionAndShowTab(@NotNull String sessionName, @Nullable RunContentDescriptor contentToReuse, - @NotNull XDebugProcessStarter starter); + @NotNull XDebugProcessStarter starter); } diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/XSourcePosition.java b/platform/xdebugger-api/src/com/intellij/xdebugger/XSourcePosition.java index 445f06b1ce6b..0f4930d96270 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/XSourcePosition.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/XSourcePosition.java @@ -22,8 +22,8 @@ import com.intellij.pom.Navigatable; import org.jetbrains.annotations.NotNull; /** - * Represents position in a source file. Use {@link XDebuggerUtil#createPosition(com.intellij.openapi.vfs.VirtualFile, int)} to create - * instances of this interface. + * Represents position in a source file. Use {@link XDebuggerUtil#createPosition} and {@link XDebuggerUtil#createPositionByOffset} to + * create instances of this interface. * @author nik */ public interface XSourcePosition { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpoint.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpoint.java index 368a225818f1..c52e87e10579 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpoint.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpoint.java @@ -23,6 +23,11 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** + * Represents a breakpoint. This interface isn't supposed to be implemented by a plugin. In order to support breakpoint provide + * {@link XBreakpointType} or {@link XLineBreakpointType} implementation + * + * @see XLineBreakpoint + * @see XBreakpointManager * @author nik */ public interface XBreakpoint

extends UserDataHolder { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointManager.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointManager.java index c936e5ae74a3..116e6bf01ce3 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointManager.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointManager.java @@ -24,6 +24,8 @@ import org.jetbrains.annotations.Nullable; import java.util.Collection; /** + * Use {@link com.intellij.xdebugger.XDebuggerManager#getBreakpointManager()} to obtain instance of this service + * * @author nik */ public interface XBreakpointManager { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java index 120f30efb805..cdcc335c128f 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java @@ -40,6 +40,9 @@ import java.util.Comparator; *   <xdebugger.breakpointType implementation="qualified-class-name"/>
* </extensions> * + * Use this class only for breakpoints like an exception breakpoints in Java. If a breakpoint will be put on some line in a file use + * {@link XLineBreakpointType} instead + * * @author nik */ public abstract class XBreakpointType, P extends XBreakpointProperties> { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpoint.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpoint.java index 456f419433bc..cdd45d58b2b1 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpoint.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpoint.java @@ -19,6 +19,9 @@ package com.intellij.xdebugger.breakpoints; import org.jetbrains.annotations.NotNull; /** + * Represent a breakpoint which is set on some line in a file. This interface isn't supposed to be implemented by a plugin. In order to + * support breakpoint provide {@link XLineBreakpointType} implementation + * * @author nik */ public interface XLineBreakpoint

extends XBreakpoint

{ diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpointType.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpointType.java index 6baa0227f003..3c5232c51973 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpointType.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpointType.java @@ -34,6 +34,15 @@ import java.util.List; import java.util.Collections; /** + * Implement this class to support new type of line breakpoints. An implementation should be registered in a plugin.xml: + *

+ * <extensions defaultExtensionNs="com.intellij">
+ *   <xdebugger.breakpointType implementation="qualified-class-name"/>
+ * </extensions> + * + * In order to support actual setting breakpoints in a debugging process create a {@link XBreakpointHandler} implementation and return it + * from {@link com.intellij.xdebugger.XDebugProcess#getBreakpointHandlers()} method + * * @author nik */ public abstract class XLineBreakpointType

extends XBreakpointType,P> { @@ -42,16 +51,23 @@ public abstract class XLineBreakpointType

exten } /** - * @deprecated implement {@link XLineBreakpointType#canPutAt(com.intellij.openapi.vfs.VirtualFile, int, com.intellij.openapi.project.Project)} instead + * @deprecated implement {@link #canPutAt(com.intellij.openapi.vfs.VirtualFile, int, com.intellij.openapi.project.Project)} instead */ public boolean canPutAt(@NotNull VirtualFile file, int line) { return false; } + /** + * Return true if breakpoint can be put on line in file + */ public boolean canPutAt(@NotNull VirtualFile file, int line, @NotNull Project project) { return canPutAt(file, line); } + /** + * return non-null value if a breakpoint should have specific properties besides containing file and line. These properties will be stored in + * {@link XBreakpoint} instance and can be obtained by using {@link XBreakpoint#getProperties()} method + */ public abstract P createBreakpointProperties(@NotNull VirtualFile file, int line); public String getDisplayText(final XLineBreakpoint

breakpoint) { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/evaluation/XDebuggerEvaluator.java b/platform/xdebugger-api/src/com/intellij/xdebugger/evaluation/XDebuggerEvaluator.java index 3e5857bbce46..e17f3b6c2e3e 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/evaluation/XDebuggerEvaluator.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/evaluation/XDebuggerEvaluator.java @@ -69,7 +69,7 @@ public abstract class XDebuggerEvaluator { } /** - * @deprecated override {@link XDebuggerEvaluator#evaluate(String, XEvaluationCallback, com.intellij.xdebugger.XSourcePosition)} instead + * @deprecated override {@link #evaluate(String, XEvaluationCallback, com.intellij.xdebugger.XSourcePosition)} instead */ @Deprecated public void evaluate(@NotNull String expression, XEvaluationCallback callback) { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XCompositeNode.java b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XCompositeNode.java index 49828556d02a..badc500ae727 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XCompositeNode.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XCompositeNode.java @@ -21,6 +21,10 @@ import org.jetbrains.annotations.NotNull; import java.util.List; /** + * Represents a node with children in a debugger tree. This interface isn't supposed to be implemented by a plugin. + * + * @see XValueContainer + * * @author nik */ public interface XCompositeNode extends Obsolescent { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XExecutionStack.java b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XExecutionStack.java index b3b6f3f18549..4188ee1fb88d 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XExecutionStack.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XExecutionStack.java @@ -24,6 +24,9 @@ import javax.swing.*; import java.util.List; /** + * Represents a stack of executions frames usually corresponding to a thread. It is shown in 'Frames' panel of + * 'Debug' tool window + * * @author nik */ public abstract class XExecutionStack { @@ -58,7 +61,8 @@ public abstract class XExecutionStack { public abstract XStackFrame getTopFrame(); /** - * Start computing stack frames top-down starting from firstFrameIndex + * Start computing stack frames top-down starting from firstFrameIndex. This method is called from the Event Dispatch Thread + * so it should return quickly * @param firstFrameIndex frame index to start from (1 corresponds to the frame just under the top frame) * @param container callback */ diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XStackFrame.java b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XStackFrame.java index 2a369dffa31f..82b97af99f7c 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XStackFrame.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XStackFrame.java @@ -25,11 +25,16 @@ import com.intellij.xdebugger.ui.DebuggerIcons; import org.jetbrains.annotations.Nullable; /** + * Represents a frame of execution stack. The selected frame is shown in 'Variables' panel of 'Debug' tool window. + * Override {@link XValueContainer#computeChildren} to show local variable, parameters, fields available in the frame + * * @author nik */ public abstract class XStackFrame extends XValueContainer { /** + * If stack frame is not changed after step expanded nodes and selection will be restored in 'Variables' tree. A stack frame is assumed + * unchanged if this method return equal non-null values before and after step * @return an object which will be used to determine if stack frame changed after step */ @Nullable diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XSuspendContext.java b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XSuspendContext.java index 008f112ed875..4406ea69276a 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XSuspendContext.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XSuspendContext.java @@ -18,10 +18,16 @@ package com.intellij.xdebugger.frame; import org.jetbrains.annotations.Nullable; /** + * Represents a suspended state of a debug process + * * @author nik */ public abstract class XSuspendContext { + /** + * Returned execution stack will be selected by default in 'Frames' panel of 'Debug' tool window. Also it will be used to obtain current + * stack frame to perform 'Evaluate' action, for example + */ @Nullable public XExecutionStack getActiveExecutionStack() { return null; diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValue.java b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValue.java index 7b8ce4d87e60..74b7221a7bdb 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValue.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValue.java @@ -19,6 +19,9 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** + * Represents a value in debugger tree. + * Override {@link XValueContainer#computeChildren} if value has a properties which should be shown as child nodes + * * @author nik */ public abstract class XValue extends XValueContainer { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueModifier.java b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueModifier.java index 6a1f8829755c..e4f90b8fa1a6 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueModifier.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueModifier.java @@ -24,7 +24,7 @@ import org.jetbrains.annotations.Nullable; public abstract class XValueModifier { /** - * Start modification of the value. + * Start modification of the value. Note that this methods is called from the Event Dispatch Thread so it should return quickly * @param expression new value * @param callback used to notify that value has been successfully modified or an error occurs */ diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueNode.java b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueNode.java index e957ded9a771..66394a03892a 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueNode.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueNode.java @@ -23,6 +23,10 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; /** + * Represents a node in debugger tree. This interface isn't supposed to be implemented by a plugin. + * + * @see XValue + * * @author nik */ public interface XValueNode extends Obsolescent { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/package.html b/platform/xdebugger-api/src/com/intellij/xdebugger/package.html new file mode 100644 index 000000000000..558808105d34 --- /dev/null +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/package.html @@ -0,0 +1,27 @@ + + + + +

API for integration with debuggers of custom languages/frameworks

+ + {@link com.intellij.xdebugger.XDebugProcess} is the main class which need to be extended to support debugging
+ + Implement {@link com.intellij.xdebugger.breakpoints.XLineBreakpointType} to support new type of breakpoints
+ + Use {@link com.intellij.xdebugger.settings.XDebuggerSettings} to provide settings + + From efb9c4f2dd4167f16f12b4b7d3eecec96b57888d Mon Sep 17 00:00:00 2001 From: Kirill Kalishev Date: Thu, 18 Feb 2010 15:31:32 +0300 Subject: [PATCH 38/93] treeui: thread violations for background loading --- .../ide/util/treeView/AbstractTreeUi.java | 45 ++++++++++++++----- 1 file changed, 34 insertions(+), 11 deletions(-) diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java index 928d187f6e1c..dd3c9f3da0be 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java @@ -268,6 +268,25 @@ public class AbstractTreeUi { } } + private ActionCallback invokeLaterIfNeeded(@NotNull final Runnable runnable) { + final ActionCallback result = new ActionCallback(); + + Runnable actual = new Runnable() { + public void run() { + runnable.run(); + result.setDone(); + } + }; + + if (isPassthroughMode() || (!isEdt() && !isTreeShowing())) { + actual.run(); + } else { + UIUtil.invokeLaterIfNeeded(actual); + } + + return result; + } + public void activate(boolean byShowing) { cancelCurrentCleanupTask(); @@ -1896,13 +1915,17 @@ public class AbstractTreeUi { final Runnable finalizeRunnable = new Runnable() { public void run() { - removeLoading(node, true); - removeFromLoadedInBackground(elementFromDescriptor.get()); - removeFromLoadedInBackground(oldElementFromDescriptor); + invokeLaterIfNeeded(new Runnable() { + public void run() { + removeLoading(node, true); + removeFromLoadedInBackground(elementFromDescriptor.get()); + removeFromLoadedInBackground(oldElementFromDescriptor); - if (nodeToProcessActions[0] != null) { - processNodeActionsIfReady(nodeToProcessActions[0]); - } + if (nodeToProcessActions[0] != null) { + processNodeActionsIfReady(nodeToProcessActions[0]); + } + } + }); } }; @@ -2062,7 +2085,7 @@ public class AbstractTreeUi { List secondary = secondaryNodeAction != null ? secondaryNodeAction.get(element) : null; for (NodeAction each : actions) { if (secondary != null && secondary.contains(each)) { - secondary.remove(each); + secondary.remove(each); } each.onReady(node); } @@ -2266,7 +2289,7 @@ public class AbstractTreeUi { NodeDescriptor parentDescriptor = getDescriptorFrom(parentNode); if (parentDescriptor != null) { parentDescriptor.setChildrenSortingStamp(-1); - } + } } if (index == null) { @@ -2867,7 +2890,7 @@ public class AbstractTreeUi { final Runnable onDone, final boolean addToSelection, boolean scroll) { - _select(elements, onDone, addToSelection, true, false, scroll, false, true, true); + _select(elements, onDone, addToSelection, true, false, scroll, false, true, true); } void _select(final Object[] elements, @@ -3924,7 +3947,7 @@ public class AbstractTreeUi { } } - + public void setPassthroughMode(boolean passthrough) { myPassthroughMode = passthrough; AbstractTreeUpdater updater = getUpdater(); @@ -3967,5 +3990,5 @@ public class AbstractTreeUi { } }); } - + } From 5ecfdd2b155c2bfd3d94925f2db99a6016600f15 Mon Sep 17 00:00:00 2001 From: "sergey.vasiliev" Date: Thu, 18 Feb 2010 15:39:10 +0300 Subject: [PATCH 39/93] projects tree navigation && override dependency action --- .../generation/MemberChooserObjectBase.java | 2 +- .../dom/MavenDomProjectProcessorUtils.java | 16 ++ .../idea/maven/dom/MavenDomUtil.java | 24 +-- .../annotator/MavenDomGutterAnnotator.java | 78 +++++++++- .../generate/GenerateDependencyAction.java | 7 +- .../dom/generate/GenerateDependencyUtil.java | 140 ++++++++++++++++++ .../GenerateOverridingDependencyAction.java | 111 ++++++++++++++ .../dom/generate/GenerateParentAction.java | 3 +- .../maven/project/MavenProjectsManager.java | 11 +- .../idea/maven/utils/MavenIcons.java | 4 + .../src/main/resources/DomBundle.properties | 12 +- .../src/main/resources/META-INF/plugin.xml | 3 +- .../resources/images/childrenProjects.png | Bin 0 -> 544 bytes .../main/resources/images/parentProject.png | Bin 0 -> 504 bytes .../generate/GenerateDomElementAction.java | 11 +- 15 files changed, 398 insertions(+), 24 deletions(-) create mode 100644 plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyUtil.java create mode 100644 plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateOverridingDependencyAction.java create mode 100644 plugins/maven/src/main/resources/images/childrenProjects.png create mode 100644 plugins/maven/src/main/resources/images/parentProject.png diff --git a/platform/lang-api/src/com/intellij/codeInsight/generation/MemberChooserObjectBase.java b/platform/lang-api/src/com/intellij/codeInsight/generation/MemberChooserObjectBase.java index b35af75a8eee..9a4c2dd9c769 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/generation/MemberChooserObjectBase.java +++ b/platform/lang-api/src/com/intellij/codeInsight/generation/MemberChooserObjectBase.java @@ -38,7 +38,7 @@ public class MemberChooserObjectBase implements MemberChooserObject { } public void renderTreeNode(SimpleColoredComponent component, JTree tree) { - component.append(myText, getTextAttributes(tree)); + component.append(getText(), getTextAttributes(tree)); component.setIcon(myIcon); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java index 1330d20832cc..2b7f2c80025a 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java @@ -130,6 +130,22 @@ public class MavenDomProjectProcessorUtils { } } + @NotNull + public static Set collectManagingDependencies(@NotNull MavenDomProjectModel model) { + final Set dependencies = new HashSet(); + + Processor collectProcessor = new Processor() { + public boolean process(MavenDomDependencies mavenDomDependencies) { + dependencies.addAll(mavenDomDependencies.getDependencies()); + return false; + } + }; + + processDependenciesInDependencyManagement(model, collectProcessor, model.getManager().getProject()); + + return dependencies; + } + @Nullable public static MavenDomDependency searchManagingDependency(@NotNull final MavenDomDependency dependency, @NotNull final Project project) { final MavenDomDependency[] parent = new MavenDomDependency[]{null}; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java index 0831c343211c..fa84377f670e 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java @@ -18,7 +18,6 @@ package org.jetbrains.idea.maven.dom; import com.intellij.lang.properties.psi.PropertiesFile; import com.intellij.lang.properties.psi.Property; import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; @@ -30,8 +29,8 @@ import com.intellij.openapi.vfs.VirtualFileSystem; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; -import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.XmlElement; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; @@ -58,9 +57,9 @@ public class MavenDomUtil { if (!(file instanceof XmlFile)) return false; String name = file.getName(); - return name.equals(MavenConstants.POM_XML) - || name.endsWith("." + MavenConstants.POM_EXTENSION) - || name.equals(MavenConstants.SUPER_POM_XML); + return name.equals(MavenConstants.POM_XML) || + name.endsWith("." + MavenConstants.POM_EXTENSION) || + name.equals(MavenConstants.SUPER_POM_XML); } public static boolean isProfilesFile(PsiFile file) { @@ -88,8 +87,7 @@ public class MavenDomUtil { } public static String calcRelativePath(VirtualFile parent, VirtualFile child) { - String result = FileUtil.getRelativePath(new File(parent.getPath()), - new File(child.getPath())); + String result = FileUtil.getRelativePath(new File(parent.getPath()), new File(child.getPath())); return FileUtil.toSystemIndependentName(result); } @@ -313,16 +311,22 @@ public class MavenDomUtil { @NotNull - public static MavenDomDependency createDomDependency(MavenDomProjectModel model, MavenArtifact mavenArtifact, Editor editor) { + public static MavenDomDependency createDomDependency(MavenDomProjectModel model, + MavenArtifact mavenArtifact, + Editor editor, + boolean overriden) { MavenDomDependency domDependency = createMavenDomDependency(model, editor); domDependency.getGroupId().setStringValue(mavenArtifact.getGroupId()); domDependency.getArtifactId().setStringValue(mavenArtifact.getArtifactId()); - domDependency.getVersion().setStringValue(mavenArtifact.getVersion()); + if (!overriden) { + domDependency.getVersion().setStringValue(mavenArtifact.getVersion()); + } return domDependency; } + @NotNull private static MavenDomDependency createMavenDomDependency(@NotNull MavenDomProjectModel model, @Nullable Editor editor) { MavenDomDependencies dependencies = model.getDependencies(); @@ -359,6 +363,4 @@ public class MavenDomUtil { } return -1; } - - } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomGutterAnnotator.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomGutterAnnotator.java index 120bcbbfb52f..ce6193c30fa2 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomGutterAnnotator.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomGutterAnnotator.java @@ -24,16 +24,24 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.xml.XmlTag; +import com.intellij.util.Function; import com.intellij.util.NotNullFunction; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.DomManager; +import com.intellij.util.xml.DomUtil; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.dom.MavenDomBundle; import org.jetbrains.idea.maven.dom.MavenDomProjectProcessorUtils; +import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.dom.model.MavenDomDependency; import org.jetbrains.idea.maven.dom.model.MavenDomDependencyManagement; +import org.jetbrains.idea.maven.dom.model.MavenDomParent; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; +import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.project.MavenProject; +import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.utils.MavenIcons; import javax.swing.*; @@ -53,7 +61,7 @@ public class MavenDomGutterAnnotator implements Annotator { if (model != null) { String name = model.getName().getStringValue(); if (!StringUtil.isEmptyOrSpaces(name)) { - return name; + return name; } } } @@ -86,6 +94,16 @@ public class MavenDomGutterAnnotator implements Annotator { } }; + private static final NotNullFunction> MAVEN_PROJECT_CONVERTER = + new NotNullFunction>() { + + @NotNull + public Collection fun(final MavenDomProjectModel pointer) { + return ContainerUtil.createMaybeSingletonList(pointer.getXmlTag()); + } + }; + + private static void annotateDependencyUsages(@NotNull MavenDomDependency dependency, AnnotationHolder holder) { final XmlTag tag = dependency.getXmlTag(); if (tag == null) return; @@ -103,8 +121,6 @@ public class MavenDomGutterAnnotator implements Annotator { } } - - private static void annotateManagedDependency(MavenDomDependency dependency, AnnotationHolder holder) { final XmlTag tag = dependency.getXmlTag(); if (tag == null) return; @@ -142,14 +158,66 @@ public class MavenDomGutterAnnotator implements Annotator { if (element instanceof MavenDomDependency) { MavenDomDependency dependency = (MavenDomDependency)element; if (isDependencyManagementSection(dependency)) { - annotateDependencyUsages(dependency, holder); - } else { + annotateDependencyUsages(dependency, holder); + } + else { annotateManagedDependency(dependency, holder); } } + else if (element instanceof MavenDomParent) { + annotateMavenDomParent((MavenDomParent)element, holder); + } + else if (element instanceof MavenDomProjectModel) { + annotateMavenDomProjectChildren((MavenDomProjectModel)element, holder); + } } } + private static void annotateMavenDomParent(@NotNull MavenDomParent mavenDomParent, @NotNull AnnotationHolder holder) { + MavenDomProjectModel parent = findParent(mavenDomParent, mavenDomParent.getManager().getProject()); + + if (parent != null) { + NavigationGutterIconBuilder.create(MavenIcons.PARENT_PROJECT, MAVEN_PROJECT_CONVERTER). + setTargets(parent). + setTooltipText(MavenDomBundle.message("parent.pom.title")). + install(holder, mavenDomParent.getXmlElement()); + } + } + + private static void annotateMavenDomProjectChildren(MavenDomProjectModel model, AnnotationHolder holder) { + MavenProject mavenProject = MavenDomUtil.findProject(model); + if (mavenProject != null) { + final Project project = model.getManager().getProject(); + Set inheritors = MavenProjectsManager.getInstance(project).findInheritors(mavenProject); + + + List children = ContainerUtil.mapNotNull(inheritors, new Function() { + public MavenDomProjectModel fun(MavenProject childProject) { + return MavenDomUtil.getMavenDomProjectModel(project, childProject.getFile()); + } + }); + if (children.size() > 0) { + NavigationGutterIconBuilder.create(MavenIcons.CHILDREN_PROJECTS, MAVEN_PROJECT_CONVERTER). + setTargets(children). + setCellRenderer(RENDERER). + setPopupTitle(MavenDomBundle.message("navigate.children.poms.title")). + setTooltipText(MavenDomBundle.message("children.poms.title")). + install(holder, model.getXmlElement()); + } + } + } + + @Nullable + public static MavenDomProjectModel findParent(@NotNull MavenDomParent mavenDomParent, Project project) { + if (!DomUtil.hasXml(mavenDomParent)) return null; + + MavenId id = new MavenId(mavenDomParent.getGroupId().getStringValue(), mavenDomParent.getArtifactId().getStringValue(), + mavenDomParent.getVersion().getStringValue()); + MavenProject mavenProject = MavenProjectsManager.getInstance(project).findProject(id); + + return mavenProject != null ? MavenDomUtil.getMavenDomProjectModel(project, mavenProject.getFile()) : null; + } + private static boolean isDependencyManagementSection(@NotNull MavenDomDependency dependency) { return dependency.getParentOfType(MavenDomDependencyManagement.class, false) != null; } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyAction.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyAction.java index 8df51e6b700d..313848c9281c 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyAction.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyAction.java @@ -18,15 +18,18 @@ package org.jetbrains.idea.maven.dom.generate; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiDocumentManager; import com.intellij.util.xml.ui.actions.generate.GenerateDomElementAction; +import org.jetbrains.idea.maven.dom.MavenDomBundle; +import org.jetbrains.idea.maven.dom.model.MavenDomBuild; import org.jetbrains.idea.maven.project.MavenId; import org.jetbrains.idea.maven.dom.model.MavenDomDependency; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; import org.jetbrains.idea.maven.indices.MavenArtifactSearchDialog; import org.jetbrains.idea.maven.project.MavenProjectsManager; +import org.jetbrains.idea.maven.utils.MavenIcons; public class GenerateDependencyAction extends GenerateDomElementAction { public GenerateDependencyAction() { - super(new MavenGenerateProvider("Generate Dependency", MavenDomDependency.class) { + super(new MavenGenerateProvider(MavenDomBundle.message("generate.dependency"), MavenDomDependency.class) { @Override protected MavenDomDependency doGenerate(MavenDomProjectModel mavenModel, Editor editor) { MavenId id = MavenArtifactSearchDialog.searchForArtifact(editor.getProject()); @@ -37,7 +40,7 @@ public class GenerateDependencyAction extends GenerateDomElementAction { MavenProjectsManager manager = MavenProjectsManager.getInstance(editor.getProject()); return manager.addDependency(manager.findProject(mavenModel.getModule()), id); } - }); + }, MavenIcons.DEPENDENCY_ICON); } @Override diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyUtil.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyUtil.java new file mode 100644 index 000000000000..d47b6fafcd54 --- /dev/null +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyUtil.java @@ -0,0 +1,140 @@ +/* + * 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 org.jetbrains.idea.maven.dom.generate; + +import com.intellij.codeInsight.generation.ClassMember; +import com.intellij.codeInsight.generation.MemberChooserObject; +import com.intellij.codeInsight.generation.MemberChooserObjectBase; +import com.intellij.codeInsight.generation.PsiElementMemberChooserObject; +import com.intellij.ide.util.MemberChooser; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.psi.PsiFile; +import com.intellij.util.Function; +import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.idea.maven.dom.MavenDomBundle; +import org.jetbrains.idea.maven.dom.model.MavenDomDependency; +import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; +import org.jetbrains.idea.maven.utils.MavenIcons; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * @author Serega.Vasiliev + */ +public class GenerateDependencyUtil { + private GenerateDependencyUtil() { + } + + @NotNull + public static List chooseDependencies(Collection candidates, final Project project) { + List dependencies = new ArrayList(); + + MavenDomProjectModelMember[] memberCandidates = + ContainerUtil.map2Array(candidates, MavenDomProjectModelMember.class, new Function() { + public MavenDomProjectModelMember fun(MavenDomDependency dependency) { + return new MavenDomProjectModelMember(dependency); + } + }); + MemberChooser chooser = + new MemberChooser(memberCandidates, true, true, project) { + protected ShowContainersAction getShowContainersAction() { + return new ShowContainersAction(MavenDomBundle.message("chooser.show.project.files"), MavenIcons.MAVEN_PROJECT_ICON); + } + + protected String getAllContainersNodeName() { + return MavenDomBundle.message("all.dependencies"); + } + }; + + chooser.setTitle(MavenDomBundle.message("dependencies.chooser.title")); + chooser.setCopyJavadocVisible(false); + chooser.show(); + + if (chooser.getExitCode() == MemberChooser.OK_EXIT_CODE) { + final MavenDomProjectModelMember[] members = chooser.getSelectedElements(new MavenDomProjectModelMember[0]); + if (members != null) { + dependencies.addAll(ContainerUtil.mapNotNull(members, new Function() { + public MavenDomDependency fun(MavenDomProjectModelMember mavenDomProjectModelMember) { + return mavenDomProjectModelMember.getDependency(); + } + })); + } + } + + return dependencies; + } + + private static class MavenDomProjectModelMember extends MemberChooserObjectBase implements ClassMember { + private final MavenDomDependency myDependency; + + public MavenDomProjectModelMember(final MavenDomDependency dependency) { + super(dependency.toString(), MavenIcons.DEPENDENCY_ICON); + myDependency = dependency; + } + + @Override + public String getText() { + StringBuffer sb = new StringBuffer(); + + append(sb, myDependency.getGroupId().getStringValue()); + append(sb, myDependency.getArtifactId().getStringValue()); + append(sb, myDependency.getVersion().getStringValue()); + + return sb.toString(); + } + + private static void append(StringBuffer sb, String str) { + if (!StringUtil.isEmptyOrSpaces(str)) { + if (sb.length() > 0) sb.append(": "); + sb.append(str); + } + } + + public MemberChooserObject getParentNodeDelegate() { + MavenDomDependency dependency = getDependency(); + + return new MavenDomProjectModelFileMemberChooserObjectBase(dependency.getXmlTag().getContainingFile(), + getProjectName(dependency)); + } + + @Nullable + private static String getProjectName(@Nullable MavenDomDependency dependency) { + if (dependency != null) { + MavenDomProjectModel model = dependency.getParentOfType(MavenDomProjectModel.class, false); + if (model != null) { + return model.getName().getStringValue(); + } + } + return null; + } + + public MavenDomDependency getDependency() { + return myDependency; + } + + private static class MavenDomProjectModelFileMemberChooserObjectBase extends PsiElementMemberChooserObject { + + public MavenDomProjectModelFileMemberChooserObjectBase(@NotNull final PsiFile psiFile, @Nullable String projectName) { + super(psiFile, StringUtil.isEmptyOrSpaces(projectName) ? psiFile.getName() : projectName, MavenIcons.MAVEN_PROJECT_ICON); + } + } + } +} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateOverridingDependencyAction.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateOverridingDependencyAction.java new file mode 100644 index 000000000000..5e9ebb68ed12 --- /dev/null +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateOverridingDependencyAction.java @@ -0,0 +1,111 @@ +/* + * 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 org.jetbrains.idea.maven.dom.generate; + +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.util.Processor; +import com.intellij.util.containers.hash.HashSet; +import com.intellij.util.xml.ui.actions.generate.GenerateDomElementAction; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.idea.maven.dom.MavenDomBundle; +import org.jetbrains.idea.maven.dom.MavenDomProjectProcessorUtils; +import org.jetbrains.idea.maven.dom.model.MavenDomDependencies; +import org.jetbrains.idea.maven.dom.model.MavenDomDependency; +import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; +import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.project.MavenProjectsManager; +import org.jetbrains.idea.maven.utils.MavenIcons; + +import java.util.List; +import java.util.Set; + +public class GenerateOverridingDependencyAction extends GenerateDomElementAction { + public GenerateOverridingDependencyAction() { + super(new MavenOverridingDependencyGenerateProvider(), MavenIcons.DEPENDENCY_ICON); + } + + @Override + protected boolean startInWriteAction() { + return false; + } + + private static class MavenOverridingDependencyGenerateProvider extends MavenGenerateProvider { + public MavenOverridingDependencyGenerateProvider() { + super(MavenDomBundle.message("override.dependency"), MavenDomDependency.class); + } + + @Override + protected MavenDomDependency doGenerate(MavenDomProjectModel mavenModel, Editor editor) { + Set managingDependencies = collectManagingDependencies(mavenModel); + + List dependenciesToOverride = GenerateDependencyUtil.chooseDependencies(managingDependencies, mavenModel.getManager().getProject()); + + for (MavenDomDependency parentDependency : dependenciesToOverride) { + String groupId = parentDependency.getGroupId().getStringValue(); + String artifactId = parentDependency.getArtifactId().getStringValue(); + + if (!StringUtil.isEmptyOrSpaces(groupId) && !StringUtil.isEmptyOrSpaces(artifactId)) { + MavenId id = new MavenId(groupId, artifactId, parentDependency.getVersion().getStringValue()); + + MavenProjectsManager manager = MavenProjectsManager.getInstance(editor.getProject()); + + MavenDomDependency dependency = manager.addOverridenDependency(manager.findProject(mavenModel.getModule()), id); + + dependency.getVersion().undefine(); + } + + } + + return null; + } + } + + @NotNull + public static Set collectManagingDependencies(@NotNull MavenDomProjectModel model) { + final Set dependencies = new HashSet(); + + final List existingDependencies = model.getDependencies().getDependencies(); + + Processor collectProcessor = new Processor() { + public boolean process(MavenDomDependencies mavenDomDependencies) { + for (MavenDomDependency dependency : mavenDomDependencies.getDependencies()) { + String groupId = dependency.getGroupId().getStringValue(); + String artifactId = dependency.getArtifactId().getStringValue(); + if (StringUtil.isEmptyOrSpaces(groupId) || StringUtil.isEmptyOrSpaces(artifactId)) continue; + + if (!isDependencyExist(groupId, artifactId, existingDependencies)) { + dependencies.add(dependency); + } + } + return false; + } + }; + + MavenDomProjectProcessorUtils.processDependenciesInDependencyManagement(model, collectProcessor, model.getManager().getProject()); + + return dependencies; + } + + private static boolean isDependencyExist(String groupId, String artifactId, List existingDependencies) { + for (MavenDomDependency existingDependency : existingDependencies) { + if(groupId.equals(existingDependency.getGroupId().getStringValue()) || artifactId.equals(existingDependency.getArtifactId().getStringValue())) { + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateParentAction.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateParentAction.java index 5ebc26e8afc9..237e3028541a 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateParentAction.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateParentAction.java @@ -25,6 +25,7 @@ import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; import org.jetbrains.idea.maven.dom.model.MavenDomParent; import org.jetbrains.idea.maven.navigator.SelectMavenProjectDialog; import org.jetbrains.idea.maven.project.MavenProject; +import org.jetbrains.idea.maven.utils.MavenIcons; public class GenerateParentAction extends GenerateDomElementAction { public GenerateParentAction() { @@ -47,7 +48,7 @@ public class GenerateParentAction extends GenerateDomElementAction { protected boolean isAvailableForModel(MavenDomProjectModel mavenModel) { return !DomUtil.hasXml(mavenModel.getMavenParent()); } - }); + }, MavenIcons.MAVEN_PROJECT_ICON); } @Override diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java index d4155ccaef0b..22b401b455a1 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java @@ -984,7 +984,16 @@ public class MavenProjectsManager extends SimpleProjectComponent return result; } + public MavenDomDependency addOverridenDependency(final MavenProject mavenProject, final MavenId id) { + return addDependency(mavenProject, id, true); + } + + public MavenDomDependency addDependency(final MavenProject mavenProject, final MavenId id) { + return addDependency(mavenProject, id, false); + } + + public MavenDomDependency addDependency(final MavenProject mavenProject, final MavenId id, final boolean overriden) { final MavenArtifact[] artifact = new MavenArtifact[1]; try { @@ -1005,7 +1014,7 @@ public class MavenProjectsManager extends SimpleProjectComponent protected void run(Result result) throws Throwable { MavenDomProjectModel model = MavenDomUtil.getMavenDomProjectModel(myProject, mavenProject.getFile()); - MavenDomDependency domDependency = MavenDomUtil.createDomDependency(model, artifact[0], getEditor()); + MavenDomDependency domDependency = MavenDomUtil.createDomDependency(model, artifact[0], getEditor(), overriden); mavenProject.addDependency(artifact[0]); result.setResult(domDependency); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenIcons.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenIcons.java index ee7ef71b30ae..0350b6dd5c9c 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenIcons.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenIcons.java @@ -22,6 +22,7 @@ import javax.swing.*; public class MavenIcons { public static final Icon MAVEN_ICON = IconLoader.getIcon("/images/mavenLogo.png"); public static final Icon MAVEN_PROJECT_ICON = IconLoader.getIcon("/images/mavenProject.png"); + public static final Icon OPEN_PROFILES_ICON = IconLoader.getIcon("/images/profilesOpen.png"); public static final Icon CLOSED_PROFILES_ICON = IconLoader.getIcon("/images/profilesClosed.png"); public static final Icon OPEN_PHASES_ICON = IconLoader.getIcon("/images/phasesOpen.png"); @@ -40,4 +41,7 @@ public class MavenIcons { public static final Icon OVERRIDING_DEPENDENCY = IconLoader.getIcon("/images/overridingDependency.png"); public static final Icon OVERRIDEN_DEPENDENCY = IconLoader.getIcon("/images/overridenDependency.png"); + + public static final Icon PARENT_PROJECT = IconLoader.getIcon("/images/parentProject.png"); + public static final Icon CHILDREN_PROJECTS = IconLoader.getIcon("/images/childrenProjects.png"); } diff --git a/plugins/maven/src/main/resources/DomBundle.properties b/plugins/maven/src/main/resources/DomBundle.properties index 3a284cc5c05b..c2375fb9e889 100644 --- a/plugins/maven/src/main/resources/DomBundle.properties +++ b/plugins/maven/src/main/resources/DomBundle.properties @@ -16,6 +16,16 @@ generate.dependency.group=Dependency (group) generate.plugin.artifact=Plugin (artifact) generate.plugin.group=Plugin (group) -overriden.dependency.title=Navigate to managing dependency + +overriden.dependency.title=Navigate to managing dependency overriding.dependency.title=Navigate to dependency usages navigate.parent.dependency.title=Choose dependency to navigate + +parent.pom.title=Navigate to parent +children.poms.title=Navigate to children projects +navigate.children.poms.title=Choose project +dependencies.chooser.title=Choose dependency +all.dependencies=All Dependencies +chooser.show.project.files=Project Files +override.dependency=Override Parent Dependency +generate.dependency=Dependency diff --git a/plugins/maven/src/main/resources/META-INF/plugin.xml b/plugins/maven/src/main/resources/META-INF/plugin.xml index 2113cd31ed00..b72eac68511c 100644 --- a/plugins/maven/src/main/resources/META-INF/plugin.xml +++ b/plugins/maven/src/main/resources/META-INF/plugin.xml @@ -351,7 +351,8 @@ - + + diff --git a/plugins/maven/src/main/resources/images/childrenProjects.png b/plugins/maven/src/main/resources/images/childrenProjects.png new file mode 100644 index 0000000000000000000000000000000000000000..62d6b64bbf990af081c05c97ff00e228be13a241 GIT binary patch literal 544 zcmV+*0^j|KP)^@$UJfJ=b6Sj7V$fXDG@o1S@jL z?PvJ;<0k{iQy?_}0R&d~`tjYFhYuZbRxz*sH>+psrAfJQO00a;ta_~s2 z>Spr@ia5Y*0T}=b9)JLXD}4Fv4nysXH~;?&Ycu@(_LkxG!+Q*~DkK;|a#0SF+lLWjuB{~53V=cEf@@mu?}7y$wZ z96Se>`+}|bFKP`m?I{BzBO`;Pjt2uoQ50AXAb{X*gqaLd3tgW^em0AhssT3X-NK~z>bT}V>S<@c{2|KB{mx8u{>m-C)p+0SF+luR$ioLj z=M*xulom2@ak4WQI0ne@35zFz)Bpq!*hI&a-q#mj{r~R}QtJo^9NDzM;x z?f(D&ZQ@#Afz$v55Ih_|erI6#2XyY+Zww5tzCqZ({vtdB5I|sGzkB{@&-E8SBhniB z8H#cX!HOJm`x$=z_{jkB6i5v~0D%?0etdW4;X_B9RSaxIo%8y^CV>>)I=tZt$mbw6 u00D#&JkqMV**t Date: Thu, 18 Feb 2010 16:40:24 +0300 Subject: [PATCH 40/93] ActionManager - timed updates go throught FocusManager -- to ensure focus is transferred --- .../openapi/actionSystem/impl/ActionManagerImpl.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java index 0048b5fde244..0bba9c872e5b 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java @@ -1163,10 +1163,14 @@ public final class ActionManagerImpl extends ActionManagerEx implements Applicat return; } - TimerListener[] listeners = myTimerListeners.toArray(new TimerListener[myTimerListeners.size()]); - for (TimerListener listener : listeners) { - runListenerAction(listener); - } + final TimerListener[] listeners = myTimerListeners.toArray(new TimerListener[myTimerListeners.size()]); + IdeFocusManager.getInstance(null).doWhenFocusSettlesDown(new Runnable() { + public void run() { + for (TimerListener listener : listeners) { + runListenerAction(listener); + } + } + }); } private void runListenerAction(final TimerListener listener) { From ee60915346fa8ce973e6c79b17ec37b46ad2cd60 Mon Sep 17 00:00:00 2001 From: Kirill Kalishev Date: Thu, 18 Feb 2010 16:44:24 +0300 Subject: [PATCH 41/93] RunnerLayoutUi NPE on updating inplace tab actions --- .../execution/ui/layout/actions/MoveToTabAction.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/platform/lang-impl/src/com/intellij/execution/ui/layout/actions/MoveToTabAction.java b/platform/lang-impl/src/com/intellij/execution/ui/layout/actions/MoveToTabAction.java index f99a1942e756..bf20c5280fe9 100644 --- a/platform/lang-impl/src/com/intellij/execution/ui/layout/actions/MoveToTabAction.java +++ b/platform/lang-impl/src/com/intellij/execution/ui/layout/actions/MoveToTabAction.java @@ -35,6 +35,12 @@ public class MoveToTabAction extends BaseViewAction { } Grid grid = context.findGridFor(content[0]); + if (grid == null) { + setEnabled(e, false); + return; + } + + Tab tab = context.getTabFor(grid); if (ViewContext.TAB_TOOLBAR_PLACE.equals(e.getPlace())) { From fb306af6216fff9c3cb7f5ce71ca1d9b62e4320a Mon Sep 17 00:00:00 2001 From: Alexey Pegov Date: Thu, 18 Feb 2010 17:10:45 +0300 Subject: [PATCH 42/93] minor --- .../codeInspection/GlobalInspectionUtil.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/platform/lang-impl/src/com/intellij/codeInspection/GlobalInspectionUtil.java b/platform/lang-impl/src/com/intellij/codeInspection/GlobalInspectionUtil.java index b5b0a077e8ed..43c7e51950cf 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/GlobalInspectionUtil.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/GlobalInspectionUtil.java @@ -56,4 +56,18 @@ public class GlobalInspectionUtil { descriptor ); } + + public static void createProblem(PsiElement elt, String message, ProblemHighlightType problemHighlightType, TextRange range, + InspectionManager manager, ProblemDescriptionsProcessor problemDescriptionsProcessor, + GlobalInspectionContext globalContext, LocalQuickFix fix) { + ProblemDescriptor descriptor = manager.createProblemDescriptor( + elt, + range, + createInspectionMessage(message), + problemHighlightType, false, fix); + problemDescriptionsProcessor.addProblemElement( + retrieveRefElement(elt, globalContext), + descriptor + ); + } } From e9d43779a25fcadfe1c012e4f73341453449afcb Mon Sep 17 00:00:00 2001 From: "Kirill.Safonov" Date: Thu, 18 Feb 2010 21:08:09 +0300 Subject: [PATCH 43/93] (S)FTP sync: actions, improvements, performance, WI-1117 --- .../src/com/intellij/openapi/actionSystem/ActionPlaces.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionPlaces.java b/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionPlaces.java index 9be902f8afd7..0ec1b550cae2 100644 --- a/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionPlaces.java +++ b/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionPlaces.java @@ -95,6 +95,8 @@ public abstract class ActionPlaces { public static final String CHANGES_VIEW_TOOLBAR = "ChangesViewToolbar"; public static final String CHANGES_VIEW_POPUP = "ChangesViewPopup"; + public static final String REMOTE_HOST_VIEW_POPUP = "RemoteHostPopup"; + public static final String REMOTE_HOST_DIALOG_POPUP = "RemoteHostDialogPopup"; private static final String[] ourToolbarPlaces = new String[]{PROJECT_VIEW_TOOLBAR, TESTTREE_VIEW_TOOLBAR, MAIN_TOOLBAR, ANT_EXPLORER_TOOLBAR, ANT_MESSAGES_TOOLBAR, COMPILER_MESSAGES_TOOLBAR, TODO_VIEW_TOOLBAR, STRUCTURE_VIEW_TOOLBAR, USAGE_VIEW_TOOLBAR, @@ -110,7 +112,7 @@ public abstract class ActionPlaces { METHOD_HIERARCHY_VIEW_POPUP, CALL_HIERARCHY_VIEW_POPUP, J2EE_ATTRIBUTES_VIEW_POPUP, J2EE_VIEW_POPUP, USAGE_VIEW_POPUP, STRUCTURE_VIEW_POPUP, TODO_VIEW_POPUP, COMPILER_MESSAGES_POPUP, ANT_MESSAGES_POPUP, ANT_EXPLORER_POPUP, UPDATE_POPUP, FILEVIEW_POPUP, CHECKOUT_POPUP, LVCS_DIRECTORY_HISTORY_POPUP, GUI_DESIGNER_EDITOR_POPUP, GUI_DESIGNER_COMPONENT_TREE_POPUP, GUI_DESIGNER_PROPERTY_INSPECTOR_POPUP, - CREATE_EJB_POPUP, CHANGES_VIEW_POPUP, + CREATE_EJB_POPUP, CHANGES_VIEW_POPUP, REMOTE_HOST_VIEW_POPUP, REMOTE_HOST_DIALOG_POPUP, }; public static boolean isPopupPlace(@NotNull String place) { From bb0d8c80ced202352afe2cd14e7ffdf06918dfe8 Mon Sep 17 00:00:00 2001 From: Eugene Zhuravlev Date: Thu, 18 Feb 2010 17:18:56 +0300 Subject: [PATCH 44/93] fix NotNull assertion --- .../engine/evaluation/expression/EvaluatorBuilderImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java index 3b7cec8c4d87..ae6252e4407f 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java @@ -1026,13 +1026,13 @@ public class EvaluatorBuilderImpl implements EvaluatorBuilder { final PsiType castType = expression.getCastType().getType(); final PsiType operandType = operandExpr.getType(); - if (!TypeConversionUtil.areTypesConvertible(operandType, castType)) { + if (castType != null && operandType != null && !TypeConversionUtil.areTypesConvertible(operandType, castType)) { throw new EvaluateRuntimeException( new EvaluateException(JavaErrorMessages.message("inconvertible.type.cast", HighlightUtil.formatType(operandType), HighlightUtil.formatType(castType))) ); } - final boolean shouldPerformBoxingConversion = TypeConversionUtil.boxingConversionApplicable(castType, operandType); + final boolean shouldPerformBoxingConversion = castType != null && operandType != null && TypeConversionUtil.boxingConversionApplicable(castType, operandType); final boolean castingToPrimitive = castType instanceof PsiPrimitiveType; if (shouldPerformBoxingConversion && castingToPrimitive) { operandEvaluator = new UnBoxingEvaluator(operandEvaluator); From 1e5afe6c528b485a780ca120126c05c503bddfce Mon Sep 17 00:00:00 2001 From: Eugene Zhuravlev Date: Thu, 18 Feb 2010 21:06:36 +0300 Subject: [PATCH 45/93] update inputId->keys map depending on the sate of "buffering" flag from the MemoryStorage. If buffering is on, all changes should be done in memory. Otherwise data in this auxiliary map will not be in sync with the data in the index on disk and further index updates will give unpretictable results (see IDEA-52223) --- .../util/indexing/FileBasedIndex.java | 71 +++++++++++++++++-- 1 file changed, 66 insertions(+), 5 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java index 224831a0bf30..621c60cdf5ff 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java @@ -321,7 +321,7 @@ public class FileBasedIndex implements ApplicationComponent { for (int attempt = 0; attempt < 2; attempt++) { try { final MapIndexStorage storage = new MapIndexStorage(IndexInfrastructure.getStorageFile(name), extension.getKeyDescriptor(), extension.getValueExternalizer(), extension.getCacheSize()); - final IndexStorage memStorage = new MemoryIndexStorage(storage); + final MemoryIndexStorage memStorage = new MemoryIndexStorage(storage); final UpdatableIndex index = createIndex(name, extension, memStorage); myIndices.put(name, new Pair, InputFilter>(index, new IndexableFilesFilter(extension.getInputFilter()))); myUnsavedDataIndexingSemaphores.put(name, new Semaphore()); @@ -382,7 +382,7 @@ public class FileBasedIndex implements ApplicationComponent { return new File(PathManager.getIndexRoot(), "work_in_progress"); } - private UpdatableIndex createIndex(final ID indexId, final FileBasedIndexExtension extension, final IndexStorage storage) throws IOException { + private UpdatableIndex createIndex(final ID indexId, final FileBasedIndexExtension extension, final MemoryIndexStorage storage) throws IOException { final MapReduceIndex index; if (extension instanceof CustomImplementationFileBasedIndexExtension) { final UpdatableIndex custom = @@ -400,7 +400,7 @@ public class FileBasedIndex implements ApplicationComponent { index.setInputIdToDataKeysIndex(new Factory>>() { public PersistentHashMap> create() { try { - return createIdToDataKeysIndex(indexId, keyDescriptor); + return createIdToDataKeysIndex(indexId, keyDescriptor, storage); } catch (IOException e) { throw new RuntimeException(e); @@ -411,9 +411,14 @@ public class FileBasedIndex implements ApplicationComponent { return index; } - private static PersistentHashMap> createIdToDataKeysIndex(ID indexId, final KeyDescriptor keyDescriptor) throws IOException { + private static PersistentHashMap> createIdToDataKeysIndex(ID indexId, + final KeyDescriptor keyDescriptor, + MemoryIndexStorage storage) throws IOException { final File indexStorageFile = IndexInfrastructure.getInputIndexStorageFile(indexId); - return new PersistentHashMap>(indexStorageFile, new EnumeratorIntegerDescriptor(), new DataExternalizer>() { + final Ref isBufferingMode = new Ref(false); + final Map> tempMap = new com.intellij.util.containers.HashMap>(); + + final DataExternalizer> dataExternalizer = new DataExternalizer>() { public void save(DataOutput out, Collection value) throws IOException { DataInputOutputUtil.writeINT(out, value.size()); for (K key : value) { @@ -429,7 +434,63 @@ public class FileBasedIndex implements ApplicationComponent { } return list; } + }; + + // Important! Update IdToDataKeysIndex depending on the sate of "buffering" flag from the MemoryStorage. + // If buffering is on, all changes should be done in memory (similar to the way it is done in memory storage). + // Otherwise data in IdToDataKeysIndex will not be in sync with the 'main' data in the index on disk and index updates will be based on the + // wrong sets of keys for the given file. This will lead to unpretictable results in main index because it will not be + // cleared properly before updating (removed data will still be present on disk). See IDEA-52223 for illustration of possible effects. + + final PersistentHashMap> map = new PersistentHashMap>( + indexStorageFile, new EnumeratorIntegerDescriptor(), dataExternalizer + ) { + + @Override + public synchronized Collection get(Integer integer) throws IOException { + if (isBufferingMode.get()) { + final Collection collection = tempMap.get(integer); + if (collection != null) { + return collection; + } + } + return super.get(integer); + } + + @Override + public synchronized void put(Integer integer, Collection ks) throws IOException { + if (isBufferingMode.get()) { + tempMap.put(integer, ks == null? Collections.emptySet() : ks); + } + else { + super.put(integer, ks); + } + } + + @Override + public synchronized void remove(Integer integer) throws IOException { + if (isBufferingMode.get()) { + tempMap.put(integer, Collections.emptySet()); + } + else { + super.remove(integer); + } + } + }; + + storage.addBufferingStateListsner(new MemoryIndexStorage.BufferingStateListener() { + public void bufferingStateChanged(boolean newState) { + synchronized (map) { + isBufferingMode.set(newState); + } + } + public void memoryStorageCleared() { + synchronized (map) { + tempMap.clear(); + } + } }); + return map; } @NonNls From 5a480f75919594a62dbba841b40b54e837d14c7a Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 18 Feb 2010 20:27:47 +0000 Subject: [PATCH 46/93] don't perform long type inference for displaying groovy method's return type in project/structure views (IDEA-27211) --- .../structure/GroovyElementPresentation.java | 103 ------------------ .../impl/GroovyFileStructureViewElement.java | 8 +- ...ovyTypeDefinitionStructureViewElement.java | 8 +- .../impl/GroovyFileItemPresentation.java | 34 ------ .../impl/GroovyMethodItemPresentation.java | 44 +++++--- .../GroovyTypeDefinitionItemPresentation.java | 34 ------ 6 files changed, 40 insertions(+), 191 deletions(-) delete mode 100644 plugins/groovy/src/org/jetbrains/plugins/groovy/structure/GroovyElementPresentation.java delete mode 100644 plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyFileItemPresentation.java delete mode 100644 plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyTypeDefinitionItemPresentation.java diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/GroovyElementPresentation.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/GroovyElementPresentation.java deleted file mode 100644 index fc10b97d7a0e..000000000000 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/GroovyElementPresentation.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.plugins.groovy.structure; - -import com.intellij.psi.*; -import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; -import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement; - -/** - * User: Dmitry.Krasilschikov - * Date: 21.05.2007 - */ -public class GroovyElementPresentation { - public static String getPresentableText(PsiElement element) { - assert element != null; - - if (element instanceof GroovyFileBase) { - return getFilePresentableText(((GroovyFileBase) element)); - - } else if (element instanceof GrTypeDefinition) { - return getTypeDefinitionPresentableText(((GrTypeDefinition) element)); - - } else if (element instanceof GrMethod) { - return getMethodPresentableText(((GrMethod) element)); - } else { - return element.getText(); - } - } - - public static String getVariablePresentableText(GrVariable variable) { - StringBuffer presentableText = new StringBuffer(); - - presentableText.append(variable.getName()); - GrTypeElement varTypeElement = variable.getTypeElementGroovy(); - - if (varTypeElement != null) { - PsiType varType = varTypeElement.getType(); - presentableText.append(":"); - presentableText.append(varType.getPresentableText()); - } - return presentableText.toString(); - } - - public static String getTypeDefinitionPresentableText(GrTypeDefinition typeDefinition) { - return typeDefinition.getNameIdentifierGroovy().getText(); - } - - public static String getMethodPresentableText(PsiMethod method) { - StringBuffer presentableText = new StringBuffer(); - presentableText.append(method.getName()); - presentableText.append(" "); - - PsiParameterList paramList = method.getParameterList(); - PsiParameter[] parameters = paramList.getParameters(); - - presentableText.append("("); - for (int i = 0; i < parameters.length; i++) { - if (i > 0) presentableText.append(", "); - presentableText.append(parameters[i].getType().getPresentableText()); - } - presentableText.append(")"); - - PsiType returnType = method.getReturnType(); - - if (returnType != null) { - presentableText.append(":"); - presentableText.append(returnType.getPresentableText()); - } - - return presentableText.toString(); - } - - public static String getFilePresentableText(GroovyFileBase file) { - return file.getName(); - } - - public static String getExpressionPresentableText(GrExpression expression) { - if (expression instanceof GrLiteral) { - final Object value = ((GrLiteral) expression).getValue(); - if (value == null || value.toString().length() == 0) return "\"\""; - } - - return expression.getText(); - } -} \ No newline at end of file diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyFileStructureViewElement.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyFileStructureViewElement.java index 75590f1e5745..d92ddcc5145e 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyFileStructureViewElement.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyFileStructureViewElement.java @@ -24,7 +24,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefini import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.GrTopStatement; import org.jetbrains.plugins.groovy.structure.elements.GroovyStructureViewElement; -import org.jetbrains.plugins.groovy.structure.itemsPresentations.impl.GroovyFileItemPresentation; +import org.jetbrains.plugins.groovy.structure.itemsPresentations.GroovyItemPresentation; import java.util.ArrayList; import java.util.List; @@ -40,7 +40,11 @@ public class GroovyFileStructureViewElement extends GroovyStructureViewElement { } public ItemPresentation getPresentation() { - return new GroovyFileItemPresentation((GroovyFileBase) myElement); + return new GroovyItemPresentation(myElement) { + public String getPresentableText() { + return ((GroovyFileBase) myElement).getName(); + } + }; } public TreeElement[] getChildren() { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyTypeDefinitionStructureViewElement.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyTypeDefinitionStructureViewElement.java index 87d733e82a58..c20258650598 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyTypeDefinitionStructureViewElement.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyTypeDefinitionStructureViewElement.java @@ -23,7 +23,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrSyntheticMethod; import org.jetbrains.plugins.groovy.structure.elements.GroovyStructureViewElement; -import org.jetbrains.plugins.groovy.structure.itemsPresentations.impl.GroovyTypeDefinitionItemPresentation; +import org.jetbrains.plugins.groovy.structure.itemsPresentations.GroovyItemPresentation; import java.util.ArrayList; import java.util.Arrays; @@ -35,7 +35,11 @@ public class GroovyTypeDefinitionStructureViewElement extends GroovyStructureVie } public ItemPresentation getPresentation() { - return new GroovyTypeDefinitionItemPresentation(((GrTypeDefinition)myElement)); + return new GroovyItemPresentation(myElement) { + public String getPresentableText() { + return ((GrTypeDefinition) myElement).getNameIdentifierGroovy().getText(); + } + }; } public TreeElement[] getChildren() { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyFileItemPresentation.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyFileItemPresentation.java deleted file mode 100644 index c96f6a99bebf..000000000000 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyFileItemPresentation.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.plugins.groovy.structure.itemsPresentations.impl; - -import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase; -import org.jetbrains.plugins.groovy.structure.GroovyElementPresentation; -import org.jetbrains.plugins.groovy.structure.itemsPresentations.GroovyItemPresentation; - -/** - * User: Dmitry.Krasilschikov - * Date: 30.10.2007 - */ - public class GroovyFileItemPresentation extends GroovyItemPresentation { - public GroovyFileItemPresentation(GroovyFileBase myElement) { - super(myElement); - } - - public String getPresentableText() { - return GroovyElementPresentation.getFilePresentableText(((GroovyFileBase) myElement)); - } -} diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyMethodItemPresentation.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyMethodItemPresentation.java index 891962ae5458..89e5593dd4e5 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyMethodItemPresentation.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyMethodItemPresentation.java @@ -17,16 +17,16 @@ package org.jetbrains.plugins.groovy.structure.itemsPresentations.impl; import com.intellij.openapi.editor.colors.CodeInsightColors; import com.intellij.openapi.editor.colors.TextAttributesKey; -import com.intellij.openapi.util.Iconable; import com.intellij.openapi.util.NotNullLazyValue; import com.intellij.psi.PsiMethod; -import org.jetbrains.annotations.Nullable; +import com.intellij.psi.PsiParameter; +import com.intellij.psi.PsiParameterList; +import com.intellij.psi.PsiType; import org.jetbrains.annotations.NotNull; -import org.jetbrains.plugins.groovy.structure.GroovyElementPresentation; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.structure.itemsPresentations.GroovyItemPresentation; -import javax.swing.*; - /** * User: Dmitry.Krasilschikov * Date: 31.10.2007 @@ -37,7 +37,29 @@ public class GroovyMethodItemPresentation extends GroovyItemPresentation { @NotNull @Override protected String compute() { - return GroovyElementPresentation.getMethodPresentableText(((PsiMethod) myElement)); + final PsiMethod method = (PsiMethod)myElement; + StringBuilder presentableText = new StringBuilder(); + presentableText.append(method.getName()); + presentableText.append(" "); + + PsiParameterList paramList = method.getParameterList(); + PsiParameter[] parameters = paramList.getParameters(); + + presentableText.append("("); + for (int i = 0; i < parameters.length; i++) { + if (i > 0) presentableText.append(", "); + presentableText.append(parameters[i].getType().getPresentableText()); + } + presentableText.append(")"); + + PsiType returnType = method instanceof GrMethod ? ((GrMethod)method).getDeclaredReturnType() : method.getReturnType(); + + if (returnType != null) { + presentableText.append(":"); + presentableText.append(returnType.getPresentableText()); + } + + return presentableText.toString(); } }; @@ -50,16 +72,6 @@ public class GroovyMethodItemPresentation extends GroovyItemPresentation { return myPresentableText.getValue(); } - @Nullable - public String getLocationString() { - return null; - } - - @Nullable - public Icon getIcon(boolean open) { - return myElement.getIcon(Iconable.ICON_FLAG_OPEN); - } - @Nullable public TextAttributesKey getTextAttributesKey() { return isInherit ? CodeInsightColors.NOT_USED_ELEMENT_ATTRIBUTES : null; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyTypeDefinitionItemPresentation.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyTypeDefinitionItemPresentation.java deleted file mode 100644 index efa4b1898f3b..000000000000 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyTypeDefinitionItemPresentation.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.plugins.groovy.structure.itemsPresentations.impl; - -import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; -import org.jetbrains.plugins.groovy.structure.GroovyElementPresentation; -import org.jetbrains.plugins.groovy.structure.itemsPresentations.GroovyItemPresentation; - -/** - * User: Dmitry.Krasilschikov - * Date: 30.10.2007 - */ - public class GroovyTypeDefinitionItemPresentation extends GroovyItemPresentation { - public GroovyTypeDefinitionItemPresentation(GrTypeDefinition myElement) { - super(myElement); - } - - public String getPresentableText() { - return GroovyElementPresentation.getTypeDefinitionPresentableText((GrTypeDefinition) myElement); - } -} From 67a9d2b935beaec04a07aa0f9ff93a29ea8dffcc Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 18 Feb 2010 20:51:12 +0000 Subject: [PATCH 47/93] restore dash in default groovy-related libraries naming --- .../plugins/groovy/config/AbstractGroovyLibraryManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/config/AbstractGroovyLibraryManager.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/config/AbstractGroovyLibraryManager.java index 344864972ace..a3f0a4cf9aff 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/config/AbstractGroovyLibraryManager.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/config/AbstractGroovyLibraryManager.java @@ -148,7 +148,7 @@ public abstract class AbstractGroovyLibraryManager extends LibraryManager { if (addVersion && !AbstractConfigUtils.UNDEFINED_VERSION.equals(newVersion)) { final Project project = container.getProject(); - final String name = generatePointerName(newVersion, getLibraryPrefix(), container, usedLibraryNames); + final String name = generatePointerName(newVersion, getLibraryPrefix() + "-", container, usedLibraryNames); final CreateLibraryDialog dialog = new CreateLibraryDialog(project, "Create " + libraryKind + " library", "Create Project " + libraryKind + " library '" + name + "'", "Create Global " + libraryKind + " library '" + name + "'"); From 3918ac9d6a5564aae4896cb4dbf7a95e46b7b0e9 Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 18 Feb 2010 21:32:53 +0000 Subject: [PATCH 48/93] allow to create groovy scripts not under src dirs --- .../src/com/intellij/ide/actions/CreateClassAction.java | 2 +- .../ide/actions/CreateTemplateInPackageAction.java | 9 ++++++++- .../plugins/groovy/actions/NewGroovyClassAction.java | 2 +- .../plugins/groovy/actions/NewScriptAction.java | 2 +- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/java/java-impl/src/com/intellij/ide/actions/CreateClassAction.java b/java/java-impl/src/com/intellij/ide/actions/CreateClassAction.java index 6b658f8d1a32..7b5bd8d35b4f 100644 --- a/java/java-impl/src/com/intellij/ide/actions/CreateClassAction.java +++ b/java/java-impl/src/com/intellij/ide/actions/CreateClassAction.java @@ -36,7 +36,7 @@ import org.jetbrains.annotations.NotNull; */ public class CreateClassAction extends CreateTemplateInPackageAction { public CreateClassAction() { - super(IdeBundle.message("action.create.new.class"), IdeBundle.message("action.create.new.class"), Icons.CLASS_ICON); + super(IdeBundle.message("action.create.new.class"), IdeBundle.message("action.create.new.class"), Icons.CLASS_ICON, true); } @NotNull diff --git a/java/java-impl/src/com/intellij/ide/actions/CreateTemplateInPackageAction.java b/java/java-impl/src/com/intellij/ide/actions/CreateTemplateInPackageAction.java index 463509a7bcbe..5defec828c81 100644 --- a/java/java-impl/src/com/intellij/ide/actions/CreateTemplateInPackageAction.java +++ b/java/java-impl/src/com/intellij/ide/actions/CreateTemplateInPackageAction.java @@ -34,8 +34,11 @@ import javax.swing.*; * @author peter */ public abstract class CreateTemplateInPackageAction extends AnAction { - protected CreateTemplateInPackageAction(String text, String description, Icon icon) { + private final boolean myinSourceOnly; + + protected CreateTemplateInPackageAction(String text, String description, Icon icon, boolean inSourceOnly) { super(text, description, icon); + myinSourceOnly = inSourceOnly; } public final void actionPerformed(final AnActionEvent e) { @@ -93,6 +96,10 @@ public abstract class CreateTemplateInPackageAction extend return false; } + if (!myinSourceOnly) { + return true; + } + ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex(); for (PsiDirectory dir : view.getDirectories()) { if (projectFileIndex.isInSourceContent(dir.getVirtualFile()) && JavaDirectoryService.getInstance().getPackage(dir) != null) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewGroovyClassAction.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewGroovyClassAction.java index e78f50b08ce4..17ad85067580 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewGroovyClassAction.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewGroovyClassAction.java @@ -35,7 +35,7 @@ import org.jetbrains.plugins.groovy.util.LibrariesUtil; public class NewGroovyClassAction extends CreateTemplateInPackageAction implements DumbAware { public NewGroovyClassAction() { - super(GroovyBundle.message("newclass.menu.action.text"), GroovyBundle.message("newclass.menu.action.description"), GroovyIcons.CLASS); + super(GroovyBundle.message("newclass.menu.action.text"), GroovyBundle.message("newclass.menu.action.description"), GroovyIcons.CLASS, true); } @NotNull diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewScriptAction.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewScriptAction.java index eb7a8affa576..a8831400bd91 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewScriptAction.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewScriptAction.java @@ -38,7 +38,7 @@ public class NewScriptAction extends CreateTemplateInPackageAction i private static final String GROOVY_DSL_SCRIPT_TMPL = "GroovyDslScript.gdsl"; public NewScriptAction() { - super(GroovyBundle.message("newscript.menu.action.text"), GroovyBundle.message("newscript.menu.action.description"), GroovyIcons.GROOVY_ICON_16x16); + super(GroovyBundle.message("newscript.menu.action.text"), GroovyBundle.message("newscript.menu.action.description"), GroovyIcons.GROOVY_ICON_16x16, false); } @NotNull From 2470719101f3f9b109fc1955b1fbcd8a64c34d3f Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 18 Feb 2010 21:37:37 +0000 Subject: [PATCH 49/93] if a PsiClassOwner has a synthetic class inside, presumably it's a strange class owner (e.g. groovy script) and we shouldn't replace its icon with the one of its classes' --- .../src/com/intellij/ide/JavaFileIconPatcher.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/java/java-impl/src/com/intellij/ide/JavaFileIconPatcher.java b/java/java-impl/src/com/intellij/ide/JavaFileIconPatcher.java index a70de4d0e132..4552c0cd67c2 100644 --- a/java/java-impl/src/com/intellij/ide/JavaFileIconPatcher.java +++ b/java/java-impl/src/com/intellij/ide/JavaFileIconPatcher.java @@ -63,14 +63,14 @@ public class JavaFileIconPatcher implements FileIconPatcher { // prefer icon of the class named after file final String fileName = file.getNameWithoutExtension(); for (PsiClass aClass : classes) { - if (!(aClass instanceof SyntheticElement) && Comparing.strEqual(aClass.getName(), fileName)) { + if (aClass instanceof SyntheticElement) { + return baseIcon; + } + if (Comparing.strEqual(aClass.getName(), fileName)) { return aClass.getIcon(flags); } } - final PsiClass lastClass = classes[classes.length - 1]; - if (!(lastClass instanceof SyntheticElement)) { - return lastClass.getIcon(flags); - } + return classes[classes.length - 1].getIcon(flags); } } return baseIcon; From 638aa4b8a7d456965d649ce7150fdbd9d8fbefa1 Mon Sep 17 00:00:00 2001 From: Maxim Medvedev Date: Sun, 14 Feb 2010 13:05:30 +0300 Subject: [PATCH 50/93] IDEA-52183: improve --- plugins/groovy/src/META-INF/plugin.xml | 3 + .../groovy/config/GroovyLibraryListener.java | 99 +++++++++++++++++++ 2 files changed, 102 insertions(+) create mode 100644 plugins/groovy/src/org/jetbrains/plugins/groovy/config/GroovyLibraryListener.java diff --git a/plugins/groovy/src/META-INF/plugin.xml b/plugins/groovy/src/META-INF/plugin.xml index 765a0b694494..bbf611a09e6b 100644 --- a/plugins/groovy/src/META-INF/plugin.xml +++ b/plugins/groovy/src/META-INF/plugin.xml @@ -483,6 +483,9 @@ org.jetbrains.plugins.groovy.codeInspection.local.GroovyUnusedImportsPassFactory + + org.jetbrains.plugins.groovy.config.GroovyLibraryListener + org.jetbrains.plugins.groovy.annotator.intentions.dynamic.DynamicManager org.jetbrains.plugins.groovy.annotator.intentions.dynamic.DynamicManagerImpl diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/config/GroovyLibraryListener.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/config/GroovyLibraryListener.java new file mode 100644 index 000000000000..e5c65715c3ab --- /dev/null +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/config/GroovyLibraryListener.java @@ -0,0 +1,99 @@ +/* + * 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 org.jetbrains.plugins.groovy.config; + +import com.intellij.ProjectTopics; +import com.intellij.openapi.application.Application; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.application.ApplicationNamesInfo; +import com.intellij.openapi.components.AbstractProjectComponent; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.module.ModuleManager; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.roots.ModuleRootEvent; +import com.intellij.openapi.roots.ModuleRootListener; +import com.intellij.openapi.roots.libraries.Library; +import com.intellij.openapi.ui.Messages; +import com.intellij.openapi.vfs.newvfs.persistent.FSRecords; +import com.intellij.util.containers.hash.HashSet; +import com.intellij.util.messages.MessageBusConnection; +import org.jetbrains.plugins.groovy.util.LibrariesUtil; + +import java.util.Set; + +/** + * @author Maxim.Medvedev + */ +public class GroovyLibraryListener extends AbstractProjectComponent implements ModuleRootListener { + private final Set groovyModules = new HashSet(); + + public GroovyLibraryListener(Project project) { + super(project); + } + + @Override + public void projectOpened() { + final MessageBusConnection connection = myProject.getMessageBus().connect(myProject); + connection.subscribe(ProjectTopics.PROJECT_ROOTS, this); + + final Module[] modules = ModuleManager.getInstance(myProject).getModules(); + for (Module module : modules) { + if (module.isDisposed()) continue; + if (LibrariesUtil.hasGroovySdk(module)) { + groovyModules.add(module); + } + } + } + + public void beforeRootsChange(ModuleRootEvent event) { + } + + public void rootsChanged(ModuleRootEvent event) { + final Module[] modules = ModuleManager.getInstance(myProject).getModules(); + for (Module module : modules) { + if (module.isDisposed()) continue; + final Library[] libraries = GroovyConfigUtils.getInstance().getSDKLibrariesByModule(module); + if ((libraries.length > 0 && !groovyModules.contains(module))) { + final Application app = ApplicationManager.getApplication(); + if (app.isRestartCapable()) { + if (Messages.showYesNoDialog(myProject, "You have added Groovy SDK library '" + + libraries[0].getName() + + "' to module '" + + module.getName() + + "'. To add Groovy support " + + ApplicationNamesInfo.getInstance().getFullProductName() + + " must be restarted. Would you like to add Groovy support and restart now?", + "Add Groovy support", Messages.getInformationIcon()) == 0) { + FSRecords.invalidateCaches(); + app.restart(); + } + } + else { + Messages.showMessageDialog(myProject, "You have added Groovy SDK library '" + + libraries[0].getName() + + "' to module '" + + module.getName() + + "'. To add Groovy support you need to restart " + + ApplicationNamesInfo.getInstance().getFullProductName() + + ".", "Add Groovy support", Messages.getInformationIcon()); + } + } + else if ((libraries.length == 0 && groovyModules.contains(module))) { + groovyModules.remove(module); + } + } + } +} From 5fc5449169b295e3685f3d21af35c747d33af466 Mon Sep 17 00:00:00 2001 From: Maxim Medvedev Date: Fri, 19 Feb 2010 11:54:39 +0300 Subject: [PATCH 51/93] IDEA-38524: Add quickfix to escalate inaccessible member visibility --- .../plugins/groovy/GroovyBundle.properties | 2 + .../groovy/annotator/GroovyAnnotator.java | 45 ++++++++- .../annotator/intentions/GrModifierFix.java | 91 +++++++++++++++++++ .../ConvertParameterToMapEntryIntention.java | 5 +- .../modifiers/GrModifierListImpl.java | 27 ++++-- 5 files changed, 156 insertions(+), 14 deletions(-) create mode 100644 plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GrModifierFix.java diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties b/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties index 0f09fa2689c0..be4d094289e5 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties @@ -174,6 +174,8 @@ unused.import.statement=Unused import statement static.declaration.in.inner.class=Inner classes cannot have static declarations constructors.are.not.allowed.in.anonymous.class=Constructors are not allowed in anonymous class no.such.property=Property ''{0}'' does not exist +change.modifier=Make ''{0}'' {1} +change.modifier.family.name=Change modifiers # {0} - colspan, {1} - method name, {2} - class name, {3} - formal myParameters row, {4} - arguments row argument.mismatch.html.tooltip=\ diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java index 35707bf19cdf..14404fc95fd1 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java @@ -16,12 +16,14 @@ package org.jetbrains.plugins.groovy.annotator; +import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.lang.ASTNode; import com.intellij.lang.annotation.Annotation; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; @@ -29,6 +31,8 @@ import com.intellij.psi.*; import com.intellij.psi.infos.CandidateInfo; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.util.ArrayUtil; +import com.intellij.util.IncorrectOperationException; import gnu.trove.TObjectHashingStrategy; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -152,11 +156,15 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { } if (!resolveResult.isAccessible()) { String message = GroovyBundle.message("cannot.access", referenceExpression.getReferenceName()); - myHolder.createWarningAnnotation(referenceExpression.getReferenceNameElement(), message); + final Annotation annotation = myHolder.createWarningAnnotation(referenceExpression.getReferenceNameElement(), message); + if (resolved instanceof PsiMember) { + registerAccessFix(annotation, referenceExpression, ((PsiMember)resolved)); + } } if (!resolveResult.isStaticsOK() && resolved instanceof PsiModifierListOwner) { if (!((PsiModifierListOwner)resolved).hasModifierProperty(GrModifier.STATIC)) { - myHolder.createWarningAnnotation(referenceExpression, GroovyBundle.message("cannot.reference.nonstatic", referenceExpression.getReferenceName())); + myHolder.createWarningAnnotation(referenceExpression, + GroovyBundle.message("cannot.reference.nonstatic", referenceExpression.getReferenceName())); } } } @@ -207,6 +215,39 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { } } + private static void registerAccessFix(Annotation annotation, GrReferenceExpression place, PsiMember refElement) { + if (refElement instanceof PsiCompiledElement) return; + PsiModifierList modifierList = refElement.getModifierList(); + if (modifierList == null) return; + + try { + Project project = refElement.getProject(); + JavaPsiFacade facade = JavaPsiFacade.getInstance(project); + PsiModifierList modifierListCopy = facade.getElementFactory().createFieldFromText("int a;", null).getModifierList(); + modifierListCopy.setModifierProperty(PsiModifier.STATIC, modifierList.hasModifierProperty(PsiModifier.STATIC)); + @Modifier String minModifier = PsiModifier.PROTECTED; + if (refElement.hasModifierProperty(PsiModifier.PROTECTED)) { + minModifier = PsiModifier.PUBLIC; + } + String[] modifiers = {PsiModifier.PROTECTED, PsiModifier.PUBLIC,}; + PsiClass accessObjectClass = PsiTreeUtil.getParentOfType(place, PsiClass.class, false); + if (accessObjectClass == null) { + accessObjectClass = ((GroovyFile)place.getContainingFile()).getScriptClass(); + } + for (int i = ArrayUtil.indexOf(modifiers, minModifier); i < modifiers.length; i++) { + String modifier = modifiers[i]; + modifierListCopy.setModifierProperty(modifier, true); + if (facade.getResolveHelper().isAccessible(refElement, modifierListCopy, place, accessObjectClass, null)) { + IntentionAction fix = new GrModifierFix(refElement, modifier, true); + annotation.registerFix(fix); + } + } + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + } + private static void registerStaticImportFix(GrReferenceExpression referenceExpression, Annotation annotation) { final String referenceName = referenceExpression.getReferenceName(); //noinspection ConstantConditions diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GrModifierFix.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GrModifierFix.java new file mode 100644 index 000000000000..27091ee62eb6 --- /dev/null +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GrModifierFix.java @@ -0,0 +1,91 @@ +/* + * 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 org.jetbrains.plugins.groovy.annotator.intentions; + +import com.intellij.codeInsight.intention.IntentionAction; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.*; +import com.intellij.util.IncorrectOperationException; +import com.intellij.util.VisibilityUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.plugins.groovy.GroovyBundle; +import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement; +import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; + +/** + * @author Maxim.Medvedev + */ +public class GrModifierFix implements IntentionAction { + private final PsiMember myMember; + private final String myModifier; + private final boolean showContainingClass; + + public GrModifierFix(PsiMember member, String modifier, boolean showContainingClass) { + myMember = member; + myModifier = modifier; + this.showContainingClass = showContainingClass; + } + + @NotNull + public String getText() { + if (showContainingClass) { + final PsiClass containingClass = myMember.getContainingClass(); + String containingClassName; + if (containingClass != null) { + containingClassName = containingClass.getName() + "."; + } + else { + containingClassName = ""; + } + String modifierText = VisibilityUtil.toPresentableText(myModifier); + + return GroovyBundle.message("change.modifier", containingClassName + myMember.getName(), modifierText); + } + else { + return GroovyBundle.message("change.modifier", myMember.getName(), myModifier); + } + } + + @NotNull + public String getFamilyName() { + return GroovyBundle.message("change.modifier.family.name"); + } + + public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { + final PsiReference ref = file.findReferenceAt(editor.getCaretModel().getOffset()); + if (ref == null) return false; + final PsiElement element = ref.getElement(); + if (element instanceof GrReferenceElement) { + final GroovyResolveResult resolveResult = ((GrReferenceElement)element).advancedResolve(); + if (!resolveResult.isAccessible() && resolveResult.getElement() instanceof PsiMember) { + return true; + } + } + return false; + } + + public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { + final PsiModifierList list = myMember.getModifierList(); + if (list != null) { + list.setModifierProperty(myModifier, true); + } + } + + public boolean startInWriteAction() { + return true; + } +} diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/parameterToEntry/ConvertParameterToMapEntryIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/parameterToEntry/ConvertParameterToMapEntryIntention.java index 5b0b9e650105..4952796b0223 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/parameterToEntry/ConvertParameterToMapEntryIntention.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/parameterToEntry/ConvertParameterToMapEntryIntention.java @@ -42,7 +42,6 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle; import org.jetbrains.plugins.groovy.intentions.base.Intention; import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate; -import static org.jetbrains.plugins.groovy.intentions.style.parameterToEntry.ConvertParameterToMapEntryIntention.FIRST_PARAMETER_KIND.*; import org.jetbrains.plugins.groovy.lang.psi.GrNamedElement; import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; @@ -64,6 +63,8 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; +import static org.jetbrains.plugins.groovy.intentions.style.parameterToEntry.ConvertParameterToMapEntryIntention.FIRST_PARAMETER_KIND.*; + /** * @author ilyas */ @@ -424,7 +425,7 @@ public class ConvertParameterToMapEntryIntention extends Intention { CodeStyleManager.getInstance(owner.getProject()).reformat(owner); } - private static boolean reportConflicts(final MultiMap conflicts, final Project project) { + private static boolean reportConflicts(final MultiMap conflicts, final Project project) { if (conflicts.size() == 0) return true; ConflictsDialog conflictsDialog = new ConflictsDialog(project, conflicts); conflictsDialog.show(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java index fd2eabd681fc..494851af58f9 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java @@ -196,19 +196,26 @@ public class GrModifierListImpl extends GroovyBaseElementImpl Date: Thu, 18 Feb 2010 12:45:10 +0300 Subject: [PATCH 52/93] ctrl-Q: format annotations fixed (IDEA-24562) --- .../com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java b/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java index 7615b0fac4d8..d25f1bd22e6e 100644 --- a/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java +++ b/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java @@ -550,7 +550,7 @@ public class JavaDocInfoGenerator { } buffer.append(")"); } - buffer.append("\n"); + buffer.append(" "); } } } From 9fdbd6cb7f6f7ad412acb8e0177e0c4f324b0ba1 Mon Sep 17 00:00:00 2001 From: anna Date: Thu, 18 Feb 2010 14:31:05 +0300 Subject: [PATCH 53/93] ctrl-Q: font settings fixed (IDEA-42152) --- .../codeInsight/javadoc/JavaDocInfoGenerator.java | 12 ++++++------ .../documentation/DocumentationComponent.java | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java b/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java index d25f1bd22e6e..8a036afb14d5 100644 --- a/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java +++ b/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java @@ -236,9 +236,9 @@ public class JavaDocInfoGenerator { if (file instanceof PsiJavaFile) { String packageName = ((PsiJavaFile)file).getPackageName(); if (packageName.length() > 0) { - buffer.append(""); + buffer.append(""); buffer.append(packageName); - buffer.append(""); + buffer.append(""); //buffer.append("
"); } } @@ -370,10 +370,10 @@ public class JavaDocInfoGenerator { if (parentClass != null) { String qName = parentClass.getQualifiedName(); if (qName != null) { - buffer.append(""); + buffer.append(""); //buffer.append(qName); generateLink(buffer, qName, qName, field, false); - buffer.append(""); + buffer.append(""); //buffer.append("
"); } } @@ -599,10 +599,10 @@ public class JavaDocInfoGenerator { if (parentClass != null) { String qName = parentClass.getQualifiedName(); if (qName != null) { - buffer.append(""); + buffer.append(""); generateLink(buffer, qName, qName, method, false); //buffer.append(qName); - buffer.append(""); + buffer.append(""); //buffer.append("
"); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java index 8c64afe9b6eb..8445802578f9 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java @@ -131,7 +131,7 @@ public class DocumentationComponent extends JPanel implements Disposable { myText = ""; myEditorPane.setEditable(false); myEditorPane.setBackground(HintUtil.INFORMATION_COLOR); - + myEditorPane.setEditorKit(UIUtil.getHTMLEditorKit()); myScrollPane = new JScrollPane(myEditorPane); myScrollPane.setBorder(null); From e5561069d37f62669da1d252459e2755164a45ff Mon Sep 17 00:00:00 2001 From: anna Date: Thu, 18 Feb 2010 19:03:23 +0300 Subject: [PATCH 54/93] compact project view combo --- .../src/com/intellij/ide/projectView/impl/ProjectViewImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java index 6010b0e857bc..e3dc85211919 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java @@ -461,7 +461,7 @@ public final class ProjectViewImpl extends ProjectView implements PersistentStat else { String presentable = pane.getPresentableSubIdName(subId); if (index == -1) { - setText(pane.getTitle() + ": " + presentable); + setText(presentable); setIcon(pane.getIcon()); } else { From d5b202f75c8eacf3eb49c9c91b1a91c4205e59f5 Mon Sep 17 00:00:00 2001 From: anna Date: Thu, 18 Feb 2010 19:13:36 +0300 Subject: [PATCH 55/93] IDEA-52351 --- .../intellij/execution/junit2/SegmentedInputStream.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/java/execution/impl/src/com/intellij/execution/junit2/SegmentedInputStream.java b/java/execution/impl/src/com/intellij/execution/junit2/SegmentedInputStream.java index d15336716a52..4ebdbebc72ce 100644 --- a/java/execution/impl/src/com/intellij/execution/junit2/SegmentedInputStream.java +++ b/java/execution/impl/src/com/intellij/execution/junit2/SegmentedInputStream.java @@ -19,6 +19,7 @@ import com.intellij.rt.execution.junit.segments.Packet; import com.intellij.rt.execution.junit.segments.PacketProcessor; import com.intellij.rt.execution.junit.segments.SegmentedStream; import com.intellij.util.StringBuilderSpinAllocator; +import com.intellij.util.containers.HashMap; import java.io.BufferedReader; import java.io.IOException; @@ -108,7 +109,9 @@ public class SegmentedInputStream extends InputStream { } public int available() throws IOException { - + + final HashMap map = new HashMap(); + map.keySet(); while (mySourceStream.ready()) { while(myStartupPassed < SegmentedStream.STARTUP_MESSAGE.length()) { @@ -131,8 +134,8 @@ public class SegmentedInputStream extends InputStream { final Integer packetRead = readControlSequence(); if (packetRead != null) { // push back quoted slash - mySourceStream.pushBack(b); mySourceStream.pushBack(packetRead); + mySourceStream.pushBack(b); return 1; } } From ce60d76a3e61ae8324bf21fc7a44e0282c594b8a Mon Sep 17 00:00:00 2001 From: anna Date: Thu, 18 Feb 2010 19:39:25 +0300 Subject: [PATCH 56/93] AIOOBE --- .../intellij/refactoring/inline/InlineParameterHandler.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java index a78a315e7017..3f8e0608bb1c 100644 --- a/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java @@ -81,7 +81,9 @@ public class InlineParameterHandler extends JavaInlineActionHandler { final PsiCallExpression methodCall = (PsiCallExpression)parent; occurrences.add(psiReference); containingFiles.add(element.getContainingFile()); - PsiExpression argument = methodCall.getArgumentList().getExpressions()[index]; + final PsiExpression[] expressions = methodCall.getArgumentList().getExpressions(); + if (expressions.length >= index) return false; + PsiExpression argument = expressions[index]; if (!refInitializer.isNull()) { return argument != null && PsiEquivalenceUtil.areElementsEquivalent(refInitializer.get(), argument) From 37f27f54534d26617dcc59e83b1cda8cc910f917 Mon Sep 17 00:00:00 2001 From: anna Date: Thu, 18 Feb 2010 20:29:58 +0300 Subject: [PATCH 57/93] NPE --- .../intellij/execution/junit/TestObject.java | 17 ++++++++++------- .../junit2/ui/TestsPacketsReceiver.java | 17 ++++++++++++----- 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/plugins/junit/src/com/intellij/execution/junit/TestObject.java b/plugins/junit/src/com/intellij/execution/junit/TestObject.java index aba51fd102b0..99a388e2448b 100644 --- a/plugins/junit/src/com/intellij/execution/junit/TestObject.java +++ b/plugins/junit/src/com/intellij/execution/junit/TestObject.java @@ -247,13 +247,16 @@ public abstract class TestObject implements JavaCommandLine { @Override public void notifyStart(TestProxy root) { super.notifyStart(root); - handler.getOut().setDispatchListener(getModel().getNotifier()); - Disposer.register(getModel(), new Disposable() { - public void dispose() { - handler.getOut().setDispatchListener(DispatchListener.DEAF); - } - }); - consoleView.attachToModel(getModel()); + final JUnitRunningModel model = getModel(); + if (model != null) { + handler.getOut().setDispatchListener(model.getNotifier()); + Disposer.register(model, new Disposable() { + public void dispose() { + handler.getOut().setDispatchListener(DispatchListener.DEAF); + } + }); + consoleView.attachToModel(model); + } } }; diff --git a/plugins/junit/src/com/intellij/execution/junit2/ui/TestsPacketsReceiver.java b/plugins/junit/src/com/intellij/execution/junit2/ui/TestsPacketsReceiver.java index c22a5f248249..c5d6f3dc6f30 100644 --- a/plugins/junit/src/com/intellij/execution/junit2/ui/TestsPacketsReceiver.java +++ b/plugins/junit/src/com/intellij/execution/junit2/ui/TestsPacketsReceiver.java @@ -37,6 +37,8 @@ import com.intellij.rt.execution.junit.segments.PacketProcessor; import com.intellij.rt.execution.junit.segments.PoolOfDelimiters; import com.intellij.rt.execution.junit.states.PoolOfTestStates; import com.intellij.util.containers.HashMap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Map; @@ -130,8 +132,11 @@ public class TestsPacketsReceiver implements PacketProcessor, Disposable { public void notifyFinish(ObjectReader reader) { myIsTerminated = true; - myModel.getNotifier().fireRunnerStateChanged(new CompletionEvent(true, reader.readInt())); - terminateStillRunning(); + final JUnitRunningModel model = getModel(); + if (model != null) { + model.getNotifier().fireRunnerStateChanged(new CompletionEvent(true, reader.readInt())); + terminateStillRunning(model); + } } public boolean isRunning() { @@ -142,11 +147,13 @@ public class TestsPacketsReceiver implements PacketProcessor, Disposable { myIsTerminated = terminated; } + @Nullable public JUnitRunningModel getModel() { return myModel; } public void dispose() { + myModel = null; } public void checkTerminated() { @@ -156,15 +163,15 @@ public class TestsPacketsReceiver implements PacketProcessor, Disposable { final JUnitListenersNotifier notifier = model.getNotifier(); if (notifier != null) { notifier.fireRunnerStateChanged(new CompletionEvent(false, -1)); - terminateStillRunning(); + terminateStillRunning(model); } } setTerminated(true); } } - private void terminateStillRunning() { - if (myModel.getRoot() != null) { + private void terminateStillRunning(@NotNull JUnitRunningModel model) { + if (model.getRoot() != null) { final List runningTests = TestStateUpdater.RUNNING_LEAF.select(myModel.getRoot().getAllTests()); for (final AbstractTestProxy runningTest : runningTests) { final TestProxy testProxy = (TestProxy)runningTest; From 989d495e7e6bd01a6ee38857a74c54461f806cd1 Mon Sep 17 00:00:00 2001 From: anna Date: Thu, 18 Feb 2010 20:37:44 +0300 Subject: [PATCH 58/93] already disposed --- java/idea-ui/src/com/intellij/ide/impl/NewProjectUtil.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/java/idea-ui/src/com/intellij/ide/impl/NewProjectUtil.java b/java/idea-ui/src/com/intellij/ide/impl/NewProjectUtil.java index 5888e31fc19f..da9e84693775 100644 --- a/java/idea-ui/src/com/intellij/ide/impl/NewProjectUtil.java +++ b/java/idea-ui/src/com/intellij/ide/impl/NewProjectUtil.java @@ -34,7 +34,6 @@ import com.intellij.openapi.projectRoots.JavaSdk; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.CompilerProjectExtension; import com.intellij.openapi.roots.LanguageLevelProjectExtension; -import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.roots.ex.ProjectRootManagerEx; import com.intellij.openapi.roots.ui.configuration.ModulesConfigurator; import com.intellij.openapi.roots.ui.configuration.ModulesProvider; @@ -132,11 +131,13 @@ public class NewProjectUtil { // ensure the dialog is shown after all startup activities are done SwingUtilities.invokeLater(new Runnable() { public void run() { + if (newProject.isDisposed()) return; if (need2OpenProjectStructure) { ModulesConfigurator.showDialog(newProject, null, null, true); } ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { + if (newProject.isDisposed()) return; final ToolWindow toolWindow = ToolWindowManager.getInstance(newProject).getToolWindow(ToolWindowId.PROJECT_VIEW); if (toolWindow != null) { toolWindow.activate(null); From 75fb3e76979991fbfbe34bb3b1dc75582f7d4042 Mon Sep 17 00:00:00 2001 From: anna Date: Thu, 18 Feb 2010 22:18:55 +0300 Subject: [PATCH 59/93] javadoc for enumerated declarations (IDEA-39126) --- .../codeInsight/javadoc/JavaDocInfoGenerator.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java b/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java index 8a036afb14d5..7d58c2f12c12 100644 --- a/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java +++ b/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java @@ -359,8 +359,19 @@ public class JavaDocInfoGenerator { return null; } + @Nullable private static PsiDocComment getDocComment(final PsiDocCommentOwner docOwner) { - return ((PsiDocCommentOwner)docOwner.getNavigationElement()).getDocComment(); + PsiDocComment comment = ((PsiDocCommentOwner)docOwner.getNavigationElement()).getDocComment(); + if (comment == null) { //check for non-normalized fields + final PsiModifierList modifierList = docOwner.getModifierList(); + if (modifierList != null) { + final PsiElement parent = modifierList.getParent(); + if (parent instanceof PsiDocCommentOwner) { + return ((PsiDocCommentOwner)parent.getNavigationElement()).getDocComment(); + } + } + } + return comment; } private void generateFieldJavaDoc(@NonNls StringBuilder buffer, PsiField field) { From a64360ca508be726460c6ec3372037af7cfc3c2c Mon Sep 17 00:00:00 2001 From: anna Date: Fri, 19 Feb 2010 12:43:36 +0300 Subject: [PATCH 60/93] javadoc inline tags: everything should be included in data elements? (IDEA-23739) --- .../psi/impl/source/tree/java/PsiInlineDocTagImpl.java | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiInlineDocTagImpl.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiInlineDocTagImpl.java index 6a1e158eaa42..613b52678ffd 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiInlineDocTagImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiInlineDocTagImpl.java @@ -39,14 +39,8 @@ import org.jetbrains.annotations.NotNull; public class PsiInlineDocTagImpl extends CompositePsiElement implements PsiInlineDocTag, Constants { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.java.PsiInlineDocTagImpl"); - private static final TokenSet VALUE_BIT_SET = TokenSet.create(new IElementType[]{ - JAVA_CODE_REFERENCE, - DOC_TAG_VALUE_TOKEN, - DOC_METHOD_OR_FIELD_REF, - DOC_COMMENT_DATA, - DOC_INLINE_TAG, - DOC_REFERENCE_HOLDER - }); + private static final TokenSet VALUE_BIT_SET = TokenSet.create(JAVA_CODE_REFERENCE, DOC_TAG_VALUE_TOKEN, DOC_METHOD_OR_FIELD_REF, + DOC_COMMENT_DATA, DOC_INLINE_TAG, DOC_REFERENCE_HOLDER, WHITE_SPACE, DOC_COMMENT_BAD_CHARACTER); public PsiInlineDocTagImpl() { super(DOC_INLINE_TAG); From 5af955589111bd1725099b0914f4a4e8bfaca741 Mon Sep 17 00:00:00 2001 From: anna Date: Fri, 19 Feb 2010 14:45:11 +0300 Subject: [PATCH 61/93] refix AIOOBE --- .../com/intellij/refactoring/inline/InlineParameterHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java index 3f8e0608bb1c..104332c1c3e8 100644 --- a/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java @@ -82,7 +82,7 @@ public class InlineParameterHandler extends JavaInlineActionHandler { occurrences.add(psiReference); containingFiles.add(element.getContainingFile()); final PsiExpression[] expressions = methodCall.getArgumentList().getExpressions(); - if (expressions.length >= index) return false; + if (expressions.length <= index) return false; PsiExpression argument = expressions[index]; if (!refInitializer.isNull()) { return argument != null From e11fb27ff4b5351b4be96c30a50722d9f205b038 Mon Sep 17 00:00:00 2001 From: Kirill Kalishev Date: Fri, 19 Feb 2010 15:22:28 +0300 Subject: [PATCH 62/93] TeeeUi: fixed loading node problem for chained expansions --- .../ide/util/treeView/AbstractTreeUi.java | 2 ++ .../ide/util/treeView/TreeUiTest.java | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java index dd3c9f3da0be..fa6bdbcfd73b 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java @@ -3670,6 +3670,8 @@ public class AbstractTreeUi { if (myRequestedExpand != null && !myRequestedExpand.equals(path)) return; + //myRequestedExpand = null; + final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); if (!myUnbuiltNodes.contains(node)) { diff --git a/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java b/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java index ef11b2a03cf7..483e421ef8e2 100644 --- a/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java +++ b/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java @@ -1,6 +1,7 @@ package com.intellij.ide.util.treeView; import com.intellij.openapi.progress.ProcessCanceledException; +import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Ref; import com.intellij.util.Time; @@ -1341,6 +1342,35 @@ public class TreeUiTest extends AbstractTreeBuilderTest { }); } + public void testStickyLoadingNodeIssue() throws Exception { + buildStructure(myRoot); + + final boolean[] done = new boolean[] {false}; + getBuilder().select(new NodeElement("jetbrains"), new Runnable() { + public void run() { + getBuilder().expand(new NodeElement("fabrique"), new Runnable() { + public void run() { + done[0] = true; + } + }); + } + }); + + waitBuilderToCome(new Condition() { + public boolean value(Object o) { + return done[0]; + } + }); + + assertTree("-/\n" + + " +com\n" + + " -[jetbrains]\n" + + " -fabrique\n" + + " ide\n" + + " +org\n" + + " +xunit\n"); + } + public void testReleaseBuilderDuringGetChildren() throws Exception { assertReleaseDuringBuilding("getChildren", "fabrique", new Runnable() { public void run() { @@ -1463,6 +1493,10 @@ public class TreeUiTest extends AbstractTreeBuilderTest { //todo } + @Override + public void testStickyLoadingNodeIssue() throws Exception { + super.testStickyLoadingNodeIssue(); + } } public static TestSuite suite() { From 8bad6154b5871f3c73828c2e91ea3df1a69c3011 Mon Sep 17 00:00:00 2001 From: Kirill Kalishev Date: Fri, 19 Feb 2010 15:39:46 +0300 Subject: [PATCH 63/93] action manager: removed unneeded assertion since listeners may get executed later, via focus manager --- .../openapi/actionSystem/impl/ActionManagerImpl.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java index 0bba9c872e5b..77aefc9eb471 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java @@ -1145,10 +1145,7 @@ public final class ActionManagerImpl extends ActionManagerEx implements Applicat } public void removeTimerListener(TimerListener listener){ - final boolean removed = myTimerListeners.remove(listener); - if (!removed) { - LOG.error("Unknown listener " + listener); - } + myTimerListeners.remove(listener); } public void actionPerformed(ActionEvent e) { @@ -1167,7 +1164,9 @@ public final class ActionManagerImpl extends ActionManagerEx implements Applicat IdeFocusManager.getInstance(null).doWhenFocusSettlesDown(new Runnable() { public void run() { for (TimerListener listener : listeners) { - runListenerAction(listener); + if (myTimerListeners.contains(listener)) { + runListenerAction(listener); + } } } }); From 78f9b956b322c21c1925fe379f14aae988c07f9f Mon Sep 17 00:00:00 2001 From: Maxim Medvedev Date: Fri, 19 Feb 2010 16:01:12 +0300 Subject: [PATCH 64/93] IDEA-39961: Check access modifiers compatibility --- .../plugins/groovy/GroovyBundle.properties | 7 +- .../groovy/annotator/GroovyAnnotator.java | 138 +++++++++++++----- .../annotator/intentions/GrModifierFix.java | 55 +++---- .../parameters/ParameterDeclaration.java | 5 +- .../modifiers/GrModifierListImpl.java | 3 +- .../AnonymousClassAbstractMethod.groovy | 2 +- .../expressions/closures/final_error.test | 2 +- .../ImplicitDefaultConstructorAfter.groovy | 2 +- 8 files changed, 148 insertions(+), 66 deletions(-) diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties b/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties index be4d094289e5..5477076735a1 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties @@ -125,7 +125,7 @@ case.expected='case' or 'default' expected block.expression.expected=Block expression expected wrong.string=Wrong string literal path.selector.expected=Property selector expected -duplicate.modifier=Duplicate modifier +duplicate.modifier=Duplicate modifier ''{0}'' param.expected=Parameter expected for.clause.expected=clause expected at.expected='@' expected @@ -175,6 +175,7 @@ static.declaration.in.inner.class=Inner classes cannot have static declarations constructors.are.not.allowed.in.anonymous.class=Constructors are not allowed in anonymous class no.such.property=Property ''{0}'' does not exist change.modifier=Make ''{0}'' {1} +change.modifier.not=Make ''{0}'' not {1} change.modifier.family.name=Change modifiers # {0} - colspan, {1} - method name, {2} - class name, {3} - formal myParameters row, {4} - arguments row @@ -206,7 +207,8 @@ intarface.cannot.have.modifier.final=interface cannot have modifier 'final' script.cannot.have.modifier.abstract=script cannot have modifier 'abstract' script.cannot.have.modifier.native=script cannot have modifier 'native' interface.must.have.no.static.method=interface must have no static method -not.abstract.class.cannot.have.abstract.method=not abstract class cannot have abstract method +only.abstract.class.can.have.abstract.method=only abstract class can have abstract method +anonymous.class.cannot.have.abstract.method=anonymous class cannot have abstract method illegal.combination.of.modifiers.volatile.and.final=illegal combination of modifiers 'volatile' and 'final' variable.cannot.be.native=variable cannot have modifier 'native' variable.cannot.be.abstract=variable cannot have modifier 'abstract' @@ -304,3 +306,4 @@ copy.groovy.files.to.output=Copy Groovy files to output as &resources in.expected='in' expected not.allowed.modifier.in.forin=Modifier ''{0}'' is not allowed here property.name.expected=Property name expected +add.method.body=Add method body diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java index 14404fc95fd1..c681e3cbeaea 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java @@ -16,6 +16,7 @@ package org.jetbrains.plugins.groovy.annotator; +import com.intellij.codeInsight.daemon.impl.quickfix.AddMethodBodyFix; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.lang.ASTNode; @@ -33,6 +34,7 @@ import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; +import gnu.trove.THashSet; import gnu.trove.TObjectHashingStrategy; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -238,7 +240,7 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { String modifier = modifiers[i]; modifierListCopy.setModifierProperty(modifier, true); if (facade.getResolveHelper().isAccessible(refElement, modifierListCopy, place, accessObjectClass, null)) { - IntentionAction fix = new GrModifierFix(refElement, modifier, true); + IntentionAction fix = new GrModifierFix(refElement, refElement.getModifierList(), modifier, true, true); annotation.registerFix(fix); } } @@ -283,18 +285,25 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { PsiElement typeDef = parent.getParent(); if (typeDef != null && typeDef instanceof GrTypeDefinition) { PsiModifierList modifiersList = variableDeclaration.getModifierList(); - checkAccessModifiers(myHolder, modifiersList); + final GrMember member = variableDeclaration.getMembers()[0]; + checkAccessModifiers(myHolder, modifiersList, member); + checkDuplicateModifiers(myHolder, variableDeclaration.getModifierList(), member); if (modifiersList.hasExplicitModifier(GrModifier.VOLATILE) && modifiersList.hasExplicitModifier(GrModifier.FINAL)) { - myHolder.createErrorAnnotation(modifiersList, GroovyBundle.message("illegal.combination.of.modifiers.volatile.and.final")); + final Annotation annotation = + myHolder.createErrorAnnotation(modifiersList, GroovyBundle.message("illegal.combination.of.modifiers.volatile.and.final")); + annotation.registerFix(new GrModifierFix(member, modifiersList, GrModifier.VOLATILE, true, false)); + annotation.registerFix(new GrModifierFix(member, modifiersList, GrModifier.FINAL, true, false)); } if (modifiersList.hasExplicitModifier(GrModifier.NATIVE)) { - myHolder.createErrorAnnotation(modifiersList, GroovyBundle.message("variable.cannot.be.native")); + final Annotation annotation = myHolder.createErrorAnnotation(modifiersList, GroovyBundle.message("variable.cannot.be.native")); + annotation.registerFix(new GrModifierFix(member, modifiersList, GrModifier.NATIVE, true, false)); } if (modifiersList.hasExplicitModifier(GrModifier.ABSTRACT)) { - myHolder.createErrorAnnotation(modifiersList, GroovyBundle.message("variable.cannot.be.abstract")); + final Annotation annotation = myHolder.createErrorAnnotation(modifiersList, GroovyBundle.message("variable.cannot.be.abstract")); + annotation.registerFix(new GrModifierFix(member, modifiersList, GrModifier.ABSTRACT, true, false)); } } } @@ -642,7 +651,8 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { if (classMember.hasModifierProperty(GrModifier.STATIC)) { final PsiElement modifier = findModifierStatic(classMember); if (modifier != null) { - holder.createErrorAnnotation(modifier, GroovyBundle.message("cannot.have.static.declarations")); + final Annotation annotation = holder.createErrorAnnotation(modifier, GroovyBundle.message("cannot.have.static.declarations")); + annotation.registerFix(new GrModifierFix(classMember, classMember.getModifierList(), GrModifier.STATIC, true, false)); } } } @@ -720,20 +730,41 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { } } + private static void registerAbstractMethodFix(Annotation annotation, GrMethod method, boolean makeClassAbstract) { + if (method.getBlock() == null) { + annotation.registerFix(new AddMethodBodyFix(method)); + } + else { + annotation.registerFix(new GrModifierFix(method, method.getModifierList(), GrModifier.ABSTRACT, false, false)); + } + if (makeClassAbstract) { + final PsiClass containingClass = method.getContainingClass(); + LOG.assertTrue(containingClass != null); + final GrModifierList list = (GrModifierList)containingClass.getModifierList(); + LOG.assertTrue(list != null); + annotation.registerFix(new GrModifierFix(containingClass, list, GrModifier.ABSTRACT, false, true)); + } + } + private static void checkMethodDefinitionModifiers(AnnotationHolder holder, GrMethod method) { - final PsiModifierList modifiersList = method.getModifierList(); - checkAccessModifiers(holder, modifiersList); + final GrModifierList modifiersList = method.getModifierList(); + checkAccessModifiers(holder, modifiersList, method); + checkDuplicateModifiers(holder, modifiersList, method); //script methods boolean isMethodAbstract = modifiersList.hasExplicitModifier(GrModifier.ABSTRACT); final boolean isMethodStatic = modifiersList.hasExplicitModifier(GrModifier.STATIC); if (method.getParent() instanceof GroovyFileBase) { if (isMethodAbstract) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("script.cannot.have.modifier.abstract")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("script.cannot.have.modifier.abstract")); + registerAbstractMethodFix(annotation, method, false); } if (modifiersList.hasExplicitModifier(GrModifier.NATIVE)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("script.cannot.have.modifier.native")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("script.cannot.have.modifier.native")); + annotation.registerFix(new GrModifierFix(method, modifiersList, GrModifier.NATIVE, false, false)); } } else //type definition methods @@ -743,11 +774,15 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { //interface if (containingTypeDef.isInterface()) { if (isMethodStatic) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("interface.must.have.no.static.method")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("interface.must.have.no.static.method")); + annotation.registerFix(new GrModifierFix(method, modifiersList, GrModifier.STATIC, true, false)); } if (modifiersList.hasExplicitModifier(GrModifier.PRIVATE)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("interface.must.have.no.private.method")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("interface.must.have.no.private.method")); + annotation.registerFix(new GrModifierFix(method, modifiersList, GrModifier.PRIVATE, true, false)); } } @@ -762,14 +797,18 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { else if (containingTypeDef.isAnonymous()) { //anonymous class if (isMethodStatic) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("static.declaration.in.inner.class")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("static.declaration.in.inner.class")); + annotation.registerFix(new GrModifierFix(method, modifiersList, GrModifier.STATIC, false, false)); } if (method.isConstructor()) { holder.createErrorAnnotation(method.getNameIdentifierGroovy(), GroovyBundle.message("constructors.are.not.allowed.in.anonymous.class")); } if (isMethodAbstract) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("not.abstract.class.cannot.have.abstract.method")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("anonymous.class.cannot.have.abstract.method")); + registerAbstractMethodFix(annotation, method, false); } } else { @@ -779,13 +818,18 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { if (!typeDefModifiersList.hasExplicitModifier(GrModifier.ABSTRACT)) { if (isMethodAbstract) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("not.abstract.class.cannot.have.abstract.method")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("only.abstract.class.can.have.abstract.method")); + registerAbstractMethodFix(annotation, method, true); } } if (!isMethodAbstract) { if (method.getBlock() == null) { - holder.createErrorAnnotation(method.getNameIdentifierGroovy(), GroovyBundle.message("not.abstract.method.should.have.body")); + final Annotation annotation = holder + .createErrorAnnotation(method.getNameIdentifierGroovy(), GroovyBundle.message("not.abstract.method.should.have.body")); + annotation.registerFix(new AddMethodBodyFix(method)); + } } if (isMethodStatic) { @@ -796,12 +840,13 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { } private static void checkTypeDefinitionModifiers(AnnotationHolder holder, GrTypeDefinition typeDefinition) { - PsiModifierList modifiersList = typeDefinition.getModifierList(); + GrModifierList modifiersList = typeDefinition.getModifierList(); if (modifiersList == null) return; /**** class ****/ - checkAccessModifiers(holder, modifiersList); + checkAccessModifiers(holder, modifiersList, typeDefinition); + checkDuplicateModifiers(holder, modifiersList, typeDefinition); PsiClassType[] extendsListTypes = typeDefinition.getExtendsListTypes(); @@ -812,48 +857,75 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { PsiModifierList modifierList = psiClass.getModifierList(); if (modifierList != null) { if (modifierList.hasExplicitModifier(GrModifier.FINAL)) { - holder.createErrorAnnotation(typeDefinition.getNameIdentifierGroovy(), GroovyBundle.message("final.class.cannot.be.extended")); + final Annotation annotation = holder + .createErrorAnnotation(typeDefinition.getNameIdentifierGroovy(), GroovyBundle.message("final.class.cannot.be.extended")); + annotation.registerFix(new GrModifierFix(typeDefinition, modifiersList, GrModifier.FINAL, false, false)); } } } } if (modifiersList.hasExplicitModifier(GrModifier.ABSTRACT) && modifiersList.hasExplicitModifier(GrModifier.FINAL)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("illegal.combination.of.modifiers.abstract.and.final")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("illegal.combination.of.modifiers.abstract.and.final")); + annotation.registerFix(new GrModifierFix(typeDefinition, modifiersList, GrModifier.FINAL, false, false)); + annotation.registerFix(new GrModifierFix(typeDefinition, modifiersList, GrModifier.ABSTRACT, false, false)); + } if (modifiersList.hasExplicitModifier(GrModifier.TRANSIENT)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("modifier.transient.not.allowed.here")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("modifier.transient.not.allowed.here")); + annotation.registerFix(new GrModifierFix(typeDefinition, modifiersList, GrModifier.TRANSIENT, false, false)); } if (modifiersList.hasExplicitModifier(GrModifier.VOLATILE)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("modifier.volatile.not.allowed.here")); + final Annotation annotation = holder.createErrorAnnotation(modifiersList, GroovyBundle.message("modifier.volatile.not.allowed.here")); + annotation.registerFix(new GrModifierFix(typeDefinition, modifiersList, GrModifier.VOLATILE, false, false)); } /**** interface ****/ if (typeDefinition.isInterface()) { if (modifiersList.hasExplicitModifier(GrModifier.FINAL)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("intarface.cannot.have.modifier.final")); - } - - if (modifiersList.hasExplicitModifier(GrModifier.VOLATILE)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("modifier.volatile.not.allowed.here")); - } - - if (modifiersList.hasExplicitModifier(GrModifier.TRANSIENT)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("modifier.transient.not.allowed.here")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("intarface.cannot.have.modifier.final")); + annotation.registerFix(new GrModifierFix(typeDefinition, modifiersList, GrModifier.FINAL, false, false)); } } checkStaticDeclarationsInInnerClass(typeDefinition, holder); } - private static void checkAccessModifiers(AnnotationHolder holder, @NotNull PsiModifierList modifierList) { + private static void checkDuplicateModifiers(AnnotationHolder holder, @NotNull GrModifierList list, PsiMember member) { + final PsiElement[] modifiers = list.getModifiers(); + Set set = new THashSet(modifiers.length); + for (PsiElement modifier : modifiers) { + String name = modifier.getText(); + if (set.contains(name)) { + final Annotation annotation = holder.createErrorAnnotation(list, GroovyBundle.message("duplicate.modifier", name)); + annotation.registerFix(new GrModifierFix(member, list, name, false, false)); + } + else { + set.add(name); + } + } + } + + private static void checkAccessModifiers(AnnotationHolder holder, @NotNull PsiModifierList modifierList, PsiMember member) { boolean hasPrivate = modifierList.hasExplicitModifier(GrModifier.PRIVATE); boolean hasPublic = modifierList.hasExplicitModifier(GrModifier.PUBLIC); boolean hasProtected = modifierList.hasExplicitModifier(GrModifier.PROTECTED); if (hasPrivate && hasPublic || hasPrivate && hasProtected || hasPublic && hasProtected) { - holder.createErrorAnnotation(modifierList, GroovyBundle.message("illegal.combination.of.modifiers")); + final Annotation annotation = holder.createErrorAnnotation(modifierList, GroovyBundle.message("illegal.combination.of.modifiers")); + if (hasPrivate) { + annotation.registerFix(new GrModifierFix(member, modifierList, GrModifier.PRIVATE, false, false)); + } + if (hasProtected) { + annotation.registerFix(new GrModifierFix(member, modifierList, GrModifier.PROTECTED, false, false)); + } + if (hasPublic) { + annotation.registerFix(new GrModifierFix(member, modifierList, GrModifier.PUBLIC, false, false)); + } } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GrModifierFix.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GrModifierFix.java index 27091ee62eb6..057f39f991ca 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GrModifierFix.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GrModifierFix.java @@ -18,31 +18,41 @@ package org.jetbrains.plugins.groovy.annotator.intentions; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; -import com.intellij.psi.*; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiMember; +import com.intellij.psi.PsiModifierList; import com.intellij.util.IncorrectOperationException; import com.intellij.util.VisibilityUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.GroovyBundle; -import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement; -import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; /** * @author Maxim.Medvedev */ public class GrModifierFix implements IntentionAction { - private final PsiMember myMember; + @NotNull private final PsiMember myMember; private final String myModifier; - private final boolean showContainingClass; + private final boolean myShowContainingClass; + private final PsiModifierList myModifierList; + private final boolean myDoSet; - public GrModifierFix(PsiMember member, String modifier, boolean showContainingClass) { + public GrModifierFix(@NotNull PsiMember member, + @NotNull PsiModifierList modifierList, + String modifier, + boolean showContainingClass, + boolean doSet) { myMember = member; myModifier = modifier; - this.showContainingClass = showContainingClass; + myShowContainingClass = showContainingClass; + myModifierList = modifierList; + myDoSet = doSet; } @NotNull public String getText() { - if (showContainingClass) { + String name; + if (myShowContainingClass) { final PsiClass containingClass = myMember.getContainingClass(); String containingClassName; if (containingClass != null) { @@ -51,12 +61,19 @@ public class GrModifierFix implements IntentionAction { else { containingClassName = ""; } - String modifierText = VisibilityUtil.toPresentableText(myModifier); - return GroovyBundle.message("change.modifier", containingClassName + myMember.getName(), modifierText); + name = containingClassName + myMember.getName(); } else { - return GroovyBundle.message("change.modifier", myMember.getName(), myModifier); + name = myMember.getName(); + } + String modifierText = VisibilityUtil.toPresentableText(myModifier); + + if (myDoSet) { + return GroovyBundle.message("change.modifier", name, modifierText); + } + else { + return GroovyBundle.message("change.modifier.not", name, modifierText); } } @@ -66,23 +83,11 @@ public class GrModifierFix implements IntentionAction { } public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { - final PsiReference ref = file.findReferenceAt(editor.getCaretModel().getOffset()); - if (ref == null) return false; - final PsiElement element = ref.getElement(); - if (element instanceof GrReferenceElement) { - final GroovyResolveResult resolveResult = ((GrReferenceElement)element).advancedResolve(); - if (!resolveResult.isAccessible() && resolveResult.getElement() instanceof PsiMember) { - return true; - } - } - return false; + return myModifierList != null && myModifierList.isValid(); } public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { - final PsiModifierList list = myMember.getModifierList(); - if (list != null) { - list.setModifierProperty(myModifier, true); - } + myModifierList.setModifierProperty(myModifier, myDoSet); } public boolean startInWriteAction() { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/auxiliary/parameters/ParameterDeclaration.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/auxiliary/parameters/ParameterDeclaration.java index dc807d7644e5..a810c1ee862f 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/auxiliary/parameters/ParameterDeclaration.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/auxiliary/parameters/ParameterDeclaration.java @@ -25,6 +25,7 @@ import org.jetbrains.plugins.groovy.lang.parser.parsing.auxiliary.VariableInitia import org.jetbrains.plugins.groovy.lang.parser.parsing.auxiliary.annotations.Annotation; import org.jetbrains.plugins.groovy.lang.parser.parsing.types.TypeSpec; import org.jetbrains.plugins.groovy.lang.parser.parsing.util.ParserUtils; +import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier; import java.util.HashSet; import java.util.Set; @@ -86,7 +87,7 @@ public class ParameterDeclaration implements GroovyElementTypes { if (kFINAL.equals(builder.getTokenType())) { if (modSet.contains(kFINAL)) { - ParserUtils.wrapError(builder, GroovyBundle.message("duplicate.modifier")); + ParserUtils.wrapError(builder, GroovyBundle.message("duplicate.modifier", GrModifier.FINAL)); } else { builder.advanceLexer(); modSet.add(kFINAL); @@ -94,7 +95,7 @@ public class ParameterDeclaration implements GroovyElementTypes { ParserUtils.getToken(builder, mNLS); } else if (kDEF.equals(builder.getTokenType())) { if (modSet.contains(kDEF)) { - ParserUtils.wrapError(builder, GroovyBundle.message("duplicate.modifier")); + ParserUtils.wrapError(builder, GroovyBundle.message("duplicate.modifier", GrModifier.DEF)); } else { builder.advanceLexer(); modSet.add(kDEF); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java index 494851af58f9..d00322776531 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java @@ -222,7 +222,8 @@ public class GrModifierListImpl extends GroovyBaseElementImplabstract void foo(); + abstract void foo(); } diff --git a/plugins/groovy/testdata/parsing/groovy/expressions/closures/final_error.test b/plugins/groovy/testdata/parsing/groovy/expressions/closures/final_error.test index daa2de0d4ad5..e59fb8978aa4 100644 --- a/plugins/groovy/testdata/parsing/groovy/expressions/closures/final_error.test +++ b/plugins/groovy/testdata/parsing/groovy/expressions/closures/final_error.test @@ -19,7 +19,7 @@ Groovy script PsiWhiteSpace(' ') PsiElement(final)('final') PsiWhiteSpace(' ') - PsiErrorElement:Duplicate modifier + PsiErrorElement:Duplicate modifier 'def' PsiElement(def)('def') PsiWhiteSpace(' ') PsiElement(identifier)('i') diff --git a/plugins/groovy/testdata/refactoring/introduceParameter/implicitDefaultConstructor/ImplicitDefaultConstructorAfter.groovy b/plugins/groovy/testdata/refactoring/introduceParameter/implicitDefaultConstructor/ImplicitDefaultConstructorAfter.groovy index 749a1ba9e734..19c1e90323eb 100644 --- a/plugins/groovy/testdata/refactoring/introduceParameter/implicitDefaultConstructor/ImplicitDefaultConstructorAfter.groovy +++ b/plugins/groovy/testdata/refactoring/introduceParameter/implicitDefaultConstructor/ImplicitDefaultConstructorAfter.groovy @@ -1,5 +1,5 @@ class B extends A { - public B() { + def B() { super(27) } From ecadd0548023abf2c12541c036424cd9493111ba Mon Sep 17 00:00:00 2001 From: Dmitry Jemerov Date: Fri, 19 Feb 2010 16:15:39 +0300 Subject: [PATCH 65/93] call backspace handler delegates also after deleting the last character of file (needed for Ruby/Python backspace unindent to work correctly) --- .../intellij/codeInsight/editorActions/BackspaceHandler.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/BackspaceHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/BackspaceHandler.java index 0714bdc304b7..9a7b1b063652 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/BackspaceHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/BackspaceHandler.java @@ -90,14 +90,13 @@ public class BackspaceHandler extends EditorWriteActionHandler { myOriginalHandler.execute(editor, dataContext); - if (offset >= editor.getDocument().getTextLength()) return true; - for(BackspaceHandlerDelegate delegate: delegates) { if (delegate.charDeleted(c, file, editor)) { return true; } } + if (offset >= editor.getDocument().getTextLength()) return true; chars = editor.getDocument().getCharsSequence(); if (c == '(' || c == '[' || c == '{'){ From b7c468d2a7d74fa0e8a7c7e3e3b89c3901cb61eb Mon Sep 17 00:00:00 2001 From: Alexander Doroshko Date: Fri, 19 Feb 2010 16:19:04 +0300 Subject: [PATCH 66/93] CompilerSettingsFactory interface moved to [compiler-openapi] module --- .../src/com/intellij/compiler/CompilerSettingsFactory.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename java/compiler/{impl => openapi}/src/com/intellij/compiler/CompilerSettingsFactory.java (100%) diff --git a/java/compiler/impl/src/com/intellij/compiler/CompilerSettingsFactory.java b/java/compiler/openapi/src/com/intellij/compiler/CompilerSettingsFactory.java similarity index 100% rename from java/compiler/impl/src/com/intellij/compiler/CompilerSettingsFactory.java rename to java/compiler/openapi/src/com/intellij/compiler/CompilerSettingsFactory.java From 8b0ba8c2a3357048806998a4090910c7616d846b Mon Sep 17 00:00:00 2001 From: Dmitry Jemerov Date: Fri, 19 Feb 2010 16:25:09 +0300 Subject: [PATCH 67/93] http://ea.jetbrains.com/browser/ea_problems/18615 --- .../intellij/codeInsight/navigation/CtrlMouseHandler.java | 5 +++-- .../navigation/actions/GotoDeclarationAction.java | 5 +++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java index 02bd1aafc627..75a4f28b976d 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java @@ -347,8 +347,9 @@ public class CtrlMouseHandler extends AbstractProjectComponent { return new InfoSingle (ref, resolvedElement); } } - targetElement = GotoDeclarationAction.findTargetElement(myProject, editor, offset); - } else if ( browseMode == BrowseMode.Implementation ) { + targetElement = GotoDeclarationAction.findTargetElementNoVS(myProject, editor, offset); + } + else if ( browseMode == BrowseMode.Implementation ) { final PsiElement element = TargetElementUtilBase.getInstance().findTargetElement(editor, ImplementationSearcher.getFlags(), offset); PsiElement[] targetElements = new ImplementationSearcher() { @NotNull diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java index a18141721b90..4978f3180d57 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java @@ -155,6 +155,11 @@ public class GotoDeclarationAction extends BaseCodeInsightAction implements Code return null; } + return findTargetElementNoVS(project, editor, offset); + } + + @Nullable + public static PsiElement findTargetElementNoVS(Project project, Editor editor, int offset) { PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == null) { return null; From 350778c328abdb5cbc904327c9b8d7c16ebb5701 Mon Sep 17 00:00:00 2001 From: Eugene Kudelevsky Date: Fri, 19 Feb 2010 16:44:56 +0300 Subject: [PATCH 68/93] fix php editing (WI-1134) --- .../codeInsight/template/XmlCustomLiveTemplate.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java b/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java index 8e6a65acd97d..fad2be78c8bf 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java +++ b/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java @@ -16,12 +16,13 @@ package com.intellij.codeInsight.template; import com.intellij.codeInsight.template.impl.TemplateImpl; +import com.intellij.lang.xml.XMLLanguage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.util.Pair; -import com.intellij.psi.xml.XmlFile; +import com.intellij.psi.PsiFile; import com.intellij.util.containers.HashMap; import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.NotNull; @@ -273,7 +274,8 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } public boolean isApplicable(@NotNull String key, @NotNull CustomTemplateCallback callback) { - if (callback.getFile() instanceof XmlFile) { + PsiFile file = callback.getFile(); + if (file.getLanguage() instanceof XMLLanguage) { List tokens = parse(key, callback); if (tokens != null) { return check(tokens); From c0e76b17ae0dfc401a8ce8cc96f31615a264c007 Mon Sep 17 00:00:00 2001 From: "Maxim.Mossienko" Date: Fri, 19 Feb 2010 17:20:16 +0300 Subject: [PATCH 69/93] WI-1148 Html tag autoclosing does not work in some cases --- .../editorActions/XmlGtTypedHandler.java | 56 ++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/xml/impl/src/com/intellij/codeInsight/editorActions/XmlGtTypedHandler.java b/xml/impl/src/com/intellij/codeInsight/editorActions/XmlGtTypedHandler.java index 443100f5b0cf..a3c483947650 100644 --- a/xml/impl/src/com/intellij/codeInsight/editorActions/XmlGtTypedHandler.java +++ b/xml/impl/src/com/intellij/codeInsight/editorActions/XmlGtTypedHandler.java @@ -17,6 +17,7 @@ package com.intellij.codeInsight.editorActions; import com.intellij.application.options.editor.WebEditorOptions; import com.intellij.codeInsight.highlighting.BraceMatchingUtil; +import com.intellij.lang.ASTNode; import com.intellij.lang.xml.XMLLanguage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; @@ -30,6 +31,7 @@ import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.html.HtmlTag; import com.intellij.psi.impl.source.xml.XmlTokenImpl; import com.intellij.psi.tree.IElementType; +import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.*; import com.intellij.util.IncorrectOperationException; import com.intellij.xml.XmlElementDescriptor; @@ -160,7 +162,59 @@ public class XmlGtTypedHandler extends TypedHandlerDelegate { if (nameToken != null && nameToken.getTextRange().getStartOffset() > offset) return Result.CONTINUE; HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(tagOffset); - if (BraceMatchingUtil.matchBrace(editor.getDocument().getCharsSequence(), editedFile.getFileType(), iterator, true,true)) return Result.CONTINUE; + if (BraceMatchingUtil.matchBrace(editor.getDocument().getCharsSequence(), editedFile.getFileType(), iterator, true,true)) { + PsiElement parent = tag.getParent(); + boolean hasBalance = true; + + while(parent instanceof XmlTag && name.equals(((XmlTag)parent).getName())) { + ASTNode astNode = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(parent.getNode()); + if (astNode == null) { + hasBalance = false; + break; + } + + parent = parent.getParent(); + } + + if (hasBalance) { + hasBalance = false; + for(ASTNode node=parent.getNode().getLastChildNode(); node != null; node = node.getTreePrev()) { + ASTNode leaf = node; + if (leaf.getElementType() == TokenType.ERROR_ELEMENT) { + ASTNode firstChild = leaf.getFirstChildNode(); + if (firstChild != null) leaf = firstChild; + else { + PsiElement psiElement = PsiTreeUtil.nextLeaf(leaf.getPsi()); + leaf = psiElement != null ? psiElement.getNode() : null; + } + if (leaf != null && leaf.getElementType() == TokenType.WHITE_SPACE) { + PsiElement psiElement = PsiTreeUtil.nextLeaf(leaf.getPsi()); + if (psiElement != null) leaf = psiElement.getNode(); + } + } + + if (leaf != null && leaf.getElementType() == XmlTokenType.XML_END_TAG_START) { + ASTNode treeNext = leaf.getTreeNext(); + IElementType treeNextType; + if (treeNext != null && + ((treeNextType = treeNext.getElementType()) == XmlTokenType.XML_NAME || + treeNextType == XmlTokenType.XML_TAG_NAME + ) + ) { + if (name.equals(treeNext.getText())) { + ASTNode parentEndName = parent instanceof XmlTag ? + XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(parent.getNode()):null; + hasBalance = !(parent instanceof XmlTag) || + parentEndName != null && !parentEndName.getText().equals(name); + break; + } + } + } + } + } + + if (hasBalance) return Result.CONTINUE; + } boolean insertedCData = false; final XmlElementDescriptor descriptor = tag.getDescriptor(); From 54ba2266c6c35504ca5a3e1b64d65bc8c4ae3dec Mon Sep 17 00:00:00 2001 From: Maxim Medvedev Date: Fri, 19 Feb 2010 17:28:26 +0300 Subject: [PATCH 70/93] IDEA-51934: Groovy constructor calls should be disambiguated by parameter count --- .../plugins/groovy/lang/resolve/ResolveUtil.java | 10 ++++++---- .../lang/resolve/processors/CompletionProcessor.java | 2 +- .../resolve/processors/MethodResolverProcessor.java | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java index 69fa1301397c..7f681e2ada76 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java @@ -348,7 +348,7 @@ public class ResolveUtil { return elements; } - public static GroovyResolveResult[] filterSameSignatureCandidates(Collection candidates) { + public static GroovyResolveResult[] filterSameSignatureCandidates(Collection candidates, int argumentCount) { GroovyResolveResult[] array = candidates.toArray(new GroovyResolveResult[candidates.size()]); if (array.length == 1) return array; @@ -365,10 +365,10 @@ public class ResolveUtil { PsiElement element = otherResolveResult.getElement(); if (element instanceof PsiMethod) { PsiMethod method = (PsiMethod)element; - if (dominated(currentMethod, array[i].getSubstitutor(), method, otherResolveResult.getSubstitutor())) { + if (dominated(currentMethod, array[i].getSubstitutor(), method, otherResolveResult.getSubstitutor(), argumentCount)) { continue Outer; } - else if (dominated(method, otherResolveResult.getSubstitutor(), currentMethod, array[i].getSubstitutor())) { + else if (dominated(method, otherResolveResult.getSubstitutor(), currentMethod, array[i].getSubstitutor(), argumentCount)) { iterator.remove(); } } @@ -384,11 +384,13 @@ public class ResolveUtil { public static boolean dominated(PsiMethod method1, PsiSubstitutor substitutor1, PsiMethod method2, - PsiSubstitutor substitutor2) { //method1 has more general parameter types thn method2 + PsiSubstitutor substitutor2, + int argumentCount) { //method1 has more general parameter types then method2 if (!method1.getName().equals(method2.getName())) return false; PsiParameter[] params1 = method1.getParameterList().getParameters(); PsiParameter[] params2 = method2.getParameterList().getParameters(); + if (argumentCount != params1.length && argumentCount == params2.length) return true; if (params1.length != params2.length) return false; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/CompletionProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/CompletionProcessor.java index 16209a63aa01..d60adfc72832 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/CompletionProcessor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/CompletionProcessor.java @@ -55,6 +55,6 @@ public class CompletionProcessor extends ResolverProcessor { public GroovyResolveResult[] getCandidates() { if (myCandidates.size() == 0) return GroovyResolveResult.EMPTY_ARRAY; - return ResolveUtil.filterSameSignatureCandidates(myCandidates); + return ResolveUtil.filterSameSignatureCandidates(myCandidates, -1); } } \ No newline at end of file diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/MethodResolverProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/MethodResolverProcessor.java index d43dcbb5c16f..530cbe2cdff1 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/MethodResolverProcessor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/MethodResolverProcessor.java @@ -212,7 +212,7 @@ public class MethodResolverProcessor extends ResolverProcessor { return filterCandidates(); } if (!myInapplicableCandidates.isEmpty()) { - return ResolveUtil.filterSameSignatureCandidates(myInapplicableCandidates); + return ResolveUtil.filterSameSignatureCandidates(myInapplicableCandidates, myArgumentTypes != null ? myArgumentTypes.length : -1); } return GroovyResolveResult.EMPTY_ARRAY; } From 695afac596ebc0ca93f699e4ddfe7735539b2a12 Mon Sep 17 00:00:00 2001 From: Pavel Fatin Date: Fri, 19 Feb 2010 17:31:02 +0300 Subject: [PATCH 71/93] IDEA-52386 - Better top-level class detection for stubs generation --- .../impl/compiled/ClassFileStubBuilder.java | 36 ++++- .../compiled/ClassFileStubBuilderTest.java | 143 ++++++++++++++++++ 2 files changed, 176 insertions(+), 3 deletions(-) create mode 100644 java/java-tests/testSrc/com/intellij/psi/impl/compiled/ClassFileStubBuilderTest.java diff --git a/java/java-impl/src/com/intellij/psi/impl/compiled/ClassFileStubBuilder.java b/java/java-impl/src/com/intellij/psi/impl/compiled/ClassFileStubBuilder.java index 1f455afe852a..bba38dd08fd2 100644 --- a/java/java-impl/src/com/intellij/psi/impl/compiled/ClassFileStubBuilder.java +++ b/java/java-impl/src/com/intellij/psi/impl/compiled/ClassFileStubBuilder.java @@ -28,11 +28,21 @@ import com.intellij.util.cls.ClsFormatException; public class ClassFileStubBuilder implements BinaryFileStubBuilder { public boolean acceptsFile(final VirtualFile file) { - return !isInner(file.getNameWithoutExtension()); + return !isInner(file.getNameWithoutExtension(), new ParentDirectory(file)); } - private static boolean isInner(final String name) { - return name.indexOf('$') >= 0; + static boolean isInner(final String name, final Directory directory) { + return isInner(name, 0, directory); + } + + private static boolean isInner(final String name, final int from, final Directory directory) { + final int index = name.indexOf('$', from); + return index == -1 ? false + : containsPart(directory, name, index) ? true : isInner(name, index + 1, directory); + } + + private static boolean containsPart(Directory directory, String name, int endIndex) { + return endIndex > 0 && directory.contains(name.substring(0, endIndex)); } public StubElement buildStubTree(final VirtualFile file, final byte[] content, final Project project) { @@ -47,4 +57,24 @@ public class ClassFileStubBuilder implements BinaryFileStubBuilder { public int getStubVersion() { return JavaFileElementType.STUB_VERSION; } + + + interface Directory { + boolean contains(String name); + } + + private static class ParentDirectory implements Directory { + private final VirtualFile myDirectory; + private final String myExtension; + + private ParentDirectory(final VirtualFile file) { + myDirectory = file.getParent(); + myExtension = file.getExtension(); + } + + public boolean contains(final String name) { + final String fullName = myExtension == null ? name : name + "." + myExtension; + return myDirectory == null ? false : myDirectory.findChild(fullName) != null; + } + } } \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/compiled/ClassFileStubBuilderTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/compiled/ClassFileStubBuilderTest.java new file mode 100644 index 000000000000..b5e9fa54880f --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/psi/impl/compiled/ClassFileStubBuilderTest.java @@ -0,0 +1,143 @@ +package com.intellij.psi.impl.compiled; + +import junit.framework.TestCase; + +import java.util.*; + +/** + * Pavel.Fatin, 18.02.2010 + */ +public class ClassFileStubBuilderTest extends TestCase { + public void testOneFile() { + assertTopLevel(""); + assertTopLevel("$"); + assertTopLevel("$$"); + assertTopLevel("$$$"); + assertTopLevel("Foo"); + assertTopLevel("Foo$"); + assertTopLevel("$Foo"); + assertTopLevel("$Foo$"); + assertTopLevel("Foo$Bar"); + assertTopLevel("$Foo$Bar"); + assertTopLevel("Foo$Bar$"); + assertTopLevel("$Foo$Bar$"); + assertTopLevel("$$Foo$$Bar$$"); + } + + public void testWrongCase() { + assertTopLevel("Foo$Bar", "foo"); + assertTopLevel("foo$Bar", "Foo"); + } + + public void testShortName() { + assertTopLevel("A"); + + assertInner("Foo$B", "Foo"); + assertInner("A$Foo", "A"); + assertInner("A$B", "A"); + + assertTopLevel("A$B", "A$"); + assertTopLevel("A$B", "$B"); + assertTopLevel("A$B", "B"); + assertTopLevel("A$B", "$"); + } + + public void testShortNames() { + assertInner("A$B$C", "A"); + assertInner("A$B$C", "A$B"); + assertInner("A$B$C", "A", "A$B"); + + assertTopLevel("A$B$C", "A$"); + assertTopLevel("A$B$C", "A$B$"); + } + + public void testEmptyFileName() { + assertTopLevel("$Foo", ""); + } + + public void testNoInnerName() { + //assertTopLevel("Foo$", "Foo"); + //assertTopLevel("Foo$$", "Foo$"); + // an exception to the rule (to hide Scala "objects") + assertInner("Foo$", "Foo"); + assertInner("Foo$$", "Foo$"); + } + + public void testDollarsInName() { + assertInner("$Foo$Bar", "$Foo"); + assertInner("Foo$$Bar", "Foo"); + assertInner("Foo$$Bar", "Foo"); + assertInner("$Foo$$Bar", "$Foo"); + assertInner("$Foo$$Bar", "$Foo$"); + } + + public void testInner() { + assertInner("Foo$Bar", "Foo"); + assertInner("Foo$bar", "Foo"); + assertInner("foo$Bar", "foo"); + assertInner("foo$bar", "foo"); + } + + public void testInnerAndNoise() { + assertInner("Foo$Bar", "Foo", "Foo$", "$Bar", "Bar"); + } + + public void testTopLevel() { + assertTopLevel("Foo$Bar"); + assertTopLevel("Foo$Bar", "Foo$"); + assertTopLevel("Foo$Bar", "$Bar"); + assertTopLevel("Foo$Bar", "Bar"); + assertTopLevel("Foo$Bar", "Foo$", "$Bar", "Bar"); + } + + public void testInners() { + assertInner("Foo$Bar$Moo", "Foo"); + assertInner("Foo$Bar$Moo", "Foo$Bar"); + assertInner("Foo$Bar$Moo", "Foo", "Foo$Bar"); + } + + public void testInnersAndNoise() { + assertInner("Foo$Bar$Moo", "Foo", "$Bar", "Bar", "$Moo", "Moo", "Bar$Moo", "$Bar$Moo"); + assertInner("Foo$Bar$Moo", "Foo$Bar", "$Bar", "Bar", "$Moo", "Moo", "Bar$Moo", "$Bar$Moo"); + assertInner("Foo$Bar$Moo", "Foo", "Foo$Bar", "$Bar", "Bar", "$Moo", "Moo", "Bar$Moo", "$Bar$Moo"); + } + + public void testTopLevels() { + assertTopLevel("Foo$Bar$Moo"); + assertTopLevel("Foo$Bar$Moo", "$Bar"); + assertTopLevel("Foo$Bar$Moo", "Bar"); + assertTopLevel("Foo$Bar$Moo", "$Moo"); + assertTopLevel("Foo$Bar$Moo", "Moo"); + assertTopLevel("Foo$Bar$Moo", "Bar$Moo"); + assertTopLevel("Foo$Bar$Moo", "$Bar$Moo"); + assertTopLevel("Foo$Bar$Moo", "$Bar", "Bar", "$Moo", "Moo", "Bar$Moo", "$Bar$Moo"); + } + + private static void assertInner(String name, String... files) { + assertTrue("Class " + name + " must be identified as inner", isInner(name, files)); + } + + private static void assertTopLevel(String name, String... files) { + assertFalse("Class " + name + " must be identified as top-level", isInner(name, files)); + } + + private static boolean isInner(String name, String... files) { + Set all = new HashSet(); + all.addAll(Arrays.asList(files)); + all.add(name); + return ClassFileStubBuilder.isInner(name, new DirectoryMock(all)); + } + + + private static class DirectoryMock implements ClassFileStubBuilder.Directory { + private Set myFiles; + + private DirectoryMock(Set files) { + myFiles = files; + } + + public boolean contains(String name) { + return myFiles.contains(name); + } + } +} \ No newline at end of file From 29d98d9a1bc147baac6635d568f2de10a3e95472 Mon Sep 17 00:00:00 2001 From: "Maxim.Mossienko" Date: Fri, 19 Feb 2010 17:44:54 +0300 Subject: [PATCH 72/93] WI-1155 Exception when trying to evaluate Xpath --- .../plugins/xpathView/XPathEvalAction.java | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java index cc56c4838485..c00667583fa1 100644 --- a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java +++ b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java @@ -17,6 +17,7 @@ package org.intellij.plugins.xpathView; import com.intellij.find.FindProgressIndicator; import com.intellij.ide.projectView.PresentationData; +import com.intellij.lang.Language; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.LangDataKeys; @@ -38,9 +39,11 @@ import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.WindowManager; +import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; +import com.intellij.psi.templateLanguages.TemplateLanguageFileViewProvider; import com.intellij.psi.xml.XmlElement; import com.intellij.psi.xml.XmlFile; import com.intellij.usageView.UsageInfo; @@ -60,7 +63,10 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; /** *

This class implements the core action to enter, evaluate and display the results of an XPath expression.

@@ -184,6 +190,14 @@ public class XPathEvalAction extends XPathAction { if (contextNode == null) { // in XPath data model, / is the document itself, including comments, PIs and the root element contextNode = ((XmlFile)psiFile).getDocument(); + if (contextNode == null) { + FileViewProvider fileViewProvider = psiFile.getViewProvider(); + if (fileViewProvider instanceof TemplateLanguageFileViewProvider) { + Language dataLanguage = ((TemplateLanguageFileViewProvider)fileViewProvider).getTemplateDataLanguage(); + PsiFile templateDataFile = fileViewProvider.getPsi(dataLanguage); + if (templateDataFile instanceof XmlFile) contextNode = ((XmlFile)templateDataFile).getDocument(); + } + } } input = inputXPathExpression(project, contextNode); @@ -195,7 +209,7 @@ public class XPathEvalAction extends XPathAction { } HighlighterUtil.clearHighlighters(editor); - } while (evaluateExpression(input, contextNode, editor, cfg)); + } while (contextNode != null && evaluateExpression(input, contextNode, editor, cfg)); } private boolean evaluateExpression(EvalExpressionDialog.Context context, XmlElement contextNode, Editor editor, Config cfg) { From 6b5d2f1152aa3ee9057819d3fd078e3070cede00 Mon Sep 17 00:00:00 2001 From: Eugene Kudelevsky Date: Fri, 19 Feb 2010 18:25:04 +0300 Subject: [PATCH 73/93] correct work of Zen Coding inside inline HTML tag (WI-1131) --- .../template/CustomLiveTemplate.java | 5 +- .../template/impl/TemplateManagerImpl.java | 38 ++----------- .../template/XmlCustomLiveTemplate.java | 53 ++++++++++++++++--- 3 files changed, 53 insertions(+), 43 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/CustomLiveTemplate.java b/platform/lang-impl/src/com/intellij/codeInsight/template/CustomLiveTemplate.java index 74912fddebad..959aa06fa19a 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/CustomLiveTemplate.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/CustomLiveTemplate.java @@ -26,7 +26,8 @@ import org.jetbrains.annotations.Nullable; public interface CustomLiveTemplate { ExtensionPointName EP_NAME = ExtensionPointName.create("com.intellij.customLiveTemplate"); - boolean isApplicable(@NotNull String key, @NotNull CustomTemplateCallback callback); + @Nullable + String computeTemplateKey(@NotNull CustomTemplateCallback callback); - void execute(@NotNull String key, @NotNull CustomTemplateCallback callback, @Nullable TemplateInvokationListener listener); + void execute(String key, @NotNull CustomTemplateCallback callback, @Nullable TemplateInvokationListener listener); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java index 0f661293de45..6bfda59e3a57 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java @@ -220,47 +220,19 @@ public class TemplateManagerImpl extends TemplateManager implements ProjectCompo } } - private static String getCurrentLineBeforeCaret(@NotNull Editor editor) { - CaretModel caretModel = editor.getCaretModel(); - int line = caretModel.getLogicalPosition().line; - int lineStart = editor.getDocument().getLineStartOffset(line); - int offset = caretModel.getOffset(); - String s = editor.getDocument().getCharsSequence().subSequence(lineStart, offset).toString(); - int index = 0; - while (index < s.length() && Character.isWhitespace(s.charAt(index))) { - index++; - } - return index < s.length() ? s.substring(index) : s; - } - - @NotNull - private static String normalize(@NotNull String key) { - int lastWhitespaceIndex = -1; - for (int i = 0; i < key.length(); i++) { - if (Character.isWhitespace(key.charAt(i))) { - lastWhitespaceIndex = i; - } - } - if (lastWhitespaceIndex >= 0 && lastWhitespaceIndex < key.length() - 1) { - return key.substring(lastWhitespaceIndex + 1); - } - return key; - } - public boolean startTemplate(final Editor editor, char shortcutChar, final PairProcessor processor) { PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, myProject); if (file == null) return false; TemplateSettings templateSettings = TemplateSettings.getInstance(); if (shortcutChar == templateSettings.getDefaultShortcutChar()) { for (final CustomLiveTemplate customLiveTemplate : CustomLiveTemplate.EP_NAME.getExtensions()) { - final String currentLineBeforeCaret = normalize(getCurrentLineBeforeCaret(editor)); final CustomTemplateCallback callback = new CustomTemplateCallback(editor, file); - if (customLiveTemplate.isApplicable(currentLineBeforeCaret, callback)) { - int offset = editor.getCaretModel().getOffset(); - final int startOffset = offset - currentLineBeforeCaret.length(); - editor.getDocument().deleteString(startOffset, offset); + String key = customLiveTemplate.computeTemplateKey(callback); + if (key != null) { + int offset = callback.getEditor().getCaretModel().getOffset(); + callback.getEditor().getDocument().deleteString(offset - key.length(), offset); callback.fixInitialEditorState(); - customLiveTemplate.execute(currentLineBeforeCaret, callback, null); + customLiveTemplate.execute(key, callback, null); return true; } } diff --git a/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java b/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java index fad2be78c8bf..446fe956c6d2 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java +++ b/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java @@ -22,6 +22,7 @@ import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.util.Pair; +import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.containers.HashMap; import com.intellij.util.containers.HashSet; @@ -273,18 +274,54 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { return state == MyState.OPERATION || state == MyState.AFTER_NUMBER; } - public boolean isApplicable(@NotNull String key, @NotNull CustomTemplateCallback callback) { - PsiFile file = callback.getFile(); - if (file.getLanguage() instanceof XMLLanguage) { - List tokens = parse(key, callback); - if (tokens != null) { - return check(tokens); + private static String computeKey(Editor editor, int startOffset) { + int offset = editor.getCaretModel().getOffset(); + String s = editor.getDocument().getCharsSequence().subSequence(startOffset, offset).toString(); + int index = 0; + while (index < s.length() && Character.isWhitespace(s.charAt(index))) { + index++; + } + String key = s.substring(index); + int lastWhitespaceIndex = -1; + for (int i = 0; i < key.length(); i++) { + if (Character.isWhitespace(key.charAt(i))) { + lastWhitespaceIndex = i; } } - return false; + if (lastWhitespaceIndex >= 0 && lastWhitespaceIndex < key.length() - 1) { + return key.substring(lastWhitespaceIndex + 1); + } + return key; } - public void execute(@NotNull String key, @NotNull CustomTemplateCallback callback, @Nullable TemplateInvokationListener listener) { + public String computeTemplateKey(@NotNull CustomTemplateCallback callback) { + PsiFile file = callback.getFile(); + if (file.getLanguage() instanceof XMLLanguage) { + Editor editor = callback.getEditor(); + PsiElement element = file.findElementAt(editor.getCaretModel().getOffset() - 1); + int line = editor.getCaretModel().getLogicalPosition().line; + int lineStart = editor.getDocument().getLineStartOffset(line); + int parentStart; + do { + parentStart = element != null ? element.getTextRange().getStartOffset() : 0; + int startOffset = parentStart > lineStart ? parentStart : lineStart; + String key = computeKey(editor, startOffset); + List tokens = parse(key, callback); + if (tokens != null) { + if (check(tokens)) { + return key; + } + } + if (element != null) { + element = element.getParent(); + } + } + while (element != null && parentStart > lineStart); + } + return null; + } + + public void execute(String key, @NotNull CustomTemplateCallback callback, @Nullable TemplateInvokationListener listener) { List tokens = parse(key, callback); assert tokens != null; MyInterpreter interpreter = new MyInterpreter(tokens, callback, MyState.WORD, listener); From 53f478bbbb2edd910f2a3f8664ad8368c6890532 Mon Sep 17 00:00:00 2001 From: Eugene Kudelevsky Date: Fri, 19 Feb 2010 19:11:15 +0300 Subject: [PATCH 74/93] cut autoclosing becase it doesn't work --- .../template/XmlCustomLiveTemplate.java | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java b/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java index 446fe956c6d2..eea9166b5241 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java +++ b/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java @@ -417,7 +417,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { return null; } - private static boolean hasClosingTag(CharSequence text, CharSequence tagName, int offset, int rightBound) { + /*private static boolean hasClosingTag(CharSequence text, CharSequence tagName, int offset, int rightBound) { if (offset + 1 < text.length() && text.charAt(offset) == '<' && text.charAt(offset + 1) == '/') { CharSequence closingTagName = parseTagName(text, offset + 2, rightBound); if (tagName.equals(closingTagName)) { @@ -425,7 +425,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } } return false; - } + }*/ @Nullable private static CharSequence getPrecedingTagName(CharSequence text, int index, int leftBound) { @@ -503,15 +503,15 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { CharSequence text = document.getCharsSequence(); CharSequence tagName = getPrecedingTagName(text, offset, startOfTemplate); if (tagName != null) { - if (!hasClosingTag(text, tagName, offset, endOfTemplate)) { + /*if (!hasClosingTag(text, tagName, offset, endOfTemplate)) { document.insertString(offset, "'); - } + }*/ } else if (offset != endOfTemplate) { tagName = getPrecedingTagName(text, endOfTemplate, startOfTemplate); if (tagName != null) { - fixEndOffset(); - document.insertString(endOfTemplate, "'); + /*fixEndOffset(); + document.insertString(endOfTemplate, "');*/ editor.getCaretModel().moveToOffset(endOfTemplate); } } @@ -535,7 +535,9 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { TemplateInvokationListener listener = new TemplateInvokationListener() { public void finished(boolean inSeparateEvent) { myState = MyState.WORD; - fixEndOffset(); + if (myCallback.getOffset() != myCallback.getEndOfTemplate(key)) { + fixEndOffset(); + } if (sign == '+') { myCallback.gotoEndOfTemplate(key); } @@ -642,7 +644,9 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { TemplateInvokationListener listener = new TemplateInvokationListener() { public void finished(boolean inSeparateEvent) { myState = MyState.WORD; - fixEndOffset(); + if (myCallback.getOffset() != myCallback.getEndOfTemplate(key)) { + fixEndOffset(); + } myCallback.gotoEndOfTemplate(key); if (inSeparateEvent) { if (finalI + 1 < count) { @@ -675,7 +679,9 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { gotoChild(key); MyInterpreter interpreter = new MyInterpreter(myTokens, myCallback, MyState.WORD, new TemplateInvokationListener() { public void finished(boolean inSeparateEvent) { - fixEndOffset(); + if (myCallback.getOffset() != myCallback.getEndOfTemplate(key)) { + fixEndOffset(); + } myCallback.gotoEndOfTemplate(key); if (inSeparateEvent) { invokeTemplateAndProcessTail(templateToken, finalI + 1, count, tailStart); From 1c8bdb2d863a388ed4528783831f2859c607b801 Mon Sep 17 00:00:00 2001 From: "Maxim.Mossienko" Date: Fri, 19 Feb 2010 19:12:36 +0300 Subject: [PATCH 75/93] NPE on null folding builder --- .../lang-api/src/com/intellij/lang/folding/LanguageFolding.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/lang-api/src/com/intellij/lang/folding/LanguageFolding.java b/platform/lang-api/src/com/intellij/lang/folding/LanguageFolding.java index e369efd4a074..232118cf37a4 100644 --- a/platform/lang-api/src/com/intellij/lang/folding/LanguageFolding.java +++ b/platform/lang-api/src/com/intellij/lang/folding/LanguageFolding.java @@ -73,7 +73,7 @@ public class LanguageFolding extends LanguageExtension { return ((FoldingBuilderEx)builder).buildFoldRegions(root, document, quick); } final ASTNode astNode = root.getNode(); - if (astNode == null) { + if (astNode == null || builder == null) { return FoldingDescriptor.EMPTY; } From 005731a118713d56d14dc51bc6b51708edb846f5 Mon Sep 17 00:00:00 2001 From: Eugene Kudelevsky Date: Fri, 19 Feb 2010 20:17:20 +0300 Subject: [PATCH 76/93] do not use hard offset, but use range markers --- .../template/CustomTemplateCallback.java | 44 ++++++++++--------- .../template/XmlCustomLiveTemplate.java | 12 ++--- 2 files changed, 31 insertions(+), 25 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/CustomTemplateCallback.java b/platform/lang-impl/src/com/intellij/codeInsight/template/CustomTemplateCallback.java index dc75c79e4ae0..08906aebd5af 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/CustomTemplateCallback.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/CustomTemplateCallback.java @@ -20,6 +20,7 @@ import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateSettings; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleManager; @@ -40,15 +41,16 @@ public class CustomTemplateCallback { private final Editor myEditor; private final PsiFile myFile; private int myStartOffset; - private int myStartLength; private Project myProject; + private RangeMarker myGlobalMarker; - private final Map myCheckpoints = new HashMap(); + //private final Map myCheckpoints = new HashMap(); + private final Map myCheckpoints = new HashMap(); - private static class MyCheckpoint { - int myFixedLength = -1; - int myFixedOffset; - } + /*private static class MyCheckpoint { + int myFixedLength = null; + RangeMarker myFixedOffset; + }*/ public CustomTemplateCallback(Editor editor, PsiFile file) { myEditor = editor; @@ -59,7 +61,9 @@ public class CustomTemplateCallback { public void fixInitialEditorState() { myStartOffset = myEditor.getCaretModel().getOffset(); - myStartLength = myEditor.getDocument().getCharsSequence().length(); + myGlobalMarker = myEditor.getDocument().createRangeMarker(myStartOffset, myStartOffset); + myGlobalMarker.setGreedyToLeft(true); + myGlobalMarker.setGreedyToRight(true); } public boolean isLiveTemplateApplicable(@NotNull String key) { @@ -128,11 +132,11 @@ public class CustomTemplateCallback { myTemplateManager.startTemplate(myEditor, template, false, predefinedVarValues, new TemplateEditingAdapter() { @Override public void templateFinished(Template template, boolean brokenOff) { - final int lengthAfter = myEditor.getDocument().getCharsSequence().length(); final CodeStyleManager style = CodeStyleManager.getInstance(myProject); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { - style.reformatText(myFile, myStartOffset, myStartOffset + lengthAfter - myStartLength); + //style.reformatText(myFile, myStartOffset, myStartOffset + lengthAfter - myStartLength); + style.reformatText(myFile, myGlobalMarker.getStartOffset(), myGlobalMarker.getEndOffset()); } }); if (brokenOff) return; @@ -150,10 +154,11 @@ public class CustomTemplateCallback { } public void fixStartOfTemplate(@NotNull Object key) { - MyCheckpoint checkpoint = new MyCheckpoint(); - checkpoint.myFixedOffset = myEditor.getCaretModel().getOffset(); - checkpoint.myFixedLength = myEditor.getDocument().getTextLength(); - myCheckpoints.put(key, checkpoint); + int offset = myEditor.getCaretModel().getOffset(); + RangeMarker marker = myEditor.getDocument().createRangeMarker(offset, offset); + marker.setGreedyToLeft(true); + marker.setGreedyToRight(true); + myCheckpoints.put(key, marker); } public void gotoEndOfTemplate(@NotNull Object key) { @@ -161,20 +166,19 @@ public class CustomTemplateCallback { } public int getEndOfTemplate(@NotNull Object key) { - MyCheckpoint checkpoint = myCheckpoints.get(key); - if (checkpoint == null) { + RangeMarker marker = myCheckpoints.get(key); + if (marker == null) { throw new IllegalArgumentException(); } - int length = myEditor.getDocument().getTextLength(); - return checkpoint.myFixedOffset + length - checkpoint.myFixedLength; + return marker.getEndOffset(); } public int getStartOfTemplate(@NotNull Object key) { - MyCheckpoint checkpoint = myCheckpoints.get(key); - if (checkpoint == null) { + RangeMarker marker = myCheckpoints.get(key); + if (marker == null) { throw new IllegalArgumentException(); } - return checkpoint.myFixedOffset; + return marker.getStartOffset(); } private static List getMatchingTemplates(@NotNull String templateKey) { diff --git a/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java b/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java index eea9166b5241..1230ecaf200c 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java +++ b/xml/impl/src/com/intellij/codeInsight/template/XmlCustomLiveTemplate.java @@ -20,6 +20,7 @@ import com.intellij.lang.xml.XMLLanguage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.util.Pair; import com.intellij.psi.PsiElement; @@ -465,7 +466,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { private final CustomTemplateCallback myCallback; private final TemplateInvokationListener myListener; private MyState myState; - private int myEndOffset = -1; + private RangeMarker myEndOffsetMarker = null; private MyInterpreter(List tokens, CustomTemplateCallback callback, @@ -478,15 +479,16 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } private void fixEndOffset() { - if (myEndOffset < 0) { - myEndOffset = myCallback.getOffset(); + if (myEndOffsetMarker == null) { + int offset = myCallback.getOffset(); + myEndOffsetMarker = myCallback.getEditor().getDocument().createRangeMarker(offset, offset); } } private void finish(boolean inSeparateEvent) { Editor editor = myCallback.getEditor(); - if (myEndOffset >= 0) { - editor.getCaretModel().moveToOffset(myEndOffset); + if (myEndOffsetMarker != null) { + editor.getCaretModel().moveToOffset(myEndOffsetMarker.getStartOffset()); } editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); if (myListener != null) { From 696d9b06199b5669ae256d1182a62890c8e6a763 Mon Sep 17 00:00:00 2001 From: Maxim Shafirov Date: Fri, 19 Feb 2010 22:22:17 +0300 Subject: [PATCH 77/93] Ignore Mercurial system folder by default --- .../openapi/fileTypes/impl/FileTypeManagerImpl.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java index 8d9b4420803a..5e254c62d420 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java @@ -54,7 +54,7 @@ import java.util.regex.Pattern; */ public class FileTypeManagerImpl extends FileTypeManagerEx implements NamedJDOMExternalizable, ExportableApplicationComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl"); - private static final int VERSION = 6; + private static final int VERSION = 7; private final Set myDefaultTypes = new THashSet(); private final ArrayList mySpecialFileTypes = new ArrayList(); @@ -521,9 +521,13 @@ public class FileTypeManagerImpl extends FileTypeManagerEx implements NamedJDOME if (savedVersion < 5) { addIgnore("*.hprof"); } - if (savedVersion < VERSION) { + if (savedVersion < 6) { addIgnore("_svn"); } + + if (savedVersion < VERSION) { + addIgnore(".hg"); + } } private void readGlobalMappings(final Element e) { From a387b41859b7651c03080387c340091eed7ea68a Mon Sep 17 00:00:00 2001 From: "Kirill.Safonov" Date: Sat, 20 Feb 2010 15:20:42 +0300 Subject: [PATCH 78/93] AbstractWizardEx moved to the platform --- .../intellij/ide/wizard/AbstractWizardEx.java | 132 ++++++++++++++++++ .../ide/wizard/AbstractWizardStepEx.java | 89 ++++++++++++ .../wizard/CommitStepCancelledException.java | 25 ++++ 3 files changed, 246 insertions(+) create mode 100644 platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardEx.java create mode 100644 platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardStepEx.java create mode 100644 platform/platform-api/src/com/intellij/ide/wizard/CommitStepCancelledException.java diff --git a/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardEx.java b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardEx.java new file mode 100644 index 000000000000..6a569625c1ed --- /dev/null +++ b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardEx.java @@ -0,0 +1,132 @@ +/* + * 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.ide.wizard; + +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.Messages; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AbstractWizardEx extends AbstractWizard { + + private final String myTitle; + private final Map myStepId2Index = new HashMap(); + private final Map myIndex2Step = new HashMap(); + + public AbstractWizardEx(String title, @Nullable Project project, List steps) { + super(title, project); + myTitle = title; + + int index = 0; + for (AbstractWizardStepEx step : steps) { + myStepId2Index.put(step.getStepId(), index); + myIndex2Step.put(index, step); + addStep(step); + + step.addStepListener(new AbstractWizardStepEx.Listener() { + public void stateChanged() { + updateButtons(); + } + + public void doNextAction() { + if (getNextButton().isEnabled()) { + AbstractWizardEx.this.doNextAction(); + } + } + }); + index++; + } + + init(); + } + + protected void doPreviousAction() { + // Commit data of current step + final AbstractWizardStepEx currentStep = mySteps.get(myCurrentStep); + try { + currentStep._commitPrev(); + } + catch (final CommitStepCancelledException e) { + return; + } + catch (CommitStepException e) { + Messages.showErrorDialog(getContentPane(), e.getMessage()); + return; + } + + myCurrentStep = getPreviousStep(myCurrentStep); + updateStep(); + } + + protected void doNextAction() { + // Commit data of current step + final AbstractWizardStepEx currentStep = mySteps.get(myCurrentStep); + try { + currentStep._commit(false); + } + catch (final CommitStepCancelledException e) { + return; + } + catch (CommitStepException e) { + Messages.showErrorDialog(getContentPane(), e.getMessage()); + return; + } + + myCurrentStep = getNextStep(myCurrentStep); + updateStep(); + } + + protected int getNextStep(final int step) { + AbstractWizardStepEx stepObject = myIndex2Step.get(step); + Object nextStepId = stepObject.getNextStepId(); + return myStepId2Index.get(nextStepId); + } + + protected int getPreviousStep(final int step) { + AbstractWizardStepEx stepObject = myIndex2Step.get(step); + Object previousStepId = stepObject.getPreviousStepId(); + return myStepId2Index.get(previousStepId); + } + + protected String getHelpID() { + return null; + } + + protected void updateStep() { + super.updateStep(); + updateButtons(); + setTitle(myTitle + ": " + getCurrentStepObject().getTitle()); + } + + private void updateButtons() { + getNextButton().setEnabled(getCurrentStepObject().isComplete() && getCurrentStepObject().getNextStepId() != null); + getPreviousButton().setEnabled(getCurrentStepObject().getPreviousStepId() != null); + getFinishButton().setEnabled(canFinish()); + } + + protected boolean canFinish() { + for (AbstractWizardStepEx step : mySteps) { + if (!step.isComplete()) { + return false; + } + } + return true; + } +} diff --git a/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardStepEx.java b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardStepEx.java new file mode 100644 index 000000000000..d1fbd812ee25 --- /dev/null +++ b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardStepEx.java @@ -0,0 +1,89 @@ +/* + * 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.ide.wizard; + +import com.intellij.util.EventDispatcher; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; + +public abstract class AbstractWizardStepEx implements Step { + + protected enum CommitType { + Prev, Next, Finish + } + + private String myTitle; + + interface Listener extends StepListener { + void doNextAction(); + } + + private final EventDispatcher myEventDispatcher = EventDispatcher.create(Listener.class); + + public AbstractWizardStepEx(final String title) { + myTitle = title; + } + + public void _init() { + } + + public final void _commitPrev() throws CommitStepException { + commit(CommitType.Prev); + } + public final void _commit(boolean finishChosen) throws CommitStepException { + commit(finishChosen ? CommitType.Finish : CommitType.Next); + } + + public void addStepListener(Listener listener) { + myEventDispatcher.addListener(listener); + } + + protected void setTitle(final String title) { + myTitle = title; + } + + protected void fireStateChanged() { + myEventDispatcher.getMulticaster().stateChanged(); + } + + protected void fireGoNext() { + myEventDispatcher.getMulticaster().doNextAction(); + } + + public Icon getIcon() { + return null; + } + + @NotNull + public abstract Object getStepId(); + + @Nullable + public abstract Object getNextStepId(); + + @Nullable + public abstract Object getPreviousStepId(); + + public abstract boolean isComplete(); + + protected abstract void commit(CommitType commitType) throws CommitStepException; + + public String getTitle() { + return myTitle; + } +} diff --git a/platform/platform-api/src/com/intellij/ide/wizard/CommitStepCancelledException.java b/platform/platform-api/src/com/intellij/ide/wizard/CommitStepCancelledException.java new file mode 100644 index 000000000000..7135a75eabb1 --- /dev/null +++ b/platform/platform-api/src/com/intellij/ide/wizard/CommitStepCancelledException.java @@ -0,0 +1,25 @@ +/* + * 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.ide.wizard; + +import com.intellij.ide.wizard.CommitStepException; + +public class CommitStepCancelledException extends CommitStepException { + public CommitStepCancelledException() { + super("User cancelled"); + } +} From a952a21fc3be206979c9de5a807f686744930fdd Mon Sep 17 00:00:00 2001 From: Maxim Medvedev Date: Sat, 20 Feb 2010 15:41:32 +0300 Subject: [PATCH 79/93] for merge --- .../CompleteReferenceExpression.java | 58 +++++------ .../types/GrCodeReferenceElementImpl.java | 98 ++++++++++--------- 2 files changed, 78 insertions(+), 78 deletions(-) diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java index ac9f2a1f0059..e08f6f536080 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java @@ -26,7 +26,6 @@ import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.util.ArrayUtil; -import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashSet; import org.jetbrains.plugins.groovy.GroovyIcons; @@ -54,10 +53,7 @@ import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; import org.jetbrains.plugins.groovy.lang.resolve.processors.CompletionProcessor; import org.jetbrains.plugins.groovy.lang.resolve.processors.ResolverProcessor; -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; +import java.util.*; /** * @author ven @@ -66,9 +62,9 @@ public class CompleteReferenceExpression { private CompleteReferenceExpression() { } - public static void processVariants(Consumer consumer, GrReferenceExpressionImpl refExpr) { + public static Object[] getVariants(GrReferenceExpressionImpl refExpr) { PsiElement refParent = refExpr.getParent(); - processArgsVariants(consumer, refParent); + List namedArgsVariants = getNamedArgsVariants(refParent); final GrExpression qualifier = refExpr.getQualifierExpression(); Object[] propertyVariants = getVariantsImpl(refExpr, CompletionProcessor.createPropertyCompletionProcessor(refExpr)); @@ -89,31 +85,34 @@ public class CompleteReferenceExpression { if (type instanceof PsiClassType) { PsiClass clazz = ((PsiClassType)type).resolve(); if (clazz != null) { - Set accessedPropertyNames = processPropertyVariants(consumer, refExpr, clazz); + Set accessedPropertyNames = new THashSet(); + List variantList = new ArrayList(getPropertyVariants(refExpr, clazz, accessedPropertyNames)); for (Object variant : propertyVariants) { - if (variant instanceof PsiField && accessedPropertyNames.contains(((PsiField)variant).getName())) { + if (variant instanceof PsiField && accessedPropertyNames.contains(((PsiField) variant).getName())) { continue; } - consumer.consume(variant); + variantList.add(variant); } + + propertyVariants = ArrayUtil.toObjectArray(variantList); } } - else { - for (Object variant : propertyVariants) { - consumer.consume(variant); - } - } + + propertyVariants = + ArrayUtil.mergeArrays(propertyVariants, ArrayUtil.toObjectArray(namedArgsVariants), Object.class); if (refExpr.getKind() == GrReferenceExpressionImpl.Kind.TYPE_OR_PROPERTY) { ResolverProcessor classVariantsCollector = CompletionProcessor.createClassCompletionProcessor(refExpr); final Object[] classVariants = getVariantsImpl(refExpr, classVariantsCollector); - for (Object variant : classVariants) { - consumer.consume(variant); - } + return ArrayUtil.mergeArrays(propertyVariants, classVariants, Object.class); + } + else { + return propertyVariants; } } - private static void processArgsVariants(Consumer consumer, PsiElement refParent) { + private static List getNamedArgsVariants(PsiElement refParent) { + List namedArgsVariants = new LinkedList(); if (refParent instanceof GrArgumentList) { PsiElement refPParent = refParent.getParent(); if (refPParent instanceof GrCall) { @@ -142,18 +141,17 @@ public class CompleteReferenceExpression { if (element instanceof GrMethod) { Set[] parametersArray = ((GrMethod)element).getNamedParametersArray(); for (Set namedParameters : parametersArray) { - for (String parameter : namedParameters) { - consumer.consume(parameter); - } + namedArgsVariants.addAll(namedParameters); } } } } } + return namedArgsVariants; } - private static Set processPropertyVariants(Consumer consumer, GrReferenceExpression refExpr, PsiClass clazz) { - Set accessedPropertyNames=new THashSet(); + private static List getPropertyVariants(GrReferenceExpression refExpr, PsiClass clazz, Set accessedPropertyNames) { + List props = new ArrayList(); final PsiClass eventListener = JavaPsiFacade.getInstance(refExpr.getProject()).findClass("java.util.EventListener", refExpr.getResolveScope()); for (PsiMethod method : clazz.getAllMethods()) { @@ -161,18 +159,17 @@ public class CompleteReferenceExpression { if (GroovyPropertyUtils.isSimplePropertyAccessor(method)) { String prop = GroovyPropertyUtils.getPropertyName(method); accessedPropertyNames.add(prop); - assert prop != null; - consumer.consume(LookupElementBuilder.create(prop).setIcon(GroovyIcons.PROPERTY)); + props.add(LookupElementBuilder.create(prop).setIcon(GroovyIcons.PROPERTY)); } else if (eventListener != null) { - consumeListenerProperties(consumer, method, eventListener); + addListenerProperties(method, eventListener, props); } } } - return accessedPropertyNames; + return props; } - private static void consumeListenerProperties(Consumer consumer, PsiMethod method, PsiClass eventListenerClass) { + private static void addListenerProperties(PsiMethod method, PsiClass eventListenerClass, List result) { if (method.getName().startsWith("add") && method.getParameterList().getParametersCount() == 1) { final PsiParameter parameter = method.getParameterList().getParameters()[0]; final PsiType type = parameter.getType(); @@ -183,7 +180,7 @@ public class CompleteReferenceExpression { final PsiMethod[] listenerMethods = listenerClass.getMethods(); if (InheritanceUtil.isInheritorOrSelf(listenerClass, eventListenerClass, true)) { for (PsiMethod listenerMethod : listenerMethods) { - consumer.consume(LookupElementBuilder.create(listenerMethod.getName()).setIcon(GroovyIcons.PROPERTY)); + result.add(LookupElementBuilder.create(listenerMethod.getName()).setIcon(GroovyIcons.PROPERTY)); } } } @@ -273,7 +270,6 @@ public class CompleteReferenceExpression { if (!PsiUtil.isValidReferenceName(propName)) { propName = "'" + propName + "'"; } - assert propName != null; result.add(LookupElementBuilder.create(propName).setIcon(GroovyIcons.PROPERTY)); } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java index 6b0016536bcb..6c1d4ba60b90 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java @@ -16,13 +16,15 @@ package org.jetbrains.plugins.groovy.lang.psi.impl.types; +import com.intellij.codeInsight.lookup.LookupElement; +import com.intellij.codeInsight.lookup.LookupElementFactory; +import com.intellij.codeInsight.lookup.MutableLookupElement; import com.intellij.lang.ASTNode; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.ResolveCache; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayUtil; -import com.intellij.util.Consumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.completion.GroovyCompletionUtil; @@ -120,10 +122,6 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement } private ReferenceKind getKind(boolean forCompletion) { - if (isClassReferenceForNew()) { - return CLASS_OR_PACKAGE; - } - PsiElement parent = getParent(); if (parent instanceof GrCodeReferenceElement) { ReferenceKind parentKind = ((GrCodeReferenceElementImpl) parent).getKind(forCompletion); @@ -199,7 +197,11 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement @NotNull public Object[] getVariants() { - return ArrayUtil.EMPTY_OBJECT_ARRAY; + if (isClassReferenceForNew()) { + return getVariantsForNewExpression(); + } + + return getVariantsImpl(getKind(true)); } private boolean isClassReferenceForNew() { @@ -208,7 +210,30 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement return parent instanceof GrNewExpression; } - private void processVariantsImpl(ReferenceKind kind, Consumer consumer) { + private Object[] getVariantsForNewExpression() { + final Object[] classVariants = getVariantsImpl(CLASS_OR_PACKAGE); + List result = new ArrayList(); + for (Object variant : classVariants) { + if (variant instanceof PsiClass) { + final PsiClass clazz = (PsiClass) variant; + final MutableLookupElement lookupElement = LookupElementFactory.getInstance().createLookupElement(clazz); + result.add(GroovyCompletionUtil.setTailTypeForConstructor(clazz, lookupElement)); + } else if (variant instanceof LookupElement) { + final LookupElement lookupElement = (LookupElement) variant; + final Object obj = lookupElement.getObject(); + if (obj instanceof PsiClass) { + result.add(GroovyCompletionUtil.setTailTypeForConstructor((PsiClass) obj, lookupElement)); + } else { + result.add(lookupElement); + } + } else { + result.add(variant); + } + } + return ArrayUtil.toObjectArray(result); + } + + private Object[] getVariantsImpl(ReferenceKind kind) { switch (kind) { case STATIC_MEMBER_FQ: { final GrCodeReferenceElement qualifier = getQualifier(); @@ -216,19 +241,21 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement final PsiElement resolve = qualifier.resolve(); if (resolve instanceof PsiClass) { final PsiClass clazz = (PsiClass) resolve; + List result = new ArrayList(); for (PsiField field : clazz.getFields()) { if (field.hasModifierProperty(PsiModifier.STATIC)) { - consumer.consume(field); + result.add(field); } } for (PsiMethod method : clazz.getMethods()) { if (method.hasModifierProperty(PsiModifier.STATIC)) { - consumer.consume(method); + result.add(method); } } - return; + + return result.toArray(new PsiElement[result.size()]); } } } @@ -244,26 +271,17 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement if (parentPackage != null) { final GlobalSearchScope scope = getResolveScope(); if (kind == PACKAGE_FQ) { - for (PsiPackage aPackage : parentPackage.getSubPackages(scope)) { - consumer.consume(aPackage); - } - return; + return parentPackage.getSubPackages(scope); } else { if (kind == CLASS_FQ) { - for (PsiClass aClass : parentPackage.getClasses(scope)) { - consumer.consume(aClass); - } - return; + return parentPackage.getClasses(scope); } else { final PsiPackage[] subpackages = parentPackage.getSubPackages(scope); final PsiClass[] classes = parentPackage.getClasses(scope); - for (PsiPackage aPackage : subpackages) { - consumer.consume(aPackage); - } - for (PsiClass aClass : classes) { - consumer.consume(aClass); - } - return; + PsiElement[] result = new PsiElement[subpackages.length + classes.length]; + System.arraycopy(subpackages, 0, result, 0, subpackages.length); + System.arraycopy(classes, 0, result, subpackages.length, classes.length); + return result; } } } @@ -278,31 +296,21 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement if (qualifierResolved instanceof PsiPackage) { PsiPackage aPackage = (PsiPackage) qualifierResolved; PsiClass[] classes = aPackage.getClasses(getResolveScope()); - - for (PsiClass aClass : classes) { - consumer.consume(aClass); - } - if (kind == CLASS) return; - + if (kind == CLASS) return classes; PsiPackage[] subpackages = aPackage.getSubPackages(); - for (PsiPackage subpackage : subpackages) { - consumer.consume(subpackage); - } + return ArrayUtil.mergeArrays(classes, subpackages, Object.class); } else if (qualifierResolved instanceof PsiClass) { - for (PsiClass aClass : ((PsiClass)qualifierResolved).getInnerClasses()) { - consumer.consume(aClass); - } + return ((PsiClass) qualifierResolved).getInnerClasses(); } } else { - ResolverProcessor classProcessor = CompletionProcessor.createClassCompletionProcessor(this); - ResolveUtil.treeWalkUp(this, classProcessor, false); - - for (Object o : GroovyCompletionUtil.getCompletionVariants(classProcessor.getCandidates())) { - consumer.consume(o); - } + ResolverProcessor processor = CompletionProcessor.createClassCompletionProcessor(this); + ResolveUtil.treeWalkUp(this, processor, false); + return GroovyCompletionUtil.getCompletionVariants(processor.getCandidates()); } } } + + return ArrayUtil.EMPTY_OBJECT_ARRAY; } public boolean isSoft() { @@ -481,8 +489,4 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement return (GroovyResolveResult[])results; } - - public void processVariants(Consumer consumer) { - processVariantsImpl(getKind(true), consumer); - } } From f3c741ff7daa465c8b0e942d9e0141ba7dfd99a4 Mon Sep 17 00:00:00 2001 From: Maxim Medvedev Date: Sat, 20 Feb 2010 17:18:22 +0300 Subject: [PATCH 80/93] Groovy type assignability --- .../CompleteReferenceExpression.java | 58 ++++++----- .../statements/expressions/TypesUtil.java | 14 +-- .../types/GrCodeReferenceElementImpl.java | 98 +++++++++---------- 3 files changed, 83 insertions(+), 87 deletions(-) diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java index e08f6f536080..ac9f2a1f0059 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java @@ -26,6 +26,7 @@ import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.util.ArrayUtil; +import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashSet; import org.jetbrains.plugins.groovy.GroovyIcons; @@ -53,7 +54,10 @@ import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; import org.jetbrains.plugins.groovy.lang.resolve.processors.CompletionProcessor; import org.jetbrains.plugins.groovy.lang.resolve.processors.ResolverProcessor; -import java.util.*; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; /** * @author ven @@ -62,9 +66,9 @@ public class CompleteReferenceExpression { private CompleteReferenceExpression() { } - public static Object[] getVariants(GrReferenceExpressionImpl refExpr) { + public static void processVariants(Consumer consumer, GrReferenceExpressionImpl refExpr) { PsiElement refParent = refExpr.getParent(); - List namedArgsVariants = getNamedArgsVariants(refParent); + processArgsVariants(consumer, refParent); final GrExpression qualifier = refExpr.getQualifierExpression(); Object[] propertyVariants = getVariantsImpl(refExpr, CompletionProcessor.createPropertyCompletionProcessor(refExpr)); @@ -85,34 +89,31 @@ public class CompleteReferenceExpression { if (type instanceof PsiClassType) { PsiClass clazz = ((PsiClassType)type).resolve(); if (clazz != null) { - Set accessedPropertyNames = new THashSet(); - List variantList = new ArrayList(getPropertyVariants(refExpr, clazz, accessedPropertyNames)); + Set accessedPropertyNames = processPropertyVariants(consumer, refExpr, clazz); for (Object variant : propertyVariants) { - if (variant instanceof PsiField && accessedPropertyNames.contains(((PsiField) variant).getName())) { + if (variant instanceof PsiField && accessedPropertyNames.contains(((PsiField)variant).getName())) { continue; } - variantList.add(variant); + consumer.consume(variant); } - - propertyVariants = ArrayUtil.toObjectArray(variantList); } } - - propertyVariants = - ArrayUtil.mergeArrays(propertyVariants, ArrayUtil.toObjectArray(namedArgsVariants), Object.class); + else { + for (Object variant : propertyVariants) { + consumer.consume(variant); + } + } if (refExpr.getKind() == GrReferenceExpressionImpl.Kind.TYPE_OR_PROPERTY) { ResolverProcessor classVariantsCollector = CompletionProcessor.createClassCompletionProcessor(refExpr); final Object[] classVariants = getVariantsImpl(refExpr, classVariantsCollector); - return ArrayUtil.mergeArrays(propertyVariants, classVariants, Object.class); - } - else { - return propertyVariants; + for (Object variant : classVariants) { + consumer.consume(variant); + } } } - private static List getNamedArgsVariants(PsiElement refParent) { - List namedArgsVariants = new LinkedList(); + private static void processArgsVariants(Consumer consumer, PsiElement refParent) { if (refParent instanceof GrArgumentList) { PsiElement refPParent = refParent.getParent(); if (refPParent instanceof GrCall) { @@ -141,17 +142,18 @@ public class CompleteReferenceExpression { if (element instanceof GrMethod) { Set[] parametersArray = ((GrMethod)element).getNamedParametersArray(); for (Set namedParameters : parametersArray) { - namedArgsVariants.addAll(namedParameters); + for (String parameter : namedParameters) { + consumer.consume(parameter); + } } } } } } - return namedArgsVariants; } - private static List getPropertyVariants(GrReferenceExpression refExpr, PsiClass clazz, Set accessedPropertyNames) { - List props = new ArrayList(); + private static Set processPropertyVariants(Consumer consumer, GrReferenceExpression refExpr, PsiClass clazz) { + Set accessedPropertyNames=new THashSet(); final PsiClass eventListener = JavaPsiFacade.getInstance(refExpr.getProject()).findClass("java.util.EventListener", refExpr.getResolveScope()); for (PsiMethod method : clazz.getAllMethods()) { @@ -159,17 +161,18 @@ public class CompleteReferenceExpression { if (GroovyPropertyUtils.isSimplePropertyAccessor(method)) { String prop = GroovyPropertyUtils.getPropertyName(method); accessedPropertyNames.add(prop); - props.add(LookupElementBuilder.create(prop).setIcon(GroovyIcons.PROPERTY)); + assert prop != null; + consumer.consume(LookupElementBuilder.create(prop).setIcon(GroovyIcons.PROPERTY)); } else if (eventListener != null) { - addListenerProperties(method, eventListener, props); + consumeListenerProperties(consumer, method, eventListener); } } } - return props; + return accessedPropertyNames; } - private static void addListenerProperties(PsiMethod method, PsiClass eventListenerClass, List result) { + private static void consumeListenerProperties(Consumer consumer, PsiMethod method, PsiClass eventListenerClass) { if (method.getName().startsWith("add") && method.getParameterList().getParametersCount() == 1) { final PsiParameter parameter = method.getParameterList().getParameters()[0]; final PsiType type = parameter.getType(); @@ -180,7 +183,7 @@ public class CompleteReferenceExpression { final PsiMethod[] listenerMethods = listenerClass.getMethods(); if (InheritanceUtil.isInheritorOrSelf(listenerClass, eventListenerClass, true)) { for (PsiMethod listenerMethod : listenerMethods) { - result.add(LookupElementBuilder.create(listenerMethod.getName()).setIcon(GroovyIcons.PROPERTY)); + consumer.consume(LookupElementBuilder.create(listenerMethod.getName()).setIcon(GroovyIcons.PROPERTY)); } } } @@ -270,6 +273,7 @@ public class CompleteReferenceExpression { if (!PsiUtil.isValidReferenceName(propName)) { propName = "'" + propName + "'"; } + assert propName != null; result.add(LookupElementBuilder.create(propName).setIcon(GroovyIcons.PROPERTY)); } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java index 2255134b45ab..41cf8c4ad425 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java @@ -211,19 +211,15 @@ public class TypesUtil { } public static boolean isAssignable(PsiType lType, PsiType rType, PsiManager manager, GlobalSearchScope scope) { + if (isAssignableByMethodCallConversion(lType, rType, manager, scope)){ + return true; + } //all numeric types are assignable if (isNumericType(lType)) { return isNumericType(rType) || rType.equals(PsiType.NULL); } - if (rType instanceof GrTupleType) { - final GrTupleType tuple = (GrTupleType)rType; - if (tuple.getComponentTypes().length == 0) { - if (lType instanceof PsiArrayType || - InheritanceUtil.isInheritor(lType, JAVA_UTIL_LIST) || - InheritanceUtil.isInheritor(lType, JAVA_UTIL_SET)) { - return true; - } - } + else if (lType.equalsToText(JAVA_LANG_STRING)) { + return true; } rType = boxPrimitiveType(rType, manager, scope); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java index 6c1d4ba60b90..6b0016536bcb 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java @@ -16,15 +16,13 @@ package org.jetbrains.plugins.groovy.lang.psi.impl.types; -import com.intellij.codeInsight.lookup.LookupElement; -import com.intellij.codeInsight.lookup.LookupElementFactory; -import com.intellij.codeInsight.lookup.MutableLookupElement; import com.intellij.lang.ASTNode; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.ResolveCache; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayUtil; +import com.intellij.util.Consumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.completion.GroovyCompletionUtil; @@ -122,6 +120,10 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement } private ReferenceKind getKind(boolean forCompletion) { + if (isClassReferenceForNew()) { + return CLASS_OR_PACKAGE; + } + PsiElement parent = getParent(); if (parent instanceof GrCodeReferenceElement) { ReferenceKind parentKind = ((GrCodeReferenceElementImpl) parent).getKind(forCompletion); @@ -197,11 +199,7 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement @NotNull public Object[] getVariants() { - if (isClassReferenceForNew()) { - return getVariantsForNewExpression(); - } - - return getVariantsImpl(getKind(true)); + return ArrayUtil.EMPTY_OBJECT_ARRAY; } private boolean isClassReferenceForNew() { @@ -210,30 +208,7 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement return parent instanceof GrNewExpression; } - private Object[] getVariantsForNewExpression() { - final Object[] classVariants = getVariantsImpl(CLASS_OR_PACKAGE); - List result = new ArrayList(); - for (Object variant : classVariants) { - if (variant instanceof PsiClass) { - final PsiClass clazz = (PsiClass) variant; - final MutableLookupElement lookupElement = LookupElementFactory.getInstance().createLookupElement(clazz); - result.add(GroovyCompletionUtil.setTailTypeForConstructor(clazz, lookupElement)); - } else if (variant instanceof LookupElement) { - final LookupElement lookupElement = (LookupElement) variant; - final Object obj = lookupElement.getObject(); - if (obj instanceof PsiClass) { - result.add(GroovyCompletionUtil.setTailTypeForConstructor((PsiClass) obj, lookupElement)); - } else { - result.add(lookupElement); - } - } else { - result.add(variant); - } - } - return ArrayUtil.toObjectArray(result); - } - - private Object[] getVariantsImpl(ReferenceKind kind) { + private void processVariantsImpl(ReferenceKind kind, Consumer consumer) { switch (kind) { case STATIC_MEMBER_FQ: { final GrCodeReferenceElement qualifier = getQualifier(); @@ -241,21 +216,19 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement final PsiElement resolve = qualifier.resolve(); if (resolve instanceof PsiClass) { final PsiClass clazz = (PsiClass) resolve; - List result = new ArrayList(); for (PsiField field : clazz.getFields()) { if (field.hasModifierProperty(PsiModifier.STATIC)) { - result.add(field); + consumer.consume(field); } } for (PsiMethod method : clazz.getMethods()) { if (method.hasModifierProperty(PsiModifier.STATIC)) { - result.add(method); + consumer.consume(method); } } - - return result.toArray(new PsiElement[result.size()]); + return; } } } @@ -271,17 +244,26 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement if (parentPackage != null) { final GlobalSearchScope scope = getResolveScope(); if (kind == PACKAGE_FQ) { - return parentPackage.getSubPackages(scope); + for (PsiPackage aPackage : parentPackage.getSubPackages(scope)) { + consumer.consume(aPackage); + } + return; } else { if (kind == CLASS_FQ) { - return parentPackage.getClasses(scope); + for (PsiClass aClass : parentPackage.getClasses(scope)) { + consumer.consume(aClass); + } + return; } else { final PsiPackage[] subpackages = parentPackage.getSubPackages(scope); final PsiClass[] classes = parentPackage.getClasses(scope); - PsiElement[] result = new PsiElement[subpackages.length + classes.length]; - System.arraycopy(subpackages, 0, result, 0, subpackages.length); - System.arraycopy(classes, 0, result, subpackages.length, classes.length); - return result; + for (PsiPackage aPackage : subpackages) { + consumer.consume(aPackage); + } + for (PsiClass aClass : classes) { + consumer.consume(aClass); + } + return; } } } @@ -296,21 +278,31 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement if (qualifierResolved instanceof PsiPackage) { PsiPackage aPackage = (PsiPackage) qualifierResolved; PsiClass[] classes = aPackage.getClasses(getResolveScope()); - if (kind == CLASS) return classes; + + for (PsiClass aClass : classes) { + consumer.consume(aClass); + } + if (kind == CLASS) return; + PsiPackage[] subpackages = aPackage.getSubPackages(); - return ArrayUtil.mergeArrays(classes, subpackages, Object.class); + for (PsiPackage subpackage : subpackages) { + consumer.consume(subpackage); + } } else if (qualifierResolved instanceof PsiClass) { - return ((PsiClass) qualifierResolved).getInnerClasses(); + for (PsiClass aClass : ((PsiClass)qualifierResolved).getInnerClasses()) { + consumer.consume(aClass); + } } } else { - ResolverProcessor processor = CompletionProcessor.createClassCompletionProcessor(this); - ResolveUtil.treeWalkUp(this, processor, false); - return GroovyCompletionUtil.getCompletionVariants(processor.getCandidates()); + ResolverProcessor classProcessor = CompletionProcessor.createClassCompletionProcessor(this); + ResolveUtil.treeWalkUp(this, classProcessor, false); + + for (Object o : GroovyCompletionUtil.getCompletionVariants(classProcessor.getCandidates())) { + consumer.consume(o); + } } } } - - return ArrayUtil.EMPTY_OBJECT_ARRAY; } public boolean isSoft() { @@ -489,4 +481,8 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement return (GroovyResolveResult[])results; } + + public void processVariants(Consumer consumer) { + processVariantsImpl(getKind(true), consumer); + } } From 6a80f2f8d9e5795f60a31982462c79aeab885c32 Mon Sep 17 00:00:00 2001 From: Dmitry Jemerov Date: Sat, 20 Feb 2010 19:33:05 +0300 Subject: [PATCH 81/93] PsiFileSystemItem implements NavigatablePsiElement --- platform/lang-api/src/com/intellij/psi/PsiFileSystemItem.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/platform/lang-api/src/com/intellij/psi/PsiFileSystemItem.java b/platform/lang-api/src/com/intellij/psi/PsiFileSystemItem.java index 209579b894cc..a10628d91bc3 100644 --- a/platform/lang-api/src/com/intellij/psi/PsiFileSystemItem.java +++ b/platform/lang-api/src/com/intellij/psi/PsiFileSystemItem.java @@ -15,7 +15,6 @@ */ package com.intellij.psi; -import com.intellij.navigation.NavigationItem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.search.PsiElementProcessor; import org.jetbrains.annotations.NonNls; @@ -27,7 +26,7 @@ import org.jetbrains.annotations.Nullable; * * @author ven */ -public interface PsiFileSystemItem extends PsiCheckedRenameElement, NavigationItem { +public interface PsiFileSystemItem extends PsiCheckedRenameElement, NavigatablePsiElement { boolean isDirectory(); @Nullable From 137f02a92791fff9f027c1ebf632ad12fb232fec Mon Sep 17 00:00:00 2001 From: Alexey Gopachenko Date: Sat, 20 Feb 2010 17:32:33 +0300 Subject: [PATCH 82/93] WI memory tweaked to handle x64 JVMs --- .../IntelliLang/src/LanguageInjectionConfiguration.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/plugins/IntelliLang/src/LanguageInjectionConfiguration.xml b/plugins/IntelliLang/src/LanguageInjectionConfiguration.xml index 025d4d20a86b..d23e02514c84 100644 --- a/plugins/IntelliLang/src/LanguageInjectionConfiguration.xml +++ b/plugins/IntelliLang/src/LanguageInjectionConfiguration.xml @@ -417,6 +417,14 @@ <<< HTML + + "<HTML>" + + + + "SELECT " + + <<< JS From b41289bb8775f096eff06fd325216e52ccd80c80 Mon Sep 17 00:00:00 2001 From: Alexey Gopachenko Date: Sun, 21 Feb 2010 10:37:13 +0300 Subject: [PATCH 83/93] cleanup testFramework dependencies --- platform/lvcs-impl/lvcs-impl.iml | 5 ++++- platform/platform-impl/platform-impl.iml | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/platform/lvcs-impl/lvcs-impl.iml b/platform/lvcs-impl/lvcs-impl.iml index 5d3d67900b2a..4976107b6041 100644 --- a/platform/lvcs-impl/lvcs-impl.iml +++ b/platform/lvcs-impl/lvcs-impl.iml @@ -12,9 +12,12 @@ - + + + + diff --git a/platform/platform-impl/platform-impl.iml b/platform/platform-impl/platform-impl.iml index 3f163f7e753d..a67411bd15c7 100644 --- a/platform/platform-impl/platform-impl.iml +++ b/platform/platform-impl/platform-impl.iml @@ -23,7 +23,7 @@ - + From 756b9b41eb1d3c171c9852100d53f25094265895 Mon Sep 17 00:00:00 2001 From: Alexey Gopachenko Date: Sun, 21 Feb 2010 10:58:45 +0300 Subject: [PATCH 84/93] deps --- platform/platform-impl/platform-impl.iml | 1 + 1 file changed, 1 insertion(+) diff --git a/platform/platform-impl/platform-impl.iml b/platform/platform-impl/platform-impl.iml index a67411bd15c7..dd72340ad855 100644 --- a/platform/platform-impl/platform-impl.iml +++ b/platform/platform-impl/platform-impl.iml @@ -24,6 +24,7 @@ + From 80ea3d052a019d119156832aaaf436e08e461754 Mon Sep 17 00:00:00 2001 From: Dmitry Jemerov Date: Sun, 21 Feb 2010 21:18:21 +0300 Subject: [PATCH 85/93] support for Python named groups in regexp lexer and parser --- .../lang/regexp/RegExpBraceMatcher.java | 1 + .../lang/regexp/RegExpLanguageHost.java | 1 + .../org/intellij/lang/regexp/RegExpTT.java | 6 +- .../org/intellij/lang/regexp/_RegExLexer.java | 419 +++++++++--------- .../intellij/lang/regexp/psi/RegExpGroup.java | 2 + .../lang/regexp/psi/impl/RegExpGroupImpl.java | 4 + .../intellij/lang/regexp/regexp-lexer.flex | 1 + .../regexp/validation/RegExpAnnotator.java | 9 +- 8 files changed, 234 insertions(+), 209 deletions(-) diff --git a/RegExpSupport/src/org/intellij/lang/regexp/RegExpBraceMatcher.java b/RegExpSupport/src/org/intellij/lang/regexp/RegExpBraceMatcher.java index e51b63fa22ff..387c548c4d21 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/RegExpBraceMatcher.java +++ b/RegExpSupport/src/org/intellij/lang/regexp/RegExpBraceMatcher.java @@ -28,6 +28,7 @@ public class RegExpBraceMatcher implements PairedBraceMatcher { new BracePair(RegExpTT.SET_OPTIONS, RegExpTT.GROUP_END, true), new BracePair(RegExpTT.NON_CAPT_GROUP, RegExpTT.GROUP_END, true), new BracePair(RegExpTT.POS_LOOKAHEAD, RegExpTT.GROUP_END, true), new BracePair(RegExpTT.NEG_LOOKAHEAD, RegExpTT.GROUP_END, true), new BracePair(RegExpTT.POS_LOOKBEHIND, RegExpTT.GROUP_END, true), new BracePair(RegExpTT.NEG_LOOKBEHIND, RegExpTT.GROUP_END, true), + new BracePair(RegExpTT.PYTHON_NAMED_GROUP, RegExpTT.GROUP_END, true), new BracePair(RegExpTT.CLASS_BEGIN, RegExpTT.CLASS_END, false), new BracePair(RegExpTT.LBRACE, RegExpTT.RBRACE, false), new BracePair(RegExpTT.QUOTE_BEGIN, RegExpTT.QUOTE_END, false),}; } diff --git a/RegExpSupport/src/org/intellij/lang/regexp/RegExpLanguageHost.java b/RegExpSupport/src/org/intellij/lang/regexp/RegExpLanguageHost.java index f1d344564c22..a3251e6d1127 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/RegExpLanguageHost.java +++ b/RegExpSupport/src/org/intellij/lang/regexp/RegExpLanguageHost.java @@ -22,4 +22,5 @@ public interface RegExpLanguageHost { boolean characterNeedsEscaping(char c); boolean supportsPerl5EmbeddedComments(); boolean supportsPossessiveQuantifiers(); + boolean supportsPythonNamedGroups(); } diff --git a/RegExpSupport/src/org/intellij/lang/regexp/RegExpTT.java b/RegExpSupport/src/org/intellij/lang/regexp/RegExpTT.java index 59eafbca65d7..54f03f7bf886 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/RegExpTT.java +++ b/RegExpSupport/src/org/intellij/lang/regexp/RegExpTT.java @@ -97,6 +97,9 @@ public interface RegExpTT { IElementType OPTIONS_ON = new RegExpElementType("OPTIONS_ON"); IElementType OPTIONS_OFF = new RegExpElementType("OPTIONS_OFF"); + // (?P... + IElementType PYTHON_NAMED_GROUP = new RegExpElementType("PYTHON_NAMED_GROUP"); + TokenSet KEYWORDS = TokenSet.create(DOT, STAR, QUEST, PLUS); TokenSet CHARACTERS = TokenSet.create(CHARACTER, @@ -123,7 +126,8 @@ public interface RegExpTT { POS_LOOKAHEAD, NEG_LOOKAHEAD, POS_LOOKBEHIND, - NEG_LOOKBEHIND); + NEG_LOOKBEHIND, + PYTHON_NAMED_GROUP); TokenSet BOUNDARIES = TokenSet.create(BOUNDARY, CARET, DOLLAR); } diff --git a/RegExpSupport/src/org/intellij/lang/regexp/_RegExLexer.java b/RegExpSupport/src/org/intellij/lang/regexp/_RegExLexer.java index 8de1c26644c5..a4126fd94117 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/_RegExLexer.java +++ b/RegExpSupport/src/org/intellij/lang/regexp/_RegExLexer.java @@ -1,21 +1,20 @@ -/* The following code was generated by JFlex 1.4.1 on 18.12.09 20:27 */ +/* The following code was generated by JFlex 1.4.3 on 21.02.10 20:59 */ /* It's an automatically generated code. Do not modify it. */ package org.intellij.lang.regexp; import com.intellij.lexer.FlexLexer; -import com.intellij.psi.StringEscapesTokenTypes; import com.intellij.psi.tree.IElementType; - import java.util.LinkedList; +import com.intellij.psi.StringEscapesTokenTypes; // IDEADEV-11055 @SuppressWarnings({ "ALL", "SameParameterValue", "WeakerAccess", "SameReturnValue", "RedundantThrows", "UnusedDeclaration", "UnusedDeclaration" }) /** * This class is a scanner generated by - * JFlex 1.4.1 - * on 18.12.09 20:27 from the specification file + * JFlex 1.4.3 + * on 21.02.10 20:59 from the specification file * C:/JetBrains/IDEA/tools/lexer/../../community/RegExpSupport/src/org/intellij/lang/regexp/regexp-lexer.flex */ class _RegExLexer implements FlexLexer { @@ -23,86 +22,96 @@ class _RegExLexer implements FlexLexer { private static final int ZZ_BUFFERSIZE = 16384; /** lexical states */ - public static final int CLASS1 = 3; - public static final int PROP = 5; - public static final int EMBRACED = 2; - public static final int QUOTED = 1; + public static final int CLASS1 = 6; + public static final int PROP = 10; + public static final int EMBRACED = 4; + public static final int QUOTED = 2; public static final int YYINITIAL = 0; - public static final int COMMENT = 7; - public static final int OPTIONS = 6; - public static final int CLASS2 = 4; + public static final int COMMENT = 14; + public static final int OPTIONS = 12; + public static final int CLASS2 = 8; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7 + }; /** * Translates characters to character classes */ private static final String ZZ_CMAP_PACKED = - "\10\0\2\51\1\13\1\0\1\51\1\60\22\0\1\44\1\55\1\0"+ - "\1\57\1\15\1\0\1\50\1\0\1\4\1\5\1\17\1\20\1\47"+ - "\1\42\1\3\1\0\1\2\7\41\2\1\1\52\1\0\1\56\1\54"+ - "\1\53\1\16\1\0\1\24\1\24\1\30\1\27\1\36\1\34\1\25"+ - "\1\43\1\32\6\43\1\33\1\35\1\43\1\26\3\43\1\26\1\26"+ - "\1\43\1\25\1\10\1\12\1\11\1\14\1\45\1\0\1\23\1\24"+ - "\1\31\1\27\1\23\1\23\2\43\1\32\4\43\1\22\1\43\1\33"+ - "\1\43\1\22\1\26\1\22\1\40\1\43\1\26\1\37\1\43\1\25"+ - "\1\6\1\21\1\7\54\0\1\43\12\0\1\43\4\0\1\43\5\0"+ - "\27\43\1\0\37\43\1\0\u013f\43\31\0\162\43\4\0\14\43\16\0"+ - "\5\43\11\0\1\43\213\0\1\43\13\0\1\43\1\0\3\43\1\0"+ - "\1\43\1\0\24\43\1\0\54\43\1\0\46\43\1\0\5\43\4\0"+ - "\202\43\10\0\105\43\1\0\46\43\2\0\2\43\6\0\20\43\41\0"+ - "\46\43\2\0\1\43\7\0\47\43\110\0\33\43\5\0\3\43\56\0"+ - "\32\43\5\0\13\43\25\0\12\46\4\0\2\43\1\0\143\43\1\0"+ - "\1\43\17\0\2\43\7\0\2\43\12\46\3\43\2\0\1\43\20\0"+ - "\1\43\1\0\36\43\35\0\3\43\60\0\46\43\13\0\1\43\u0152\0"+ - "\66\43\3\0\1\43\22\0\1\43\7\0\12\43\4\0\12\46\25\0"+ - "\10\43\2\0\2\43\2\0\26\43\1\0\7\43\1\0\1\43\3\0"+ - "\4\43\3\0\1\43\36\0\2\43\1\0\3\43\4\0\12\46\2\43"+ - "\23\0\6\43\4\0\2\43\2\0\26\43\1\0\7\43\1\0\2\43"+ - "\1\0\2\43\1\0\2\43\37\0\4\43\1\0\1\43\7\0\12\46"+ - "\2\0\3\43\20\0\11\43\1\0\3\43\1\0\26\43\1\0\7\43"+ - "\1\0\2\43\1\0\5\43\3\0\1\43\22\0\1\43\17\0\2\43"+ - "\4\0\12\46\25\0\10\43\2\0\2\43\2\0\26\43\1\0\7\43"+ - "\1\0\2\43\1\0\5\43\3\0\1\43\36\0\2\43\1\0\3\43"+ - "\4\0\12\46\1\0\1\43\21\0\1\43\1\0\6\43\3\0\3\43"+ - "\1\0\4\43\3\0\2\43\1\0\1\43\1\0\2\43\3\0\2\43"+ - "\3\0\3\43\3\0\10\43\1\0\3\43\55\0\11\46\25\0\10\43"+ - "\1\0\3\43\1\0\27\43\1\0\12\43\1\0\5\43\46\0\2\43"+ - "\4\0\12\46\25\0\10\43\1\0\3\43\1\0\27\43\1\0\12\43"+ - "\1\0\5\43\3\0\1\43\40\0\1\43\1\0\2\43\4\0\12\46"+ - "\25\0\10\43\1\0\3\43\1\0\27\43\1\0\20\43\46\0\2\43"+ - "\4\0\12\46\25\0\22\43\3\0\30\43\1\0\11\43\1\0\1\43"+ - "\2\0\7\43\72\0\60\43\1\0\2\43\14\0\7\43\11\0\12\46"+ - "\47\0\2\43\1\0\1\43\2\0\2\43\1\0\1\43\2\0\1\43"+ - "\6\0\4\43\1\0\7\43\1\0\3\43\1\0\1\43\1\0\1\43"+ - "\2\0\2\43\1\0\4\43\1\0\2\43\11\0\1\43\2\0\5\43"+ - "\1\0\1\43\11\0\12\46\2\0\2\43\42\0\1\43\37\0\12\46"+ - "\26\0\10\43\1\0\42\43\35\0\4\43\164\0\42\43\1\0\5\43"+ - "\1\0\2\43\25\0\12\46\6\0\6\43\112\0\46\43\12\0\51\43"+ - "\7\0\132\43\5\0\104\43\5\0\122\43\6\0\7\43\1\0\77\43"+ - "\1\0\1\43\1\0\4\43\2\0\7\43\1\0\1\43\1\0\4\43"+ - "\2\0\47\43\1\0\1\43\1\0\4\43\2\0\37\43\1\0\1\43"+ - "\1\0\4\43\2\0\7\43\1\0\1\43\1\0\4\43\2\0\7\43"+ - "\1\0\7\43\1\0\27\43\1\0\37\43\1\0\1\43\1\0\4\43"+ - "\2\0\7\43\1\0\47\43\1\0\23\43\16\0\11\46\56\0\125\43"+ - "\14\0\u026c\43\2\0\10\43\12\0\32\43\5\0\113\43\25\0\15\43"+ - "\1\0\4\43\16\0\22\43\16\0\22\43\16\0\15\43\1\0\3\43"+ - "\17\0\64\43\43\0\1\43\4\0\1\43\3\0\12\46\46\0\12\46"+ - "\6\0\130\43\10\0\51\43\127\0\35\43\51\0\12\46\36\43\2\0"+ - "\5\43\u038b\0\154\43\224\0\234\43\4\0\132\43\6\0\26\43\2\0"+ - "\6\43\2\0\46\43\2\0\6\43\2\0\10\43\1\0\1\43\1\0"+ - "\1\43\1\0\1\43\1\0\37\43\2\0\65\43\1\0\7\43\1\0"+ - "\1\43\3\0\3\43\1\0\7\43\3\0\4\43\2\0\6\43\4\0"+ - "\15\43\5\0\3\43\1\0\7\43\164\0\1\43\15\0\1\43\202\0"+ - "\1\43\4\0\1\43\2\0\12\43\1\0\1\43\3\0\5\43\6\0"+ - "\1\43\1\0\1\43\1\0\1\43\1\0\4\43\1\0\3\43\1\0"+ - "\7\43\3\0\3\43\5\0\5\43\u0ebb\0\2\43\52\0\5\43\5\0"+ - "\2\43\4\0\126\43\6\0\3\43\1\0\132\43\1\0\4\43\5\0"+ - "\50\43\4\0\136\43\21\0\30\43\70\0\20\43\u0200\0\u19b6\43\112\0"+ - "\u51a6\43\132\0\u048d\43\u0773\0\u2ba4\43\u215c\0\u012e\43\2\0\73\43\225\0"+ - "\7\43\14\0\5\43\5\0\1\43\1\0\12\43\1\0\15\43\1\0"+ - "\5\43\1\0\1\43\1\0\2\43\1\0\2\43\1\0\154\43\41\0"+ - "\u016b\43\22\0\100\43\2\0\66\43\50\0\14\43\164\0\5\43\1\0"+ - "\207\43\23\0\12\46\7\0\32\43\6\0\32\43\13\0\131\43\3\0"+ - "\6\43\2\0\6\43\2\0\6\43\2\0\3\43\43\0"; + "\10\0\2\52\1\13\1\0\1\52\1\61\22\0\1\45\1\56\1\0"+ + "\1\60\1\15\1\0\1\51\1\0\1\4\1\5\1\17\1\20\1\50"+ + "\1\43\1\3\1\0\1\2\7\42\2\1\1\53\1\0\1\57\1\55"+ + "\1\54\1\16\1\0\1\24\1\24\1\30\1\27\1\37\1\35\1\25"+ + "\1\44\1\32\6\44\1\34\1\36\1\44\1\26\3\44\1\26\1\26"+ + "\1\44\1\25\1\10\1\12\1\11\1\14\1\46\1\0\1\23\1\24"+ + "\1\31\1\27\1\23\1\23\2\44\1\32\4\44\1\22\1\44\1\33"+ + "\1\44\1\22\1\26\1\22\1\41\1\44\1\26\1\40\1\44\1\25"+ + "\1\6\1\21\1\7\54\0\1\44\12\0\1\44\4\0\1\44\5\0"+ + "\27\44\1\0\37\44\1\0\u013f\44\31\0\162\44\4\0\14\44\16\0"+ + "\5\44\11\0\1\44\213\0\1\44\13\0\1\44\1\0\3\44\1\0"+ + "\1\44\1\0\24\44\1\0\54\44\1\0\46\44\1\0\5\44\4\0"+ + "\202\44\10\0\105\44\1\0\46\44\2\0\2\44\6\0\20\44\41\0"+ + "\46\44\2\0\1\44\7\0\47\44\110\0\33\44\5\0\3\44\56\0"+ + "\32\44\5\0\13\44\25\0\12\47\4\0\2\44\1\0\143\44\1\0"+ + "\1\44\17\0\2\44\7\0\2\44\12\47\3\44\2\0\1\44\20\0"+ + "\1\44\1\0\36\44\35\0\3\44\60\0\46\44\13\0\1\44\u0152\0"+ + "\66\44\3\0\1\44\22\0\1\44\7\0\12\44\4\0\12\47\25\0"+ + "\10\44\2\0\2\44\2\0\26\44\1\0\7\44\1\0\1\44\3\0"+ + "\4\44\3\0\1\44\36\0\2\44\1\0\3\44\4\0\12\47\2\44"+ + "\23\0\6\44\4\0\2\44\2\0\26\44\1\0\7\44\1\0\2\44"+ + "\1\0\2\44\1\0\2\44\37\0\4\44\1\0\1\44\7\0\12\47"+ + "\2\0\3\44\20\0\11\44\1\0\3\44\1\0\26\44\1\0\7\44"+ + "\1\0\2\44\1\0\5\44\3\0\1\44\22\0\1\44\17\0\2\44"+ + "\4\0\12\47\25\0\10\44\2\0\2\44\2\0\26\44\1\0\7\44"+ + "\1\0\2\44\1\0\5\44\3\0\1\44\36\0\2\44\1\0\3\44"+ + "\4\0\12\47\1\0\1\44\21\0\1\44\1\0\6\44\3\0\3\44"+ + "\1\0\4\44\3\0\2\44\1\0\1\44\1\0\2\44\3\0\2\44"+ + "\3\0\3\44\3\0\10\44\1\0\3\44\55\0\11\47\25\0\10\44"+ + "\1\0\3\44\1\0\27\44\1\0\12\44\1\0\5\44\46\0\2\44"+ + "\4\0\12\47\25\0\10\44\1\0\3\44\1\0\27\44\1\0\12\44"+ + "\1\0\5\44\3\0\1\44\40\0\1\44\1\0\2\44\4\0\12\47"+ + "\25\0\10\44\1\0\3\44\1\0\27\44\1\0\20\44\46\0\2\44"+ + "\4\0\12\47\25\0\22\44\3\0\30\44\1\0\11\44\1\0\1\44"+ + "\2\0\7\44\72\0\60\44\1\0\2\44\14\0\7\44\11\0\12\47"+ + "\47\0\2\44\1\0\1\44\2\0\2\44\1\0\1\44\2\0\1\44"+ + "\6\0\4\44\1\0\7\44\1\0\3\44\1\0\1\44\1\0\1\44"+ + "\2\0\2\44\1\0\4\44\1\0\2\44\11\0\1\44\2\0\5\44"+ + "\1\0\1\44\11\0\12\47\2\0\2\44\42\0\1\44\37\0\12\47"+ + "\26\0\10\44\1\0\42\44\35\0\4\44\164\0\42\44\1\0\5\44"+ + "\1\0\2\44\25\0\12\47\6\0\6\44\112\0\46\44\12\0\51\44"+ + "\7\0\132\44\5\0\104\44\5\0\122\44\6\0\7\44\1\0\77\44"+ + "\1\0\1\44\1\0\4\44\2\0\7\44\1\0\1\44\1\0\4\44"+ + "\2\0\47\44\1\0\1\44\1\0\4\44\2\0\37\44\1\0\1\44"+ + "\1\0\4\44\2\0\7\44\1\0\1\44\1\0\4\44\2\0\7\44"+ + "\1\0\7\44\1\0\27\44\1\0\37\44\1\0\1\44\1\0\4\44"+ + "\2\0\7\44\1\0\47\44\1\0\23\44\16\0\11\47\56\0\125\44"+ + "\14\0\u026c\44\2\0\10\44\12\0\32\44\5\0\113\44\25\0\15\44"+ + "\1\0\4\44\16\0\22\44\16\0\22\44\16\0\15\44\1\0\3\44"+ + "\17\0\64\44\43\0\1\44\4\0\1\44\3\0\12\47\46\0\12\47"+ + "\6\0\130\44\10\0\51\44\127\0\35\44\51\0\12\47\36\44\2\0"+ + "\5\44\u038b\0\154\44\224\0\234\44\4\0\132\44\6\0\26\44\2\0"+ + "\6\44\2\0\46\44\2\0\6\44\2\0\10\44\1\0\1\44\1\0"+ + "\1\44\1\0\1\44\1\0\37\44\2\0\65\44\1\0\7\44\1\0"+ + "\1\44\3\0\3\44\1\0\7\44\3\0\4\44\2\0\6\44\4\0"+ + "\15\44\5\0\3\44\1\0\7\44\164\0\1\44\15\0\1\44\202\0"+ + "\1\44\4\0\1\44\2\0\12\44\1\0\1\44\3\0\5\44\6\0"+ + "\1\44\1\0\1\44\1\0\1\44\1\0\4\44\1\0\3\44\1\0"+ + "\7\44\3\0\3\44\5\0\5\44\u0ebb\0\2\44\52\0\5\44\5\0"+ + "\2\44\4\0\126\44\6\0\3\44\1\0\132\44\1\0\4\44\5\0"+ + "\50\44\4\0\136\44\21\0\30\44\70\0\20\44\u0200\0\u19b6\44\112\0"+ + "\u51a6\44\132\0\u048d\44\u0773\0\u2ba4\44\u215c\0\u012e\44\2\0\73\44\225\0"+ + "\7\44\14\0\5\44\5\0\1\44\1\0\12\44\1\0\15\44\1\0"+ + "\5\44\1\0\1\44\1\0\2\44\1\0\2\44\1\0\154\44\41\0"+ + "\u016b\44\22\0\100\44\2\0\66\44\50\0\14\44\164\0\5\44\1\0"+ + "\207\44\23\0\12\47\7\0\32\44\6\0\32\44\13\0\131\44\3\0"+ + "\6\44\2\0\6\44\2\0\6\44\2\0\3\44\43\0"; /** * Translates characters to character classes @@ -122,12 +131,12 @@ class _RegExLexer implements FlexLexer { "\1\36\1\35\1\37\1\40\1\1\1\41\1\42\1\2"+ "\1\43\1\44\1\45\1\46\1\47\1\50\1\51\1\52"+ "\1\53\1\54\2\55\1\56\1\11\1\57\1\60\1\61"+ - "\1\62\1\63\1\64\1\65\1\66\2\0\1\67\1\70"+ - "\2\60\2\61\1\71\1\72\1\0\1\67\1\60\1\73"+ - "\2\61\1\74\1\67\3\61\1\75"; + "\1\62\1\63\1\0\1\64\1\65\1\66\2\0\1\67"+ + "\1\70\2\60\2\61\1\0\1\71\1\72\1\0\1\67"+ + "\1\60\1\73\2\61\1\74\1\75\1\67\3\61\1\76"; private static int [] zzUnpackAction() { - int [] result = new int[89]; + int [] result = new int[92]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; @@ -152,21 +161,21 @@ class _RegExLexer implements FlexLexer { private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = - "\0\0\0\61\0\142\0\223\0\304\0\365\0\u0126\0\u0157"+ - "\0\u0188\0\u0188\0\u01b9\0\u0188\0\u0188\0\u01ea\0\u021b\0\u0188"+ - "\0\u0188\0\u0188\0\u0188\0\u0188\0\u0188\0\u0188\0\u0188\0\u0188"+ - "\0\u0188\0\u024c\0\u0188\0\u027d\0\u0188\0\u02ae\0\u0188\0\u0188"+ - "\0\u0188\0\u0188\0\u0188\0\u02df\0\u0188\0\u0188\0\u01ea\0\u0188"+ - "\0\u0188\0\u0310\0\u0341\0\u0188\0\u0188\0\u0372\0\u0188\0\u0188"+ - "\0\u03a3\0\u03d4\0\u0188\0\u0188\0\u0188\0\u0188\0\u0188\0\u0188"+ - "\0\u0405\0\u0188\0\u0188\0\u0188\0\u0436\0\u0467\0\u0188\0\u0188"+ - "\0\u0188\0\u0188\0\u0188\0\u0498\0\u04c9\0\u04fa\0\u0188\0\u052b"+ - "\0\u055c\0\u058d\0\u05be\0\u0188\0\u0188\0\u05ef\0\u0620\0\u0188"+ - "\0\u0188\0\u0651\0\u0682\0\u0188\0\u0188\0\u06b3\0\u06e4\0\u0188"+ - "\0\u0188"; + "\0\0\0\62\0\144\0\226\0\310\0\372\0\u012c\0\u015e"+ + "\0\u0190\0\u0190\0\u01c2\0\u0190\0\u0190\0\u01f4\0\u0226\0\u0190"+ + "\0\u0190\0\u0190\0\u0190\0\u0190\0\u0190\0\u0190\0\u0190\0\u0190"+ + "\0\u0190\0\u0258\0\u0190\0\u028a\0\u0190\0\u02bc\0\u0190\0\u0190"+ + "\0\u0190\0\u0190\0\u0190\0\u02ee\0\u0190\0\u0190\0\u01f4\0\u0190"+ + "\0\u0190\0\u0320\0\u0352\0\u0190\0\u0190\0\u0384\0\u0190\0\u0190"+ + "\0\u03b6\0\u03e8\0\u0190\0\u0190\0\u0190\0\u0190\0\u0190\0\u0190"+ + "\0\u041a\0\u0190\0\u0190\0\u0190\0\u044c\0\u047e\0\u0190\0\u0190"+ + "\0\u04b0\0\u0190\0\u0190\0\u0190\0\u04e2\0\u0514\0\u0546\0\u0190"+ + "\0\u0578\0\u05aa\0\u05dc\0\u060e\0\u0640\0\u0190\0\u0190\0\u0672"+ + "\0\u06a4\0\u0190\0\u0190\0\u06d6\0\u0708\0\u0190\0\u0190\0\u0190"+ + "\0\u073a\0\u076c\0\u0190\0\u0190"; private static int [] zzUnpackRowMap() { - int [] result = new int[89]; + int [] result = new int[92]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; @@ -191,40 +200,41 @@ class _RegExLexer implements FlexLexer { private static final String ZZ_TRANS_PACKED_0 = "\3\11\1\12\1\13\1\14\1\15\1\11\1\16\1\11"+ "\1\17\1\20\1\21\1\22\1\23\1\24\1\25\1\26"+ - "\20\11\1\27\1\11\1\30\4\11\1\20\5\11\1\31"+ - "\1\20\12\11\1\32\1\0\45\11\1\33\2\34\4\33"+ - "\1\35\12\33\17\36\1\34\1\33\1\36\2\33\1\34"+ - "\1\37\11\33\11\40\1\41\1\40\1\0\45\40\6\11"+ - "\1\15\1\11\1\16\1\42\1\17\1\43\1\21\25\11"+ + "\21\11\1\27\1\11\1\30\4\11\1\20\5\11\1\31"+ + "\1\20\12\11\1\32\1\0\46\11\1\33\2\34\4\33"+ + "\1\35\12\33\20\36\1\34\1\33\1\36\2\33\1\34"+ + "\1\37\11\33\11\40\1\41\1\40\1\0\46\40\6\11"+ + "\1\15\1\11\1\16\1\42\1\17\1\43\1\21\26\11"+ "\1\27\5\11\1\44\1\43\6\11\1\43\6\45\1\46"+ - "\1\45\1\47\1\45\1\17\46\45\5\50\1\51\14\50"+ - "\17\52\1\50\1\53\1\52\6\50\1\54\6\50\13\10"+ - "\1\55\44\10\1\55\77\0\1\56\53\0\1\57\47\0"+ + "\1\45\1\47\1\45\1\17\47\45\5\50\1\51\14\50"+ + "\20\52\1\50\1\53\1\52\6\50\1\54\6\50\13\10"+ + "\1\55\45\10\1\55\100\0\1\56\54\0\1\57\50\0"+ "\1\60\1\61\1\62\4\63\1\60\1\63\1\60\1\63"+ "\1\64\6\63\2\65\2\66\2\67\1\70\1\71\1\70"+ - "\1\72\1\73\1\74\1\73\1\75\1\76\1\61\1\63"+ - "\1\73\1\64\4\60\1\64\6\60\1\64\36\0\1\77"+ - "\23\0\2\34\36\0\1\34\4\0\1\34\13\0\2\36"+ - "\17\0\20\36\1\0\1\36\1\0\2\36\62\0\1\100"+ - "\32\0\17\52\2\0\1\52\37\0\17\53\2\0\1\53"+ - "\67\0\2\101\1\102\1\103\1\104\1\105\2\0\2\61"+ - "\36\0\1\61\21\0\1\106\36\0\1\106\17\0\61\107"+ - "\1\110\2\111\20\110\2\111\2\110\3\111\2\110\1\111"+ - "\1\110\1\111\2\110\1\111\17\110\1\112\2\113\20\112"+ - "\2\113\2\112\3\113\2\112\1\113\1\112\1\113\2\112"+ - "\1\113\17\112\54\0\1\114\1\115\3\0\5\116\1\0"+ - "\53\116\2\0\1\117\36\0\1\117\17\0\62\120\2\121"+ - "\20\120\2\121\2\120\3\121\2\120\1\121\1\120\1\121"+ - "\2\120\1\121\17\120\62\122\2\123\20\122\2\123\2\122"+ - "\3\123\2\122\1\123\1\122\1\123\2\122\1\123\17\122"+ - "\5\116\1\124\53\116\2\0\1\125\36\0\1\125\17\0"+ - "\62\126\2\127\20\126\2\127\2\126\3\127\2\126\1\127"+ - "\1\126\1\127\2\126\1\127\17\126\62\130\2\131\20\130"+ - "\2\131\2\130\3\131\2\130\1\131\1\130\1\131\2\130"+ - "\1\131\17\130"; + "\2\72\1\73\1\74\1\73\1\75\1\76\1\61\1\63"+ + "\1\73\1\64\4\60\1\64\6\60\1\64\37\0\1\77"+ + "\23\0\2\34\37\0\1\34\4\0\1\34\13\0\2\36"+ + "\17\0\21\36\1\0\1\36\1\0\2\36\63\0\1\100"+ + "\32\0\20\52\2\0\1\52\37\0\20\53\2\0\1\53"+ + "\51\0\1\101\16\0\2\102\1\103\1\104\1\105\1\106"+ + "\2\0\2\61\37\0\1\61\21\0\1\107\37\0\1\107"+ + "\17\0\62\110\1\111\2\112\20\111\2\112\2\111\3\112"+ + "\3\111\1\112\1\111\1\112\2\111\1\112\17\111\1\113"+ + "\2\114\20\113\2\114\2\113\3\114\3\113\1\114\1\113"+ + "\1\114\2\113\1\114\17\113\57\0\1\115\57\0\1\116"+ + "\1\117\3\0\5\120\1\0\54\120\2\0\1\121\37\0"+ + "\1\121\17\0\63\122\2\123\20\122\2\123\2\122\3\123"+ + "\3\122\1\123\1\122\1\123\2\122\1\123\17\122\63\124"+ + "\2\125\20\124\2\125\2\124\3\125\3\124\1\125\1\124"+ + "\1\125\2\124\1\125\17\124\22\0\20\115\2\0\1\115"+ + "\7\0\1\126\5\0\5\120\1\127\54\120\2\0\1\130"+ + "\37\0\1\130\17\0\63\131\2\132\20\131\2\132\2\131"+ + "\3\132\3\131\1\132\1\131\1\132\2\131\1\132\17\131"+ + "\63\133\2\134\20\133\2\134\2\133\3\134\3\133\1\134"+ + "\1\133\1\134\2\133\1\134\17\133"; private static int [] zzUnpackTrans() { - int [] result = new int[1813]; + int [] result = new int[1950]; int offset = 0; offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); return result; @@ -265,15 +275,15 @@ class _RegExLexer implements FlexLexer { private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = - "\6\0\2\1\2\11\1\1\2\11\1\3\1\1\12\11"+ - "\1\1\1\11\1\1\1\11\1\1\5\11\1\1\2\11"+ - "\1\3\2\11\2\1\2\11\1\1\1\15\1\11\2\1"+ - "\6\11\1\1\3\11\2\1\5\11\2\0\1\1\1\11"+ - "\4\1\2\11\1\0\1\1\2\11\2\1\2\11\2\1"+ - "\2\11"; + "\6\0\2\1\2\11\1\1\2\11\2\1\12\11\1\1"+ + "\1\11\1\1\1\11\1\1\5\11\1\1\2\11\1\1"+ + "\2\11\2\1\2\11\1\1\2\11\2\1\6\11\1\1"+ + "\3\11\2\1\2\11\1\0\3\11\2\0\1\1\1\11"+ + "\4\1\1\0\2\11\1\0\1\1\2\11\2\1\3\11"+ + "\2\1\2\11"; private static int [] zzUnpackAttribute() { - int [] result = new int[89]; + int [] result = new int[92]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; @@ -570,8 +580,6 @@ class _RegExLexer implements FlexLexer { int [] zzTransL = ZZ_TRANS; int [] zzRowMapL = ZZ_ROWMAP; int [] zzAttrL = ZZ_ATTRIBUTE; - int zzPushbackPosL = zzPushbackPos = -1; - boolean zzWasPushback; while (true) { zzMarkedPosL = zzMarkedPos; @@ -580,9 +588,8 @@ class _RegExLexer implements FlexLexer { zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; - zzState = zzLexicalState; + zzState = ZZ_LEXSTATE[zzLexicalState]; - zzWasPushback = false; zzForAction: { while (true) { @@ -597,14 +604,12 @@ class _RegExLexer implements FlexLexer { // store back cached positions zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; - zzPushbackPos = zzPushbackPosL; boolean eof = zzRefill(); // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; - zzPushbackPosL = zzPushbackPos; if (eof) { zzInput = YYEOF; break zzForAction; @@ -618,11 +623,7 @@ class _RegExLexer implements FlexLexer { zzState = zzNext; int zzAttributes = zzAttrL[zzState]; - if ( (zzAttributes & 2) == 2 ) - zzPushbackPosL = zzCurrentPosL; - if ( (zzAttributes & 1) == 1 ) { - zzWasPushback = (zzAttributes & 4) == 4; zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ( (zzAttributes & 8) == 8 ) break zzForAction; @@ -633,246 +634,250 @@ class _RegExLexer implements FlexLexer { // store back cached position zzMarkedPos = zzMarkedPosL; - if (zzWasPushback) - zzMarkedPos = zzPushbackPosL; switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 7: { if (yystate() != CLASS2) yypushstate(EMBRACED); return RegExpTT.LBRACE; } - case 62: break; + case 63: break; case 6: { return RegExpTT.GROUP_END; } - case 63: break; + case 64: break; case 36: + // lookahead expression with fixed base length + zzMarkedPos = zzStartRead + 1; { yypushstate(CLASS1); return RegExpTT.CLASS_BEGIN; } - case 64: break; + case 65: break; case 14: { return RegExpTT.STAR; } - case 65: break; + case 66: break; case 40: { return RegExpTT.ESC_CHARACTER; } - case 66: break; + case 67: break; case 28: { return commentMode ? com.intellij.psi.TokenType.WHITE_SPACE : RegExpTT.ESC_CHARACTER; } - case 67: break; + case 68: break; case 41: { return commentMode ? RegExpTT.CHARACTER : RegExpTT.REDUNDANT_ESCAPE; } - case 68: break; + case 69: break; case 37: { return RegExpTT.REDUNDANT_ESCAPE; } - case 69: break; + case 70: break; case 24: { return RegExpTT.COMMA; } - case 70: break; + case 71: break; case 57: { return RegExpTT.POS_LOOKBEHIND; } - case 71: break; + case 72: break; case 39: { return RegExpTT.BAD_OCT_VALUE; } - case 72: break; + case 73: break; case 10: { return commentMode ? com.intellij.psi.TokenType.WHITE_SPACE : RegExpTT.CTRL_CHARACTER; } - case 73: break; + case 74: break; case 30: { yypopstate(); yypushstate(EMBRACED); return RegExpTT.LBRACE; } - case 74: break; + case 75: break; case 49: { return StringEscapesTokenTypes.INVALID_UNICODE_ESCAPE_TOKEN; } - case 75: break; + case 76: break; case 58: { return RegExpTT.NEG_LOOKBEHIND; } - case 76: break; - case 61: + case 77: break; + case 62: { return RegExpTT.UNICODE_CHAR; } - case 77: break; + case 78: break; case 56: { if (xmlSchemaMode) { yypushback(1); return RegExpTT.CHAR_CLASS; } else return RegExpTT.CTRL; } - case 78: break; + case 79: break; case 35: { yybegin(OPTIONS); return RegExpTT.SET_OPTIONS; } - case 79: break; + case 80: break; case 12: { return RegExpTT.DOLLAR; } - case 80: break; + case 81: break; case 50: { yypopstate(); return RegExpTT.QUOTE_END; } - case 81: break; + case 82: break; case 53: { return RegExpTT.POS_LOOKAHEAD; } - case 82: break; + case 83: break; case 22: { yypopstate(); return RegExpTT.RBRACE; } - case 83: break; + case 84: break; case 3: { return RegExpTT.CHARACTER; } - case 84: break; + case 85: break; case 54: { return RegExpTT.NEG_LOOKAHEAD; } - case 85: break; + case 86: break; case 42: { return RegExpTT.ESC_CTRL_CHARACTER; } - case 86: break; + case 87: break; case 23: { return RegExpTT.NAME; } - case 87: break; + case 88: break; case 51: { return RegExpTT.ANDAND; } - case 88: break; + case 89: break; case 13: { return RegExpTT.QUEST; } - case 89: break; + case 90: break; case 44: { return RegExpTT.CHAR_CLASS; } - case 90: break; + case 91: break; case 17: { return RegExpTT.MINUS; } - case 91: break; - case 60: + case 92: break; + case 61: { return RegExpTT.COMMENT; } - case 92: break; + case 93: break; case 38: { return yystate() != CLASS2 ? RegExpTT.BACKREF : RegExpTT.ESC_CHARACTER; } - case 93: break; + case 94: break; case 16: { return RegExpTT.UNION; } - case 94: break; + case 95: break; + case 60: + { return RegExpTT.PYTHON_NAMED_GROUP; + } + case 96: break; case 45: { if (xmlSchemaMode) return RegExpTT.CHAR_CLASS; else return StringEscapesTokenTypes.INVALID_CHARACTER_ESCAPE_TOKEN; } - case 95: break; + case 97: break; case 55: { return RegExpTT.OCT_CHAR; } - case 96: break; + case 98: break; case 4: { return RegExpTT.DOT; } - case 97: break; + case 99: break; case 32: { yybegin(YYINITIAL); return RegExpTT.GROUP_END; } - case 98: break; + case 100: break; case 21: { return RegExpTT.NUMBER; } - case 99: break; + case 101: break; case 46: { yypushstate(PROP); return RegExpTT.PROPERTY; } - case 100: break; + case 102: break; case 18: { return commentMode ? com.intellij.psi.TokenType.WHITE_SPACE : RegExpTT.CHARACTER; } - case 101: break; + case 103: break; case 33: { handleOptions(); return RegExpTT.OPTIONS_OFF; } - case 102: break; + case 104: break; case 34: { yybegin(YYINITIAL); return RegExpTT.COLON; } - case 103: break; + case 105: break; case 25: { assert false : yytext(); } - case 104: break; + case 106: break; case 27: { yypopstate(); return RegExpTT.CLASS_END; } - case 105: break; + case 107: break; case 11: { return RegExpTT.CARET; } - case 106: break; + case 108: break; case 1: { handleOptions(); return RegExpTT.OPTIONS_ON; } - case 107: break; + case 109: break; case 29: { yypopstate(); yypushback(1); } - case 108: break; + case 110: break; case 43: { return yystate() != CLASS2 ? RegExpTT.BOUNDARY : RegExpTT.ESC_CHARACTER; } - case 109: break; + case 111: break; case 19: { if (commentMode) { yypushstate(COMMENT); return RegExpTT.COMMENT; } else return RegExpTT.CHARACTER; } - case 110: break; + case 112: break; case 59: { return RegExpTT.HEX_CHAR; } - case 111: break; + case 113: break; case 5: { return RegExpTT.GROUP_BEGIN; } - case 112: break; + case 114: break; case 8: { yypushstate(CLASS2); return RegExpTT.CLASS_BEGIN; } - case 113: break; + case 115: break; case 52: { return RegExpTT.NON_CAPT_GROUP; } - case 114: break; + case 116: break; case 9: { return StringEscapesTokenTypes.INVALID_CHARACTER_ESCAPE_TOKEN; } - case 115: break; + case 117: break; case 48: { return RegExpTT.BAD_HEX_VALUE; } - case 116: break; + case 118: break; case 2: { yypopstate(); return RegExpTT.COMMENT; } - case 117: break; + case 119: break; case 47: { yypushstate(QUOTED); return RegExpTT.QUOTE_BEGIN; } - case 118: break; + case 120: break; case 26: { yybegin(CLASS2); return RegExpTT.CHARACTER; } - case 119: break; + case 121: break; case 15: { return RegExpTT.PLUS; } - case 120: break; + case 122: break; case 20: { if (allowDanglingMetacharacters) { yypopstate(); yypushback(1); @@ -880,11 +885,11 @@ class _RegExLexer implements FlexLexer { return RegExpTT.BAD_CHARACTER; } } - case 121: break; + case 123: break; case 31: { yybegin(YYINITIAL); return RegExpTT.BAD_CHARACTER; } - case 122: break; + case 124: break; default: if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; diff --git a/RegExpSupport/src/org/intellij/lang/regexp/psi/RegExpGroup.java b/RegExpSupport/src/org/intellij/lang/regexp/psi/RegExpGroup.java index 7770f6ad4376..db6e81c0eae5 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/psi/RegExpGroup.java +++ b/RegExpSupport/src/org/intellij/lang/regexp/psi/RegExpGroup.java @@ -22,4 +22,6 @@ public interface RegExpGroup extends RegExpAtom { @Nullable RegExpPattern getPattern(); + + boolean isPythonNamedGroup(); } diff --git a/RegExpSupport/src/org/intellij/lang/regexp/psi/impl/RegExpGroupImpl.java b/RegExpSupport/src/org/intellij/lang/regexp/psi/impl/RegExpGroupImpl.java index 9b8fa67ece98..976fb2ba8fef 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/psi/impl/RegExpGroupImpl.java +++ b/RegExpSupport/src/org/intellij/lang/regexp/psi/impl/RegExpGroupImpl.java @@ -41,4 +41,8 @@ public class RegExpGroupImpl extends RegExpElementImpl implements RegExpGroup { final ASTNode node = getNode().findChildByType(RegExpElementTypes.PATTERN); return node != null ? (RegExpPattern)node.getPsi() : null; } + + public boolean isPythonNamedGroup() { + return getNode().findChildByType(RegExpTT.PYTHON_NAMED_GROUP) != null; + } } diff --git a/RegExpSupport/src/org/intellij/lang/regexp/regexp-lexer.flex b/RegExpSupport/src/org/intellij/lang/regexp/regexp-lexer.flex index 621fc89cf6e6..2b0455a747eb 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/regexp-lexer.flex +++ b/RegExpSupport/src/org/intellij/lang/regexp/regexp-lexer.flex @@ -205,6 +205,7 @@ HEX_CHAR=[0-9a-fA-F] "(?<=" { return RegExpTT.POS_LOOKBEHIND; } "(?" { return RegExpTT.PYTHON_NAMED_GROUP; } "(?" { yybegin(OPTIONS); return RegExpTT.SET_OPTIONS; } } diff --git a/RegExpSupport/src/org/intellij/lang/regexp/validation/RegExpAnnotator.java b/RegExpSupport/src/org/intellij/lang/regexp/validation/RegExpAnnotator.java index 52307d1cd58d..21e50a871722 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/validation/RegExpAnnotator.java +++ b/RegExpSupport/src/org/intellij/lang/regexp/validation/RegExpAnnotator.java @@ -30,12 +30,13 @@ import org.intellij.lang.regexp.RegExpLanguageHost; import org.intellij.lang.regexp.RegExpTT; import org.intellij.lang.regexp.psi.*; import org.intellij.lang.regexp.psi.impl.RegExpPropertyImpl; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class RegExpAnnotator extends RegExpElementVisitor implements Annotator { private AnnotationHolder myHolder; - public void annotate(PsiElement psiElement, AnnotationHolder holder) { + public void annotate(@NotNull PsiElement psiElement, @NotNull AnnotationHolder holder) { assert myHolder == null : "unsupported concurrent annotator invocation"; try { myHolder = holder; @@ -159,6 +160,12 @@ public final class RegExpAnnotator extends RegExpElementVisitor implements Annot } } } + if (group.isPythonNamedGroup()) { + RegExpLanguageHost host = findRegExpHost(group); + if (host == null || !host.supportsPythonNamedGroups()) { + myHolder.createErrorAnnotation(group, "This named group syntax is not supported"); + } + } } @Override From 60eaa298a63937d4592bd159571160d26802db61 Mon Sep 17 00:00:00 2001 From: peter Date: Sun, 21 Feb 2010 19:13:29 +0000 Subject: [PATCH 86/93] allow copying node text from compiler messages toolwindow (IDEA-27757) --- .../errorTreeView/NewErrorTreeViewPanel.java | 29 +++++++++++++++++-- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java b/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java index 1e56ad0dc092..d2ec4fb49caa 100644 --- a/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java +++ b/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java @@ -21,9 +21,11 @@ import com.intellij.ide.errorTreeView.impl.ErrorTreeViewConfiguration; import com.intellij.ide.errorTreeView.impl.ErrorViewTextExporter; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.ide.CopyPasteManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.IconLoader; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.Navigatable; import com.intellij.ui.AutoScrollToSourceHandler; @@ -42,11 +44,12 @@ import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import java.awt.*; +import java.awt.datatransfer.StringSelection; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.List; -public class NewErrorTreeViewPanel extends JPanel implements DataProvider, OccurenceNavigator, MutableErrorTreeView { +public class NewErrorTreeViewPanel extends JPanel implements DataProvider, OccurenceNavigator, MutableErrorTreeView, CopyProvider { protected static final Logger LOG = Logger.getInstance("#com.intellij.ide.errorTreeView.NewErrorTreeViewPanel"); private String myProgressText = ""; private final boolean myCreateExitAction; @@ -158,10 +161,29 @@ public class NewErrorTreeViewPanel extends JPanel implements DataProvider, Occur Disposer.dispose(myBuilder); } + public void performCopy(DataContext dataContext) { + final ErrorTreeNodeDescriptor descriptor = getSelectedNodeDescriptor(); + if (descriptor != null) { + final String[] lines = descriptor.getElement().getText(); + CopyPasteManager.getInstance().setContents(new StringSelection(StringUtil.join(lines, "\n"))); + } + } + + public boolean isCopyEnabled(DataContext dataContext) { + return getSelectedNodeDescriptor() != null; + } + + public boolean isCopyVisible(DataContext dataContext) { + return true; + } + public Object getData(String dataId) { + if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) { + return this; + } if (PlatformDataKeys.NAVIGATABLE.is(dataId)) { final NavigatableMessageElement selectedMessageElement = getSelectedMessageElement(); - return selectedMessageElement != null? selectedMessageElement.getNavigatable() : null; + return selectedMessageElement != null ? selectedMessageElement.getNavigatable() : null; } else if (PlatformDataKeys.HELP_ID.is(dataId)) { return myHelpId; @@ -174,7 +196,7 @@ public class NewErrorTreeViewPanel extends JPanel implements DataProvider, Occur } else if (CURRENT_EXCEPTION_DATA_KEY.is(dataId)) { NavigatableMessageElement selectedMessageElement = getSelectedMessageElement(); - return selectedMessageElement != null? selectedMessageElement.getData() : null; + return selectedMessageElement != null ? selectedMessageElement.getData() : null; } return null; } @@ -289,6 +311,7 @@ public class NewErrorTreeViewPanel extends JPanel implements DataProvider, Occur if (getData(PlatformDataKeys.NAVIGATABLE.getName()) != null) { group.add(ActionManager.getInstance().getAction(IdeActions.ACTION_EDIT_SOURCE)); } + group.add(ActionManager.getInstance().getAction(IdeActions.ACTION_COPY)); addExtraPopupMenuActions(group); ActionPopupMenu menu = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.COMPILER_MESSAGES_POPUP, group); From 8e28929db2dce6b92d037bf99079db9ba8470a76 Mon Sep 17 00:00:00 2001 From: peter Date: Sun, 21 Feb 2010 19:17:06 +0000 Subject: [PATCH 87/93] show full exception stacktrace on internal groovyc errors (on IDEA-52410) --- .../groovy/compiler/rt/GroovyCompilerWrapper.java | 7 ++++++- .../groovy/compiler/GroovycOSProcessHandler.java | 10 +++++----- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovyCompilerWrapper.java b/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovyCompilerWrapper.java index d9e22c303402..821950cb45d3 100644 --- a/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovyCompilerWrapper.java +++ b/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovyCompilerWrapper.java @@ -28,6 +28,8 @@ import org.codehaus.groovy.tools.GroovyClass; import java.io.File; import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; import java.util.*; @@ -154,7 +156,10 @@ public class GroovyCompilerWrapper { } else if (forStubs) { addMessageWithoutLocation(collector, "Groovyc stub generation failed: " + exception.getMessage(), false); } else { - addMessageWithoutLocation(collector, exception.getMessage(), true); + final StringWriter writer = new StringWriter(); + //noinspection IOResourceOpenedButNotSafelyClosed + exception.printStackTrace(new PrintWriter(writer)); + addMessageWithoutLocation(collector, writer.toString(), true); } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovycOSProcessHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovycOSProcessHandler.java index b1d75ce67cef..4fd26dc4080f 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovycOSProcessHandler.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovycOSProcessHandler.java @@ -65,15 +65,15 @@ public class GroovycOSProcessHandler extends OSProcessHandler { LOG.debug("Received from groovyc: " + text); } - text = text.trim(); + final String trimmed = text.trim(); - if (text.startsWith(GroovycRunner.PRESENTABLE_MESSAGE)) { - myContext.getProgressIndicator().setText(text.substring(GroovycRunner.PRESENTABLE_MESSAGE.length())); + if (trimmed.startsWith(GroovycRunner.PRESENTABLE_MESSAGE)) { + myContext.getProgressIndicator().setText(trimmed.substring(GroovycRunner.PRESENTABLE_MESSAGE.length())); return; } - if (GroovycRunner.CLEAR_PRESENTABLE.equals(text)) { + if (GroovycRunner.CLEAR_PRESENTABLE.equals(trimmed)) { myContext.getProgressIndicator().setText(GROOVY_COMPILER_IN_OPERATION); return; } @@ -202,7 +202,7 @@ public class GroovycOSProcessHandler extends OSProcessHandler { outputBuffer.indexOf(START_MARKER), outputBuffer.indexOf(END_MARKER) + END_MARKER.length()); - return text; + return text.trim(); } @Nullable From d5a02bccaf71bd14efd7e89f1bef33c1b5908745 Mon Sep 17 00:00:00 2001 From: peter Date: Sun, 21 Feb 2010 20:21:16 +0000 Subject: [PATCH 88/93] groovy ASTTransformation files should be marked as resources. do it semi-automatically (on IDEA-52410) --- .../groovy/compiler/GroovyCompiler.java | 37 ++++++++++++++++++- .../compiler/GroovyCompilerConfiguration.java | 5 +++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java index 9b8530a36c4c..b4c1067d7981 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java @@ -16,6 +16,7 @@ package org.jetbrains.plugins.groovy.compiler; +import com.intellij.compiler.CompilerConfiguration; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompileScope; @@ -27,19 +28,26 @@ import com.intellij.openapi.projectRoots.JavaSdkType; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ContentIterator; import com.intellij.openapi.roots.ModuleRootManager; +import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.roots.ui.configuration.ClasspathEditor; import com.intellij.openapi.roots.ui.configuration.ModulesConfigurator; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.*; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiElementVisitor; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiManager; +import com.intellij.psi.search.FilenameIndex; +import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.containers.FactoryMap; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.GroovyBundle; import org.jetbrains.plugins.groovy.GroovyFileType; import org.jetbrains.plugins.groovy.GroovyFileTypeLoader; +import org.jetbrains.plugins.groovy.GroovyIcons; import org.jetbrains.plugins.groovy.config.GroovyConfigUtils; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; @@ -55,6 +63,7 @@ import java.util.*; public class GroovyCompiler extends GroovyCompilerBase { private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.compiler.GroovyCompiler"); + private static final String AST_TRANSFORM_FILE_NAME = "org.codehaus.groovy.transform.ASTTransformation"; public GroovyCompiler(Project project) { super(project); @@ -235,7 +244,33 @@ public class GroovyCompiler extends GroovyCompilerBase { return false; } + final GroovyCompilerConfiguration configuration = GroovyCompilerConfiguration.getInstance(myProject); + if (!configuration.transformsOk && needTransformCopying(compileScope)) { + final int result = Messages.showYesNoDialog(myProject, + "You seem to have global Groovy AST transformations defined in your project,\n" + + "but they won't be applied to your code because they are not marked as compiler resources.\n" + + "Do you want to add them to compiler resource list?\n" + + "(you can do it yourself later in Settings | Compiler | Resource patterns)", "AST Transformations found", + GroovyIcons.GROOVY_ICON_32x32); + if (result == 0) { + CompilerConfiguration.getInstance(myProject).addResourceFilePattern(AST_TRANSFORM_FILE_NAME); + } else { + configuration.transformsOk = true; + } + } + return true; } + private boolean needTransformCopying(CompileScope compileScope) { + final CompilerConfiguration configuration = CompilerConfiguration.getInstance(myProject); + final ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex(); + for (VirtualFile file : FilenameIndex.getVirtualFilesByName(myProject, AST_TRANSFORM_FILE_NAME, GlobalSearchScope.projectScope(myProject))) { + if (compileScope.belongs(file.getUrl()) && index.isInSource(file) && !configuration.isResourceFile(file)) { + return true; + } + } + return false; + } + } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompilerConfiguration.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompilerConfiguration.java index dfc2534355c8..6690eb562468 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompilerConfiguration.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompilerConfiguration.java @@ -37,12 +37,14 @@ import org.jdom.Element; public class GroovyCompilerConfiguration implements PersistentStateComponent, Disposable { private String myHeapSize = "400"; private boolean myUseGroovycStubs = false; + public boolean transformsOk = false; private final ExcludedEntriesConfiguration myExcludeFromStubGeneration = new ExcludedEntriesConfiguration(); public MyStateBean getState() { final MyStateBean bean = new MyStateBean(); bean.heapSize = myHeapSize; bean.useGroovycStubs = myUseGroovycStubs; + bean.transformsOk = transformsOk; myExcludeFromStubGeneration.writeExternal(bean.excludes); return bean; } @@ -58,6 +60,7 @@ public class GroovyCompilerConfiguration implements PersistentStateComponent Date: Sun, 21 Feb 2010 21:14:43 +0000 Subject: [PATCH 89/93] qualify all class names in groovy evaluation fragment (IDEA-25396) --- .../debugger/GroovyCodeFragmentFactory.java | 7 +++++++ .../GroovyDebuggerEvaluatorTest.groovy | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java index cff9590d02fb..3735eeaac2a6 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java @@ -183,6 +183,13 @@ public class GroovyCodeFragmentFactory implements CodeFragmentFactory { } parameters.put(name, value); } + + if (resolved instanceof PsiClass) { + String qName = ((PsiClass)resolved).getQualifiedName(); + if (qName != null && qName.contains(".") && !referenceExpression.isQualified()) { + replaceWithReference(referenceExpression, qName); + } + } } @Override diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyDebuggerEvaluatorTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyDebuggerEvaluatorTest.groovy index 702c2e7ae814..a2898ce49b07 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyDebuggerEvaluatorTest.groovy +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyDebuggerEvaluatorTest.groovy @@ -32,8 +32,26 @@ a++""", "[a:this.a] -> a" } + public void testQualifyClassNames() throws Exception { + myFixture.addFileToProject("com/Foo.groovy", """ +package com +class Foo { static bar = 2 }""") + + def bar = myFixture.addFileToProject("com/Bar.groovy", """ +package com +println 2""") + + myFixture.configureFromExistingVirtualFile bar.virtualFile + + evaluates "Foo.bar", "[:] -> com.Foo.bar" + } + private void evaluates(String text, String expression, String expected) throws IOException { myFixture.configureByText("_.groovy", text); + evaluates(expression, expected) + } + + private def evaluates(String expression, String expected) { def context = myFixture.file.findElementAt(myFixture.editor.caretModel.offset); def pair = GroovyCodeFragmentFactory.externalParameters(expression, context) From f62e867cb2533d5250c590ce95fbf792991c4654 Mon Sep 17 00:00:00 2001 From: Bas Leijdekkers Date: Mon, 22 Feb 2010 00:39:24 +0100 Subject: [PATCH 90/93] http://ea.jetbrains.com/browser/ea_problems/18792 IDEA-52407 (Quickfix 'add braces' for Control flow without braces throws exception) --- ...lFlowStatementWithoutBracesInspection.java | 24 +++++++------------ 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/style/ControlFlowStatementWithoutBracesInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/style/ControlFlowStatementWithoutBracesInspection.java index bbf4c6d2297c..f3cda82c55ed 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/style/ControlFlowStatementWithoutBracesInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/style/ControlFlowStatementWithoutBracesInspection.java @@ -75,23 +75,15 @@ public class ControlFlowStatementWithoutBracesInspection final PsiIfStatement ifStatement = (PsiIfStatement)statement; if ("if".equals(elementText)) { statementWithoutBraces = ifStatement.getThenBranch(); - // special casing to avoid "else" on new line - final PsiElement[] children = ifStatement.getChildren(); - final StringBuilder newStatementText = new StringBuilder(); - for (PsiElement child : children) { - if (child instanceof PsiWhiteSpace) { - continue; - } - if (child != statementWithoutBraces) { - newStatementText.append(child.getText()); - } else { - newStatementText.append("{\n"); - newStatementText.append(child.getText()); - newStatementText.append("\n}"); - } + if (statementWithoutBraces == null) { + return; + } + final PsiElement nextSibling = + statementWithoutBraces.getNextSibling(); + if (nextSibling instanceof PsiWhiteSpace) { + // to avoid "else" on new line + nextSibling.delete(); } - replaceStatement(ifStatement, newStatementText.toString()); - return; } else { statementWithoutBraces = ifStatement.getElseBranch(); } From a53013eeaa242ac3132dac86d13bedc667204463 Mon Sep 17 00:00:00 2001 From: Roman Chernyatchik Date: Mon, 22 Feb 2010 11:03:17 +0300 Subject: [PATCH 91/93] actions attached to generators updated accroding Rails 3.0 generators names --- .../openapi/util/text/StringUtil.java | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/platform/util/src/com/intellij/openapi/util/text/StringUtil.java b/platform/util/src/com/intellij/openapi/util/text/StringUtil.java index 0fe7ac86fa17..4ed80c6f3cd4 100644 --- a/platform/util/src/com/intellij/openapi/util/text/StringUtil.java +++ b/platform/util/src/com/intellij/openapi/util/text/StringUtil.java @@ -581,20 +581,29 @@ public class StringUtil { return suggestion + "s"; } - @NotNull public static String capitalizeWords(@NotNull String text, boolean allWords) { - StringTokenizer tokenizer = new StringTokenizer(text); - String out = ""; - String delim = ""; + @NotNull public static String capitalizeWords(@NotNull String text, + boolean allWords) { + return capitalizeWords(text, " \t\n\r\f", allWords, false); + } + + @NotNull public static String capitalizeWords(@NotNull String text, + @NotNull String tokenizerDelim, + boolean allWords, + boolean leaveOriginalDelims) { + final StringTokenizer tokenizer = new StringTokenizer(text, tokenizerDelim, leaveOriginalDelims); + final StringBuilder out = new StringBuilder(); boolean toCapitalize = true; while (tokenizer.hasMoreTokens()) { - String word = tokenizer.nextToken(); - out += delim + (toCapitalize ? capitalize(word) : word); - delim = " "; + final String word = tokenizer.nextToken(); + if (!leaveOriginalDelims && out.length() > 0) { + out.append(' '); + } + out.append(toCapitalize ? capitalize(word) : word); if (!allWords) { toCapitalize = false; } } - return out; + return out.toString(); } public static String decapitalize(String s) { From 4b265f889da17947b5ecdfc747cabdfd886bff0e Mon Sep 17 00:00:00 2001 From: "Kirill.Safonov" Date: Mon, 22 Feb 2010 17:26:31 +0300 Subject: [PATCH 92/93] create web project wizard (in progress) + minor fixes --- .../ide/util/treeView/AbstractTreeBuilder.java | 1 + .../intellij/ide/wizard/AbstractWizardEx.java | 18 +++++++++++++++++- .../ide/wizard/AbstractWizardStepEx.java | 14 ++++++++++++-- .../platform/NewDirectoryProjectDialog.java | 2 +- 4 files changed, 31 insertions(+), 4 deletions(-) diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java index 354b9c02af71..fa6777ff4a20 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java @@ -406,6 +406,7 @@ public class AbstractTreeBuilder implements Disposable { @NotNull public final Set getSelectedElements() { + if (isDisposed()) return Collections.emptySet(); return getUi().getSelectedElements(); } diff --git a/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardEx.java b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardEx.java index 6a569625c1ed..b78a4b65304f 100644 --- a/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardEx.java +++ b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardEx.java @@ -18,8 +18,11 @@ package com.intellij.ide.wizard; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; +import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.wm.IdeFocusManager; import org.jetbrains.annotations.Nullable; +import javax.swing.*; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -112,7 +115,12 @@ public class AbstractWizardEx extends AbstractWizard { protected void updateStep() { super.updateStep(); updateButtons(); - setTitle(myTitle + ": " + getCurrentStepObject().getTitle()); + final AbstractWizardStepEx step = getCurrentStepObject(); + setTitle(myTitle + ": " + step.getTitle()); + final JComponent toFocus = step.getPreferredFocusedComponent(); + if (toFocus != null) { + IdeFocusManager.findInstanceByComponent(getWindow()).requestFocus(toFocus, true); + } } private void updateButtons() { @@ -129,4 +137,12 @@ public class AbstractWizardEx extends AbstractWizard { } return true; } + + @Override + protected void dispose() { + super.dispose(); + for (AbstractWizardStepEx step : mySteps) { + Disposer.dispose(step); + } + } } diff --git a/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardStepEx.java b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardStepEx.java index d1fbd812ee25..8950b53a95e7 100644 --- a/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardStepEx.java +++ b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardStepEx.java @@ -16,13 +16,15 @@ package com.intellij.ide.wizard; +import com.intellij.openapi.Disposable; import com.intellij.util.EventDispatcher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; +import java.awt.*; -public abstract class AbstractWizardStepEx implements Step { +public abstract class AbstractWizardStepEx implements Step, Disposable { protected enum CommitType { Prev, Next, Finish @@ -46,8 +48,9 @@ public abstract class AbstractWizardStepEx implements Step { public final void _commitPrev() throws CommitStepException { commit(CommitType.Prev); } + public final void _commit(boolean finishChosen) throws CommitStepException { - commit(finishChosen ? CommitType.Finish : CommitType.Next); + commit(finishChosen ? CommitType.Finish : CommitType.Next); } public void addStepListener(Listener listener) { @@ -86,4 +89,11 @@ public abstract class AbstractWizardStepEx implements Step { public String getTitle() { return myTitle; } + + public void dispose() { + } + + @Nullable + public abstract JComponent getPreferredFocusedComponent(); + } diff --git a/platform/platform-impl/src/com/intellij/platform/NewDirectoryProjectDialog.java b/platform/platform-impl/src/com/intellij/platform/NewDirectoryProjectDialog.java index da3416d95878..64eb4d849083 100644 --- a/platform/platform-impl/src/com/intellij/platform/NewDirectoryProjectDialog.java +++ b/platform/platform-impl/src/com/intellij/platform/NewDirectoryProjectDialog.java @@ -110,7 +110,7 @@ public class NewDirectoryProjectDialog extends DialogWrapper { } } - private static String getBaseDir() { + public static String getBaseDir() { final String lastProjectLocation = GeneralSettings.getInstance().getLastProjectLocation(); if (lastProjectLocation != null) { return lastProjectLocation.replace('/', File.separatorChar); From 086d32914fd27aacc04cbb20bab65a25852528a7 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 22 Feb 2010 23:12:06 +0000 Subject: [PATCH 93/93] don't suggest to reload IDEA on groovy library change --- plugins/groovy/src/META-INF/plugin.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/groovy/src/META-INF/plugin.xml b/plugins/groovy/src/META-INF/plugin.xml index 08aa0daece2a..3b5a010b90e2 100644 --- a/plugins/groovy/src/META-INF/plugin.xml +++ b/plugins/groovy/src/META-INF/plugin.xml @@ -483,9 +483,9 @@ org.jetbrains.plugins.groovy.codeInspection.local.GroovyUnusedImportsPassFactory - + org.jetbrains.plugins.groovy.annotator.intentions.dynamic.DynamicManager org.jetbrains.plugins.groovy.annotator.intentions.dynamic.DynamicManagerImpl